项目记录:利用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缓存后,查询效率明显提升。

相关推荐
我是唐青枫1 小时前
终于不用手搓两级缓存了!C#.NET HybridCache 详解:L1 L2、标签失效与防击穿实战
redis·缓存·c#·.net
2301_809204701 小时前
JavaScript中严格模式use-strict对引擎解析的辅助.txt
jvm·数据库·python
zjy277771 小时前
mysql如何选择合适的索引类型_mysql索引设计实战
jvm·数据库·python
笨蛋不要掉眼泪2 小时前
Mysql架构揭秘:update语句的执行流程
数据库·mysql·架构
万邦科技Lafite2 小时前
京东item_get接口实战案例:实时商品价格监控全流程解析
java·开发语言·数据库·python·开放api·淘宝开放平台
秋92 小时前
ruoyi项目更换为mysql9.7.0数据库
数据库
Andya_net3 小时前
MySQL | MySQL 8.0 权限管理实践-精确赋予库、表只读等权限
android·数据库·mysql
筑梦之路4 小时前
harbor数据库报错权限异常如何处理——筑梦之路
数据库·harbor
czlczl200209254 小时前
理解 MySQL 行锁:两阶段锁协议与热点更新优化
数据库·mysql
AllData公司负责人5 小时前
通过Postgresql同步到Doris,全视角演示AllData数据中台核心功能效果,涵盖:数据入湖仓,数据同步,数据处理,数据服务,BI可视化驾驶舱
java·大数据·数据库·数据仓库·人工智能·python·postgresql