【发布时间】: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