8.集成缓存数据库Redis

    技术2025-07-26  12

    1.Redis简介 Redis是一个基于内存的、单线程、高性能的key-value型数据库,读写性能优异。Redis支持丰富的数据类型,包括string(字符串)、list(链表)、set(集合)、zset(有序集合)和hash(哈希类型)。 在SpringBoot中提供了强大的基于注解的缓存支持,可以通过注解配置的方式,低侵入地给原有Spring应用增加缓存功能,提高数据访问性能。

    2.引入依赖 复制一份“集成MyBatis”的项目代码,修改项目名称为redis,并在pom.xml文件中添加集成Redis所需要的dependency。

    <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.7.3</version> </dependency>

    3.添加配置 在application.properties文件中添加如下配置信息。

    ############################################################ # # redis配置 # ############################################################ ### 默认redis数据库为db0 spring.redis.database = 0 ### 服务器地址,默认为localhost spring.redis.host = 127.0.0.1 ### 链接端口,默认为6379 spring.redis.port = 6379

    4.序列化po对象 所有po对象都要实现Serializable接口,如下面代码所示。

    @Data @NoArgsConstructor @AllArgsConstructor @ToString public class User implements Serializable{ private Integer id; private String name; private String email; }

    5.redis缓存工具类开发 在项目目录“/src/main/java/com/leichuangkj/redis”下新建utils目录,并在utils目录下新建RedisUtil类,具体代码如下。

    public class RedisUtil { /** * @description 指定缓存失效时间 * * @param key 键 * @param time 时间(秒) * @return boolean */ public static boolean expire(RedisTemplate<String, Object> redisTemplate, String key, long time) { try { if (time > 0) { redisTemplate.expire(key, time, TimeUnit.SECONDS); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 根据key获取过期时间 * * @param key 键(不能为null) * @return long 时间(秒) 返回0代表为永久有效 */ public static long getExpire(RedisTemplate<String, Object> redisTemplate, String key) { return redisTemplate.getExpire(key, TimeUnit.SECONDS); } /** * @description 判断key是否存在 * * @param key 键 * @return boolean(true:存在 false:不存在) */ public static boolean hasKey(RedisTemplate<String, Object> redisTemplate, String key) { try { return redisTemplate.hasKey(key); } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 删除缓存 * * @param key 可以传一个值或多个 */ @SuppressWarnings("unchecked") public static void del(RedisTemplate<String, Object> redisTemplate, String... key) { if (key != null && key.length > 0) { if (key.length == 1) { redisTemplate.delete(key[0]); } else { redisTemplate.delete(CollectionUtils.arrayToList(key)); } } } // ============================String============================= /** * @description 普通缓存获取 * * @param key 键 * @return Object */ public static Object get(RedisTemplate<String, Object> redisTemplate, String key) { return key == null ? null : redisTemplate.opsForValue().get(key); } /** * @description 普通缓存放入 * * @param key 键 * @param value 值 * @return boolean (true:成功 false:失败) */ public static boolean set(RedisTemplate<String, Object> redisTemplate, String key, Object value) { try { redisTemplate.opsForValue().set(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 普通缓存放入并设置时间 * * @param key 键 * @param value 值 * @param time 时间(秒) (time要大于0,如果time小于等于0,将设置无限期) * @return boolean (true:成功 false:失败) */ public static boolean set(RedisTemplate<String, Object> redisTemplate, String key, Object value, long time) { try { if (time > 0) { redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS); } else { set(redisTemplate, key, value); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 递增 * * @param key 键 * @return long */ public static long incr(RedisTemplate<String, Object> redisTemplate, String key, long delta) { if (delta < 0) { throw new RuntimeException("递增因子必须大于0"); } return redisTemplate.opsForValue().increment(key, delta); } /** * @description 递减 * * @param key 键 * @return long */ public static long decr(RedisTemplate<String, Object> redisTemplate, String key, long delta) { if (delta < 0) { throw new RuntimeException("递减因子必须大于0"); } return redisTemplate.opsForValue().increment(key, -delta); } // ================================Map================================= /** * @description HashGet * * @param key 键 不能为null * @param item 项 不能为null * @return Object 值 */ public static Object hget(RedisTemplate<String, Object> redisTemplate, String key, String item) { return redisTemplate.opsForHash().get(key, item); } /** * @description 获取hashKey对应的所有键值 * * @param key 键 * @return Map<Object,Object> 对应的多个键值 */ public static Map<Object, Object> hmget(RedisTemplate<String, Object> redisTemplate, String key) { return redisTemplate.opsForHash().entries(key); } /** * @description HashSet * * @param key 键 * @param map 对应多个键值 * @return boolean (true:成功 false:失败) */ public static boolean hmset(RedisTemplate<String, Object> redisTemplate, String key, Map<String, Object> map) { try { redisTemplate.opsForHash().putAll(key, map); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description HashSet 并设置时间 * * @param key 键 * @param map 对应多个键值 * @param time 时间(秒) * @return boolean (true:成功 false:失败) */ public static boolean hmset(RedisTemplate<String, Object> redisTemplate, String key, Map<String, Object> map, long time) { try { redisTemplate.opsForHash().putAll(key, map); if (time > 0) { expire(redisTemplate, key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 向一张hash表中放入数据,如果不存在将创建 * * @param key 键 * @param item 项 * @param value 值 * @return boolean (true:成功 false:失败) */ public static boolean hset(RedisTemplate<String, Object> redisTemplate, String key, String item, Object value) { try { redisTemplate.opsForHash().put(key, item, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 向一张hash表中放入数据,如果不存在将创建 * * @param key 键 * @param item 项 * @param value 值 * @param time 时间(秒) (如果已存在的hash表有时间,这里将会替换原有的时间) * @return boolean (true:成功 false:失败) */ public static boolean hset(RedisTemplate<String, Object> redisTemplate, String key, String item, Object value, long time) { try { redisTemplate.opsForHash().put(key, item, value); if (time > 0) { expire(redisTemplate, key, time); } return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 删除hash表中的值 * * @param key 键 不能为null * @param item 项 可以为多个但不能为null */ public static void hdel(RedisTemplate<String, Object> redisTemplate, String key, Object... item) { redisTemplate.opsForHash().delete(key, item); } /** * @description 判断hash表中是否有该项的值 * * @param key 键 不能为null * @param item 项 不能为null * @return boolean (true:存在 false:不存在) */ public static boolean hHasKey(RedisTemplate<String, Object> redisTemplate, String key, String item) { return redisTemplate.opsForHash().hasKey(key, item); } /** * @description hash递增 * * @param key 键 * @param item 项 * @param by 要增加(大于0) * @return double */ public static double hincr(RedisTemplate<String, Object> redisTemplate, String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, by); } /** * @description hash递减 * * @param key 键 * @param item 项 * @param by 要减少(小于0) * @return double */ public static double hdecr(RedisTemplate<String, Object> redisTemplate, String key, String item, double by) { return redisTemplate.opsForHash().increment(key, item, -by); } // ============================set============================= /** * @description 根据key获取Set中的所有值 * * @param key 键 * @return Set<Object> */ public static Set<Object> sGet(RedisTemplate<String, Object> redisTemplate, String key) { try { return redisTemplate.opsForSet().members(key); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @description 根据value从一个set中查询,判断是否存在 * * @param key 键 * @param value 值 * @return boolean(true:存在 false:不存在) */ public static boolean sHasKey(RedisTemplate<String, Object> redisTemplate, String key, Object value) { try { return redisTemplate.opsForSet().isMember(key, value); } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 将数据放入set缓存 * * @param key 键 * @param values 值 * @return long 返回存入成功的个数 */ public static long sSet(RedisTemplate<String, Object> redisTemplate, String key, Object... values) { try { return redisTemplate.opsForSet().add(key, values); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * @description 将set数据放入缓存 * * @param key 键 * @param time 时间(秒) * @param values 值 * @return long 返回存入成功的个数 */ public static long sSetAndTime(RedisTemplate<String, Object> redisTemplate, String key, long time, Object... values) { try { Long count = redisTemplate.opsForSet().add(key, values); if (time > 0) expire(redisTemplate, key, time); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } /** * @description 获取set缓存的长度 * * @param key 键 * @return long */ public static long sGetSetSize(RedisTemplate<String, Object> redisTemplate, String key) { try { return redisTemplate.opsForSet().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * @description 移除值为value的数 * * @param key 键 * @param values 值 * @return long 返回移除的个数 */ public static long setRemove(RedisTemplate<String, Object> redisTemplate, String key, Object... values) { try { Long count = redisTemplate.opsForSet().remove(key, values); return count; } catch (Exception e) { e.printStackTrace(); return 0; } } // ===============================list================================= /** * @description 获取list缓存的内容 * * @param key 键 * @param start 开始 * @param end 结束 (0到-1代表所有值) * @return List<Object> */ public static List<Object> lGet(RedisTemplate<String, Object> redisTemplate, String key, long start, long end) { try { return redisTemplate.opsForList().range(key, start, end); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @description 获取list缓存的长度 * * @param key 键 * @return long */ public static long lGetListSize(RedisTemplate<String, Object> redisTemplate, String key) { try { return redisTemplate.opsForList().size(key); } catch (Exception e) { e.printStackTrace(); return 0; } } /** * @description 通过索引,获取list中的值 * * @param key 键 * @param index 索引 (index>=0时,0:表头,1:第二个元素,依次类推;index<0时,-1:表尾,-2:倒数第二个元素,依次类推) * @return Object */ public static Object lGetIndex(RedisTemplate<String, Object> redisTemplate, String key, long index) { try { return redisTemplate.opsForList().index(key, index); } catch (Exception e) { e.printStackTrace(); return null; } } /** * @description 将list放入缓存 * * @param key 键 * @param value 值 * @return boolean */ public static boolean lSet(RedisTemplate<String, Object> redisTemplate, String key, Object value) { try { redisTemplate.opsForList().rightPush(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) * @return boolean */ public static boolean lSet(RedisTemplate<String, Object> redisTemplate, String key, Object value, long time) { try { redisTemplate.opsForList().rightPush(key, value); if (time > 0) expire(redisTemplate, key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 将list放入缓存 * * @param key 键 * @param value 值 * @return boolean */ public static boolean lSet(RedisTemplate<String, Object> redisTemplate, String key, List<Object> value) { try { redisTemplate.opsForList().rightPushAll(key, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 将list放入缓存 * * @param key 键 * @param value 值 * @param time 时间(秒) * @return boolean */ public static boolean lSet(RedisTemplate<String, Object> redisTemplate, String key, List<Object> value, long time) { try { redisTemplate.opsForList().rightPushAll(key, value); if (time > 0) expire(redisTemplate, key, time); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 根据索引修改list中的某条数据 * * @param key 键 * @param index 索引 * @param value 值 * @return boolean */ public static boolean lUpdateIndex(RedisTemplate<String, Object> redisTemplate, String key, long index, Object value) { try { redisTemplate.opsForList().set(key, index, value); return true; } catch (Exception e) { e.printStackTrace(); return false; } } /** * @description 移除N个值为value * * @param key 键 * @param count 移除个数 * @param value 值 * @return long 返回移除的个数 */ public static long lRemove(RedisTemplate<String, Object> redisTemplate, String key, long count, Object value) { try { Long remove = redisTemplate.opsForList().remove(key, count, value); return remove; } catch (Exception e) { e.printStackTrace(); return 0; } } }

    6.使用缓存 UserImpl类代码修改如下。

    @Service public class UserImpl implements IUser { @Autowired private RedisTemplate redisTemplate; @Autowired UserMapper userMapper; @Override public ServerResponse findByName(String name) { User user = (User) RedisUtil.get(this.redisTemplate, "user_" + name); if(user == null) { User userMySQL = userMapper.findByName(name); if(userMySQL == null){ return ServerResponse.createByErrorMessage("没有查询到用户"); } RedisUtil.set(this.redisTemplate, "user_" + name, userMySQL); return ServerResponse.createBySuccess(userMySQL); } return ServerResponse.createBySuccess(user); } } RedisTemplate:Spring Data Redis提供的用来操作数据的模版,在应用启动时,Spring会初始化RedisTemplate模版类,通过@Autowired注解注入即可使用。RedisTemplate提供了opsForValue方法来操作简单属性的数据,此外还提供了opsForList、opsForSet、opsForZSet、opsForHash等方法来操作列表、集合、有序集合和哈希等数据。当数据存放到Redis时,RedisTemplate默认使用JdkSerializationRedisSerializer将键(Key)和值(Value)序列化到数据库。

    7.启动类开发 在启动类RedisApplication上添加注解“@MapperScan(basePackages = “com.leichuangkj.redis.dao.mapper”)”。

    @MapperScan(basePackages = "com.leichuangkj.redis.dao.mapper") @SpringBootApplication public class RedisApplication { public static void main(String[] args) { SpringApplication.run(RedisApplication.class, args); } }

    8.测试 以debug方式启动项目(包括启动reids服务,通过“keys *”命令查看redis数据库里的内容,此时为空),然后在postman中请求“http://localhost:8080/user/findByName”,可以在IDEA中看到,第一次从缓存中没有查询到数据,而是通过读取mysql数据库获取的,然后通过“keys *”命令查看redis数据库里的内容,此时存在一条key为“user_steven”的数据。然后继续在postman中请求“http://localhost:8080/user/findByName”,此时在IDEA中可以看到直接从缓存中取到了数据,整个测试过程如下所示。

    9.工程目录结构

    Processed: 0.013, SQL: 9