小工具知识网

当前位置: 首页 > 行业知识 > Spring Boot 整合 Redis 集群详解

行业知识

Spring Boot 整合 Redis 集群详解

2026-11-02 19:36:14 来源:互联网转载

前言:

项目中需要使用 Redis 做缓存数据库,本文分享一下 Spring Boot 项目集成 Redis 的过程以及踩过的坑。

Spring Boot 集成 Redis 可以分为三大步,如下:

  • 在 proerties 或者 yml 文件中添加 redis 和 lettuce 配置。
  • 项目 pom.xml 文件中引入 spring-boot-starter-data-redis 依赖。
  • 注入 RedisTemplate 开始使用 Redis,其实这步以及算是使用了,不能算作集成了,但是集成了总归是要使用的,我把这里也算作一步了。

    添加 redis 和 lettuce 配置:

    //redis 集群地址spring.redis.cluster.nodes = dev-k8s-redis.eminxing.com:17000//密码spring.redis.password = z8_UX7BCi_XYckrM//在群集上执行命令时重定向的最大数量。spring.redis.cluster.max-redirects = 3//连接池最小空闲连接数 负值表示没有限制spring.redis.lettuce.pool.max-idle = 10//连接池最大空闲连接数 负值表示没有限制spring.redis.lettuce.pool.min-idle = 5//连接池最大活跃连接数 负值表示没有限制spring.redis.lettuce.pool.max-active = 20//建立连接最大等待时间,默认1ms,超出该时间会抛异常。设为-1表示无限等待,直到分配成功spring.redis.lettuce.pool.max-wait = 10000

    项目 pom.xml 文件中引入 spring-boot-starter-data-redis 依赖:

           org.springframework.boot       spring-boot-starter-data-redis

    注入 RedisTemplate 开始使用 Redis,启动就报错,完美翻车,错误信息如下:

    nested exception is java.lang.NoClassDefFoundError: org/apache/commons/pool2/impl/GenericObjectPoolConfig

    关于这个错误的解决方案另起了一篇文章进行了详细分析,如下:

    解决报错传送门:

    传送门告诉我们正确的 Spring Boot 2.0 以上版本集成 Redis 的正确依赖如下:

             org.springframework.boot        spring-boot-starter-data-redis       org.apache.commons       commons-pool2

    解决启动报错问题,准备开始使用:

    测试代码:

    @Slf4j@RestController@RequestMapping("/api/redis/")public class RedisDemoController {    @Autowired    private RedisUtils redisUtils;    @ApiOperation(value = "测试redis", produces = "application/json")    @GetMapping("/test-redis")    public Result batchCreateOrUpdatePipeline(@RequestParam("key") String key, @RequestParam("value") String value) {        redisUtils.set(key, value);        return ResultGenerator.genSuccessResult();    }}

    这里的 RedisUtils 是我封装的一个工具类,下文会进行分享,这里先分享一下演示结果,Another Redis Desktop Manager 客户端展示如下:

    分析结果,我们发现出现了一串字符串 “\xac\xed\x00\x05t\x00\x10”,这串字符串明显不是我们想要看到的,难道是 Redis 集成又出问题了吗,使用代码获取了缓存字符串,发现并没有这串奇奇怪怪的字符串,那是怎么回事呢?查阅资料得知是序列话的问题。

    Redis 序列化与反序列化问题处理,如下:

    @Configurationpublic class RedisConfig {    @Bean    public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {        RedisTemplate redisTemplate = new RedisTemplate();        redisTemplate.setConnectionFactory(connectionFactory);        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);        ObjectMapper mapper = new ObjectMapper();        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);        mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);        serializer.setObjectMapper(mapper);        //如果不序列化在key value 使用redis客户端工具 直连redis服务器 查看数据时 前面会有一个 \xac\xed\x00\x05t\x00\x05 字符串        // StringRedisSerializer 来序列化和反序列化 String 类型 redis 的 key value        redisTemplate.setKeySerializer(new StringRedisSerializer());        redisTemplate.setValueSerializer(serializer);        // StringRedisSerializer 来序列化和反序列化 hash 类型 redis 的 key value        redisTemplate.setHashKeySerializer(new StringRedisSerializer());        redisTemplate.setHashValueSerializer(serializer);        redisTemplate.afterPropertiesSet();        return redisTemplate;    }}

    自定义了 RedisTemplate 配置,设置了序列化和反序列化后,再次验证后,如下:

    完美解决问题。

    RedisUtils 分享如下:

    package com.zt.zteam.main.utils;import lombok.extern.slf4j.Slf4j;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.core.ValueOperations;import org.springframework.stereotype.Component;import org.springframework.util.CollectionUtils;import java.util.List;import java.util.Map;import java.util.Set;import java.util.concurrent.TimeUnit;/** * @ClassName: RedisUtils * @Author: zhangyong * @Date: 2024/4/1 14:56 * @Description: redis 工具类 */@Component@Slf4jpublic class RedisUtils {    @Autowired    public RedisTemplate redisTemplate;    /**     * @Description: 设置缓存对象     * @Date: 2024/4/2 14:18     */    public  void set(String key, T value) {        redisTemplate.opsForValue().set(key, value);    }    /**     * @Description: 设置缓存对象,附带设定有效期     * @Date: 2024/4/2 14:18     */    public  void set(String key, T value, Integer timeout, TimeUnit timeUnit) {        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);    }    /**     * @Description: 设置缓存对象的有效期     * @Date: 2024/4/2 14:18     */    public  void expire(String key, Integer timeout, TimeUnit timeUnit) {        redisTemplate.expire(key, timeout, timeUnit);    }    /**     * @Description: 获取缓存对象     * @Date: 2024/4/2 14:18     */    public  T get(String key) {        ValueOperations operation = redisTemplate.opsForValue();        return operation.get(key);    }    /**     * @Description: 删除缓存对象     * @Date: 2024/4/2 14:18     */    public boolean remove(String key) {        return redisTemplate.delete(key);    }    /**     * @Description: 从redis缓存中移除指定前缀的所有值     * @Date: 2024/4/2 14:18     */    public void removePrefix(String prefix) {        Set keys = redisTemplate.keys(prefix + "*");        redisTemplate.delete(keys);    }    /**     * @Description: 伪批量存入缓存     * @Date: 2024/4/2 14:18     */    public void setBatch(Map cachedMap) {        for (String key : cachedMap.keySet()) {            set(key, cachedMap.get(key));        }    }    /**     * @Description: key 是否存在     * @Date: 2024/4/2 14:18     */    public boolean exists(String key) {        return redisTemplate.hasKey(key);    }    /**     * @Description: 根据key 删除 value     * @Date: 2024/4/2 14:18     */    public boolean del(String key) {        return redisTemplate.delete(key);    }    /**     * @Description: 判断key是否存在     * @Date: 2024/4/2 14:18     */    public boolean hasKey(String key) {        try {            return redisTemplate.hasKey(key);        } catch (Exception e) {            e.printStackTrace();            return false;        }    }    /**     * @Description: 指定缓存失效时间     * @Date: 2024/4/13 8:53     */    public boolean expire(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 的过期时间     * @Date: 2024/4/13 8:54     */    public long getExpire(String key) {        return redisTemplate.getExpire(key, TimeUnit.SECONDS);    }    /**     * @Description: 删除缓存 支持一个到多个     * @Date: 2024/4/13 8:55     */    public void del(String... key) {        if (key != null && key.length > 0) {            if (key.length == 1) {                redisTemplate.delete(key[0]);            } else {                redisTemplate.delete(CollectionUtils.arrayToList(key));            }        }    }    /**     * @Description: 增加操作     * @Date: 2024/4/13 8:55     */    public long incr(String key, long count) {        if (count  0) {                expire(key, time);            }            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }    /**     * @Description: hash set 操作 单个set     * @Date: 2024/4/13 8:55     */    public boolean hSet(String key, String item, Object value) {        try {            redisTemplate.opsForHash().put(key, item, value);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }    /**     * @Description: hash set 操作 单个set 带过期时间     * @Date: 2024/4/13 8:55     */    public boolean hset(String key, String item, Object value, long time) {        try {            redisTemplate.opsForHash().put(key, item, value);            if (time > 0) {                expire(key, time);            }            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }    /**     * @Description: hash 删除操作 支持当个或多个     * @Date: 2024/4/13 8:55     */    public void hDel(String key, Object... item) {        redisTemplate.opsForHash().delete(key, item);    }    /**     * @Description: hash 判断 key 是否存在     * @Date: 2024/4/13 8:55     */    public boolean hHasKey(String key, String item) {        return redisTemplate.opsForHash().hasKey(key, item);    }    /**     * @Description: hash 递增操作     * @Date: 2024/4/13 8:55     */    public double hincr(String key, String item, double by) {        return redisTemplate.opsForHash().increment(key, item, by);    }    /**     * @Description: hash 递减操作     * @Date: 2024/4/13 8:55     */    public double hdecr(String key, String item, double by) {        return redisTemplate.opsForHash().increment(key, item, -by);    }    /**     * @Description: set  根据key 获取value 值     * @Date: 2024/4/13 8:55     */    public Set sGet(String key) {        try {            return redisTemplate.opsForSet().members(key);        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    /**     * @Description: set  判断value是否存在set集合中     * @Date: 2024/4/13 8:55     */    public boolean sHasValue(String key, Object value) {        try {            return redisTemplate.opsForSet().isMember(key, value);        } catch (Exception e) {            e.printStackTrace();            return false;        }    }    /**     * @Description: set 添加元素操作 value 可以是一个或多个     * @Date: 2024/4/13 8:55     */    public long sSet(String key, Object... values) {        try {            return redisTemplate.opsForSet().add(key, values);        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }    /**     * @Description: set 添加元素操作 value 可以是一个或多个 带缓存时间     * @Date: 2024/4/13 8:55     */    public long sSetAndTime(String key, long time, Object... values) {        try {            Long count = redisTemplate.opsForSet().add(key, values);            if (time > 0) {                expire(key, time);            }            return count;        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }    /**     * @Description: 获取 set 集合的元素个数     * @Date: 2024/4/13 8:55     */    public long sGetSize(String key) {        try {            return redisTemplate.opsForSet().size(key);        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }    /**     * @Description: 删除 set 集合中元素 支持一个或者多个 返回删除的个数     * @Date: 2024/4/13 8:55     */    public long setDel(String key, Object... values) {        try {            Long count = redisTemplate.opsForSet().remove(key, values);            return count;        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }    /**     * @Description: 获取 list 缓存的内容 从start 位置到 end 位置     * @Date: 2024/4/13 8:55     */    public List lGet(String key, long start, long end) {        try {            return redisTemplate.opsForList().range(key, start, end);        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    /**     * @Description: 获取 list 缓存的元素个数     * @Date: 2024/4/13 8:55     */    public long lGetSize(String key) {        try {            return redisTemplate.opsForList().size(key);        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }    /**     * @Description: 通过索引获取list 集合中的元素 类似 list(0)     * @Date: 2024/4/13 8:55     */    public Object lGetIndex(String key, long index) {        try {            return redisTemplate.opsForList().index(key, index);        } catch (Exception e) {            e.printStackTrace();            return null;        }    }    /**     * @Description: 像list 集合中添加元素     * @Date: 2024/4/13 8:55     */    public boolean lSet(String key, Object value) {        try {            redisTemplate.opsForList().rightPush(key, value);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }    /**     * @Description: 像list 集合中添加元素 带缓存时间     * @Date: 2024/4/13 8:55     */    public boolean lSet(String key, Object value, long time) {        try {            redisTemplate.opsForList().rightPush(key, value);            if (time > 0) {                expire(key, time);            }            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }    /**     * @Description: 像list 集合中添加元素 批量操作     * @Date: 2024/4/13 8:55     */    public boolean lBatchSet(String key, List value) {        try {            redisTemplate.opsForList().rightPushAll(key, value);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }    /**     * @Description: 像list 集合中添加元素 批量操作 带过期时间     * @Date: 2024/4/13 8:55     */    public boolean lBatchSet(String key, List value, long time) {        try {            redisTemplate.opsForList().rightPushAll(key, value);            if (time > 0) {                expire(key, time);            }            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }    /**     * @Description: 根据索引修改 list 中的某个元素     * @Date: 2024/4/13 8:55     */    public boolean lUpdateIndex(String key, long index, Object value) {        try {            redisTemplate.opsForList().set(key, index, value);            return true;        } catch (Exception e) {            e.printStackTrace();            return false;        }    }    /**     * @Description: 删除 count 个值为value 的元素 返回删除的个数     * @Date: 2024/4/13 8:55     */    public long lRemove(String key, long count, Object value) {        try {            Long remove = redisTemplate.opsForList().remove(key, count, value);            return remove;        } catch (Exception e) {            e.printStackTrace();            return 0;        }    }}

    本篇简单分享了 Spring Boot 项目集成 Redis 过程中可能会需要的一些问题,希望能够帮助到有需要的朋友。

    如有错误的地方欢迎指出纠正。

上一篇:摔炮折纸教程,轻松学会炫酷折叠技巧!

下一篇:阿里云服务器的网络接入服务商的简单介绍