【问题标题】:How to use @Cacheable with redis using spring boot如何使用 Spring Boot 将 @Cacheable 与 redis 一起使用
【发布时间】:2020-12-29 08:39:45
【问题描述】:

我正在尝试使用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 任何帮助将不胜感激。

【问题讨论】:

    标签: java spring-boot redis jedis


    【解决方案1】:

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

    【讨论】:

    • 谢谢@Adam - 那我怎么把一些数据放进去呢?
    • 基本上注释为@Cacheable 的方法应该在其主体内获取/计算/获取数据(在您的情况下在RedisService.getStudentCache() 内)。通常是一些繁重的操作。如果缓存数据需要更改,则与其关联的缓存条目应失效,即通过@CacheEvict / @CachePut 或直接通过CacheManager &amp; Cache bean。一般来说,缓存条目的失效频率应该比访问缓存数据的频率低得多,否则缓存就没有意义了。在这种情况下,也许缓存不是您需要的。
    猜你喜欢
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 2018-08-07
    • 2021-01-02
    • 2020-03-09
    • 1970-01-01
    • 2020-11-02
    • 1970-01-01
    相关资源
    最近更新 更多