项目记录:利用Redis实现缓存以提升查询效率

一、概述

当我们查询所有数据时,如果缓存中没有,则去数据库查询,如果有,直接查缓存的数据就行。注意定期更新缓存数据。

二、主体代码

java 复制代码
    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缓存后,查询效率明显提升。

相关推荐
小兜全糖(xdqt)2 小时前
pyspark 从postgresql读取数据
数据库·postgresql
姓刘的哦4 小时前
Qt中的QWebEngineView
数据库·c++·qt
心随_风动4 小时前
Ubuntu 文件复制大师:精通cp命令完整指南
数据库·ubuntu·postgresql
不要再敲了4 小时前
JDBC从入门到面试:全面掌握Java数据库连接技术
java·数据库·面试
无敌的神原秋人5 小时前
关于Redis不同序列化压缩性能的对比
java·redis·缓存
恣艺7 小时前
Redis列表(List):实现队列/栈的利器,底层原理与实战
数据库·redis·list
秋难降8 小时前
零基础学习SQL(十一):SQL 索引结构|从 B+Tree 到 Hash,面试常问的 “为啥选 B+Tree” 有答案了
数据库·后端·mysql
代码的余温8 小时前
Linux内核调优实战指南
linux·服务器·数据库
almighty278 小时前
C# DataGridView表头自定义设置全攻略
数据库·c#·winform·datagridview·自定义表头
ljh5746491198 小时前
mysql 必须在逗号分隔字符串和JSON字段之间二选一,怎么选
数据库·mysql·json