简体   繁体   English

如何使用 Spring Boot 将 @Cacheable 与 redis 一起使用

[英]How to use @Cacheable with redis using spring boot

I am trying to implement hashmap using redis but I would like to control the key myself, so I have implemented following service class.我正在尝试使用 redis 实现 hashmap,但我想自己控制密钥,所以我实现了以下服务类。

@Slf4j
@Service
public class RedisService {
    Map<Long, Student> studentMap = new HashMap<>();
    @Cacheable(cacheNames = "studentCache")
    public Map<Long, Student> getStudentCache(){
        return studentMap;
    }
}

my pojo class is我的 pojo 课是

@Data
public class Student implements Serializable {
    private static final long serialVersionUID = -2722504679276149008L;
    public enum Gender {
        MALE, FEMALE
    }
    private Long id;
    private String name;
    private Gender gender;
    private int grade;

}

and the data loader和数据加载器

@Slf4j
@Component
public class DataLoader implements CommandLineRunner {

    @Autowired
    RedisService redisService;

    @Override
    public void run(String... args) {
      log.info("================ loading data now ========================");
        Student student = getStudent();
        redisService.getStudentCache().put(student.getId(), student);
        System.out.println("student is "+redisService.getStudentCache().get(student.getId()));
        log.info("================= program ends ==============");
    }

    private Student getStudent() {
        Student student = new Student();
        student.setId(ThreadLocalRandom.current().nextLong());
        student.setName("first last");
        student.setGender(Student.Gender.MALE);
        student.setGrade(85);
        return student;
    }
}

Main class主班

@EnableCaching
@SpringBootApplication
public class DemoApplication {

    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }

}

I have successfull connection with redis but it does not seems to be putting anything in the cache.我已成功与 redis 连接,但似乎没有将任何内容放入缓存中。 When I run the program I got following message as outcome.当我运行程序时,我收到以下消息作为结果。

2020-09-10 15:26:37.605  INFO 28540 --- [           main] c.w.s.components.DataLoader              : ================ loading data now ========================
student is null
2020-09-10 15:26:38.295  INFO 28540 --- [           main] c.w.s.components.DataLoader              : ================= program ends ==============

So I am not sure why student is returning NULL any help would be appreciated.所以我不确定为什么学生会返回NULL任何帮助将不胜感激。

Cache is being initialized when you access cached data for the first time (to be specific - data for the specific caching key - in this case constant).当您第一次访问缓存数据时,缓存正在初始化(具体来说 - 特定缓存键的数据 - 在这种情况下为常量)。 In your case it's happenning at the end of first call to redisService.getStudentCache() .在您的情况下,它发生在第一次调用redisService.getStudentCache() At that time studentMap is an empty map, hence empty map is being cached.当时studentMap是一个空地图,因此正在缓存空地图。 The fact that moment later you add there some entry (via .put(student.getId(), student); ) doesn't matter because caching system is using its own copy of cached map, hence null on getting value from this map.稍后您在那里添加一些条目(通过.put(student.getId(), student); )这一事实并不重要,因为缓存系统正在使用它自己的缓存映射副本,因此从该映射获取值时为 null。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM