如何使用Spring Boot在Redis中使用@Cacheable

问题描述

我正在尝试使用Redis实现哈希映射,但是我想自己控制密钥,因此我实现了以下服务类。

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