一、概述
当我们查询所有数据时,如果缓存中没有,则去数据库查询,如果有,直接查缓存的数据就行。注意定期更新缓存数据。
二、主体代码
private static final String ROOM_SCHEDULES_HASH = "RoomSchedules";@Overridepublic List<RoomSchedule> getAllRoomSchedules() {BoundHashOperations<String, String, String> hashOps = stringRedisTemplate.boundHashOps(ROOM_SCHEDULES_HASH);if (hashOps.size() == 0) {List<RoomSchedule> roomSchedules = roomScheduleMapper.getAllRoomSchedules();for (RoomSchedule roomSchedule : roomSchedules) {ObjectMapper objectMapper = new ObjectMapper();try {String json = objectMapper.writeValueAsString(roomSchedule);hashOps.put(roomSchedule.getId().toString(), json);} catch (Exception e) {e.printStackTrace();}}stringRedisTemplate.expire(ROOM_SCHEDULES_HASH, 3, TimeUnit.MINUTES); // 设置有效期为三分钟return roomSchedules;} else {Map<String, String> entries = hashOps.entries();List<RoomSchedule> roomSchedules = new ArrayList<>();for (String json : entries.values()) {try {ObjectMapper objectMapper = new ObjectMapper();RoomSchedule roomSchedule = objectMapper.readValue(json, RoomSchedule.class);roomSchedules.add(roomSchedule);} catch (Exception e) {e.printStackTrace();}}return roomSchedules;}}
BoundHashOperations是绑定键值的方法,意味着之后的操作都是对此键进行操作。
ObjectMapper类提供了一系列json序列化和反序列化的操作。
缓存更新操作是通过设置TTL有效期来实现的。
三、效果实现
可以看到引入Redis缓存后,查询效率明显提升。