当我们查询所有数据时,如果缓存中没有,则去数据库查询,如果有,直接查缓存的数据就行。注意定期更新缓存数据。
private static final String ROOM_SCHEDULES_HASH = "RoomSchedules";
@Override
public 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缓存后,查询效率明显提升。