Java 如何使用spring boot将@Cacheable与redis一起使用
我试图使用redis实现hashmap,但我想自己控制密钥,所以我实现了以下服务类Java 如何使用spring boot将@Cacheable与redis一起使用,java,spring-boot,redis,jedis,Java,Spring Boot,Redis,Jedis,我试图使用redis实现hashmap,但我想自己控制密钥,所以我实现了以下服务类 @Slf4j @Service public class RedisService { Map<Long, Student> studentMap = new HashMap<>(); @Cacheable(cacheNames = "studentCache") public Map<Long, Student> getStuden
@Slf4j
@Service
public class RedisService {
Map<Long, Student> studentMap = new HashMap<>();
@Cacheable(cacheNames = "studentCache")
public Map<Long, Student> getStudentCache(){
return studentMap;
}
}
和数据加载器
@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;
}
}
主类
@EnableCaching
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
我已成功连接redis,但它似乎没有将任何内容放入缓存。当我运行程序时,我得到以下消息作为结果
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 ==============
因此,我不确定为什么student返回NULL任何帮助都将不胜感激。当您第一次访问缓存数据时,缓存正在初始化(具体来说,是特定缓存键的数据,在本例中为常量)。在您的例子中,它发生在对
redisService.getStudentCache()
的第一次调用结束时。当时studentMap
是一个空映射,因此正在缓存空映射。稍后您添加了一些条目(通过.put(student.getId(),student);
)这一事实并不重要,因为缓存系统正在使用自己的缓存映射副本,因此,从该映射中获取值时为空。谢谢@Adam-那么我如何将一些数据放入其中呢?基本上,注释为@Cacheable
的方法应该在其主体内获取/计算/获取数据(在您的情况下,在RedisService.getStudentCache()中)。通常是一些繁重的工作。如果缓存数据需要更改,则与之关联的缓存项应无效,即通过@cacheexecute
/@CachePut
或直接通过CacheManager&cache bean
。一般来说,缓存项的失效频率应该大大低于访问缓存数据的频率,否则就没有必要使用缓存。在这种情况下,缓存可能不是您所需要的。
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 ==============