I am trying to implement hashmap using redis but I would like to control the key myself, so I have implemented following service class.
@Slf4j@Servicepublic class RedisService { Map<Long, Student> studentMap = new HashMap<>(); @Cacheable(cacheNames = "studentCache") public Map<Long, Student> getStudentCache(){ return studentMap; }}
my pojo class is
@Datapublic 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;}
and the data loader
@Slf4j@Componentpublic 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; }}
Main class
@EnableCaching@SpringBootApplicationpublic class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}
I have successfull connection with redis but it does not seems to be putting anything in the cache. When I run the program I got following message as outcome.
2020-09-10 15:26:37.605 INFO 28540 --- [ main] c.w.s.components.DataLoader : ================ loading data now ========================student is null2020-09-10 15:26:38.295 INFO 28540 --- [ main] c.w.s.components.DataLoader : ================= program ends ==============
So I am not sure why student is returning NULL any help would be appreciated.