繁体   English   中英

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

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

我正在尝试使用 redis 实现 hashmap,但我想自己控制密钥,所以我实现了以下服务类。

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

我的 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;

}

和数据加载器

@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 ==============

所以我不确定为什么学生会返回NULL任何帮助将不胜感激。

当您第一次访问缓存数据时,缓存正在初始化(具体来说 - 特定缓存键的数据 - 在这种情况下为常量)。 在您的情况下,它发生在第一次调用redisService.getStudentCache() 当时studentMap是一个空地图,因此正在缓存空地图。 稍后您在那里添加一些条目(通过.put(student.getId(), student); )这一事实并不重要,因为缓存系统正在使用它自己的缓存映射副本,因此从该映射获取值时为 null。

暂无
暂无

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

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