SpringBoot集成Redis实战——步骤、坑点、解决方案

背景

回顾项目中的TODO工作,发现留了一条待办项,即对Redis配置参数的具体含义的了解。开发平台研发期间,由于时间紧张,对于Redis,没有进行相对充分的技术预研,集成的比较粗放,虽然目标达成了,使用Redis读写缓存功能也实现了,但心里实际是不踏实的。

当下有了相对充裕的时间,深入了解下Redis,并对集成部分进行重构与优化,过程中,发现网上很多资料都是存在谬误的,一些坑点或注意事项,也在这里一并整理出来,作为知识沉淀,也能为后来者提供一定的参考,能少走一点弯路。

原有集成方式

既然是优化重构,那就不得不说下原有的集成的方式,这样才有对比。
首先,是引入了jar包依赖,使用的是spring-boot-starter-data-redis

   <!-- redis缓存 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <!--2.0以上版本默认客户端是lettuce, 因为此次是采用jedis,所以需要排除lettuce的jar -->
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- jedis客户端 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>

使用的springboot版本是2.3.0,而spring-boot-starter-data-redis在2.0版本以上默认使用lettuce作为redis的客户端工具,而我当时查到的集成资料,是需要使用jedis,因此将lettuce排除掉了,并且引用了jedis的maven依赖。

其次,在yml中配置redis及jedis参数

spring: 
  devtools:
    livereload:
      enabled: true
  redis:
    host: localhost
    port: 6379
    password: test123
    #新版本redis的timeout是一个duration,需使用如下写法
    timeout: 5s
    database: 0
    #连接耗尽时是否阻塞, false报异常,true阻塞直到超时, 默认true
    block-when-exhausted: true
    #    集群环境打开下面注释,单机不需要打开
    #    cluster:
    #      集群信息
    #      nodes: xxx.xxx.xxx.xxx:xxxx,xxx.xxx.xxx.xxx:xxxx,xxx.xxx.xxx.xxx:xxxx
    #      #默认值是5 一般当此值设置过大时,容易报:Too many Cluster redirections
    #      maxRedirects: 3
    jedis:
      pool:
        max-active: 16
        min-idle: 4
        max-idle: 8
        max-wait: 300ms
  profiles:
    active: dev

再次,新建一个配置文件,来设置jedis的连接池

/**
 * Redis配置
 * @author wqliu
 * TODO:具体配置参数待深入了解
 */
@Configuration
@Slf4j
public class RedisConfig {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.timeout}")
    private Duration timeout;

    @Value("${spring.redis.jedis.pool.max-idle}")
    private int maxIdle;

    @Value("${spring.redis.jedis.pool.max-wait}")
    private Duration maxWait;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.block-when-exhausted}")
    private boolean  blockWhenExhausted;

    /**
     * 配置文件中的秒数转换为毫秒数的乘积数
     */
    private static final int THOUSAND =1000;

    @Bean
    public JedisPool redisPoolFactory()  throws Exception{
        log.info("JedisPool注入成功!!");
        log.info("redis地址:" + host + ":" + port);
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(maxIdle);
        jedisPoolConfig.setMaxWaitMillis((int)maxWait.getSeconds()* THOUSAND);
        // 连接耗尽时是否阻塞, false报异常,true阻塞直到超时, 默认true
        jedisPoolConfig.setBlockWhenExhausted(blockWhenExhausted);
        // 是否启用pool的jmx管理功能, 默认true
        jedisPoolConfig.setJmxEnabled(true);
        JedisPool jedisPool=null;
        if(StringUtils.isNotBlank(password)){
            jedisPool = new JedisPool(jedisPoolConfig, host, port, (int)timeout.getSeconds()* THOUSAND, password);
        } else{
            //redis服务器未设置密码的情况下不传递密码参数,否则读写时会报错
            jedisPool = new JedisPool(jedisPoolConfig, host, port, (int)timeout.getSeconds()* THOUSAND);
        }
        return jedisPool;
    }
}

在回顾代码的时候就发现这里有问题了,yml中的配置参数,与上述配置类中的参数对应不起来,主要有以下几点:
1.配置文件中设置了 min-idle、max-active属性,而配置类中并没有使用
2.配置文件中block-when-exhausted,上级节点是redis,而在配置类中,使用该属性的则是jedisPool,那这个属性,究竟上级节点应该是redis还是pool?

大概当时是从网上拷贝的现成代码,没有认真查看(本次重构过程中,还反复搜到了多个来源,都存在这样的错误)。

此时,产生了新的疑问,按照SpringBoot自动装配的套路,我在yml中配置了,按理说就不需要再写配置类,SpringBoot应该把这些参数给加载进去了。

最后,看下封装的工具类,因为使用的redis功能相对简单,键值对都是string类型,未使用集合等高级特性,因此这个工具类也比较简单。

package tech.popsoft.platform.common.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.Map;
import java.util.Set;


/**
 * Jedis工具类
 * @author  wqliu
 * @date  2022-8-1
*/
@Component
@Slf4j
public class JedisUtil {
    @Autowired
    private JedisPool jedisPool;

    /**
     * 存入redis缓存
     *
     * @param key
     * @param value
     */
    public void set(String key, String value) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key, value);
        } catch (Exception ex) {
            log.error("存储redis出错" + ex);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

    }

    /**
     * 从redis缓存中读取
     */
    public String get(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.get(key);
        } catch (Exception ex) {
            log.error("读取redis出错" + ex);
            return StringUtils.EMPTY;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

    }

    /**
     * 从redis缓存中移除
     */
    public void remove(String key) {

        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.del(key);
        } catch (Exception ex) {
            log.error("移除redis出错" + ex);

        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    /**
     * 从redis缓存中移除指定前缀的所有值
     */
    public void removePrefix(String prefix) {

        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            Set<String> set= jedis.keys(prefix+"*");
            for (String item: set) {
                jedis.del(item);
            }

        } catch (Exception ex) {
            log.error("移除redis出错" + ex);

        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

    }

    /**
     * 批量存入缓存
     * @param cachedMap
     */
    public void setBatch(Map<String,String> cachedMap) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            for(String key : cachedMap.keySet()) {
                jedis.set(key, cachedMap.get(key));
            }
        } catch (Exception ex) {
            log.error("存储redis出错" + ex);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

}

深入了解集成知识

如上所述,发现了不少疑点,因此补了下关于集成的相关知识,整理如下。

spring-data-redis与jedis是什么关系?

这俩的关系,用一个类比来说明,就是slf4j与logback的关系,也就是spring-data-redis对reids底层开发包(Jedis、JRedis、lettuce等 )进行了高度封装,统一由RedisTemplate提供了redis各种操作、异常处理及序列化工作。
也就是说,可以将spring-data-redis视作抽象的接口,对redis的读写,可以灵活更换为具体的客户端,如jedis或lettuce。

从这一点就可以看出,我们应该使用spring-boot-data-redis,而不是直接使用Jedis等客户端,一方面,封装后的组件,往往比未封装的组件更易用;另一方面,当需要更换组件时,明显更易于实现。

jedis与lettuce的差异

既然spring-data-redis只是个封装,那么具体的实现组件,jedis和lettuce应该选哪个呢?

先来看下简介。
Jedis:是老牌的Redis的Java实现客户端,提供了比较全面的Redis命令的支持。
Lettuce:高级Redis客户端,用于线程安全同步,异步和响应使用,支持集群,Sentinel,管道和编码器。
好像从简介中也看不出谁优谁劣,再进一步看下技术实现。

Jedis使用阻塞的I/O,且其方法调用都是同步的,程序流需要等到sockets处理完I/O才能执行,不支持异步。Jedis客户端实例不是线程安全的,所以需要通过连接池来使用Jedis。
Lettuce基于Netty框架的事件驱动的通信层,其方法调用是异步的。Lettuce的API是线程安全的,所以可以操作单个Lettuce连接来完成各种操作。

这时候就看出来差别来了,从技术实现上,明显Lettuce更胜一筹。
SpringBoot从2.0版本开始,将spring-boot-data-redis内置的jedis,更换为lettuce,大概也是后者优于前者的一个佐证。

重构后集成方式

首先,是引入了jar包依赖,使用的是spring-boot-starter-data-redis

      <!-- redis缓存 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
        </dependency>

使用的springboot版本是2.3.0,而spring-boot-starter-data-redis在2.0版本以上默认使用lettuce作为redis的客户端工具。

这时候,第一个坑点出现了,lettuce内部使用了apache的连接池,但并没有强依赖,需要引入commons-pool2,如上所示。

其次,在yml中配置redis及lettuce参数

spring: 
  devtools:
    livereload:
      enabled: true
    redis:
    host: localhost
    port: 6379
    password: test123
    #新版本redis的timeout是一个duration,需使用如下写法
    timeout: 10s
    database: 0
    lettuce:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 2
        # 连接池中的最大空闲连接
        max-idle: 2
        # 连接池的最大连接数
        max-active: 16
        #连接池最大阻塞等待时间
        max-wait: 30s
  profiles:
    active: dev

以上配置,会自动由SpringBoot装配,根本就不需要再写个配置类,把这些配置参数加载后实例化连接池。

再次,就是实现工具类了,这里进行了适当的功能扩展。

package tech.popsoft.platform.common.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 java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;


/**
 * 缓存工具类
 *
 * @author wqliu
 * @date 2022-8-1
 */
@Component
@Slf4j
public class CacheUtil {


    @Autowired
    public RedisTemplate redisTemplate;


    /**
     * 设置缓存对象
     *
     * @param key   缓存的键
     * @param value 缓存的值
     */
    public <T> void set(String key, T value) {

        redisTemplate.opsForValue().set(key, value);

    }

    /**
     * 设置缓存对象,附带设定有效期
     *
     * @param key      缓存的键值
     * @param value    缓存的值
     * @param timeout  时间
     * @param timeUnit 时间单位
     */
    public <T> void set(String key, T value, Integer timeout, TimeUnit timeUnit) {
        redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    }

    /**
     * 设置缓存对象的有效期
     *
     * @param key      缓存的键值
     * @param timeout  时间
     * @param timeUnit 时间单位
     */
    public <T> void expire(String key, Integer timeout, TimeUnit timeUnit) {
        redisTemplate.expire(key, timeout, timeUnit);
    }


    /**
     * 获取缓存对象
     *
     * @param key 缓存键值
     * @return 缓存键值对应的数据
     */
    public <T> T get(String key) {
        ValueOperations<String, T> operation = redisTemplate.opsForValue();
        return operation.get(key);
    }


    /**
     * 删除缓存对象
     *
     * @param key 缓存的键
     */
    public boolean remove(String key) {
        return redisTemplate.delete(key);
    }


    /**
     * 从redis缓存中移除指定前缀的所有值
     */
    public void removePrefix(String prefix) {

        Set keys = redisTemplate.keys(prefix + "*");
        redisTemplate.delete(keys);
    }

    
    /**
     * 批量存入缓存
     *
     * @param cachedMap
     */
    public void setBatch(Map<String, String> cachedMap) {
        for (String key : cachedMap.keySet()) {
            set(key, cachedMap.get(key));
        }
    }



}

可以看出来,使用封装后的redisTemplate,要比原生的jedis方便得多,一句代码就能实现读或写,而jedis更像是访问关系型数据库的模式,需要先从连接池中获取1个连接,然后执行读或写操作,最后再关闭连接。

完成上面三个步骤后,这时候,已经可以正常使用Redis来进行缓存的读写了。

但是,这还没有完,通过系统读写是没问题,但是使用redis客户端工具,直连redis服务器,查看数据时,则会显示多了一些不可读的前缀\xac\xed\x00\x05t\x00\,这是另外一个坑点。
这是怎么出现的呢?原来lettuce默认使用JdkSerializationRedisSerializer作为序列化与反序列化的工具,将字符串转换为字节数组搞出来的幺蛾子。

怎么解决呢?知道原因了,解决思路也有了,搞一个配置类,将默认的序列化与反序列的类替换掉。

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<Object, Object> redisStringTemplate(RedisTemplate<Object, Object> redisTemplate) {
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringRedisSerializer);
        redisTemplate.setValueSerializer(stringRedisSerializer);
        return redisTemplate;
    }

}

StringRedisSerializer是spring-data提供的,同时还提供了负责json数据的处理类,可用于键值为json的场景。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
### 回答1: 好的,下面是使用Spring Boot集成Redis实战步骤: 1. 添加Redis依赖 在pom.xml文件中添加Redis依赖: ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 2. 配置Redis连接信息 在application.properties文件中添加Redis连接信息: ```properties spring.redis.host=127.0.0.1 spring.redis.port=6379 spring.redis.password=yourpassword spring.redis.database=0 ``` 3. 创建RedisTemplate 在Java代码中创建RedisTemplate对象,用于对Redis进行操作: ```java @Configuration public class RedisConfig { @Bean public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); // 设置key序列化方式 redisTemplate.setKeySerializer(new StringRedisSerializer()); // 设置value序列化方式 redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer()); // 设置hash key序列化方式 redisTemplate.setHashKeySerializer(new StringRedisSerializer()); // 设置hash value序列化方式 redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer()); return redisTemplate; } } ``` 4. 使用RedisTemplate操作Redis 通过RedisTemplate对象可以对Redis进行操作,例如: ```java @Autowired private RedisTemplate<String, Object> redisTemplate; // 存储字符串 redisTemplate.opsForValue().set("name", "ChatGPT"); // 获取字符串 String name = (String) redisTemplate.opsForValue().get("name"); // 存储对象 User user = new User(); user.setId(1); user.setName("ChatGPT"); redisTemplate.opsForValue().set("user", user); // 获取对象 User user = (User) redisTemplate.opsForValue().get("user"); ``` 5. 使用Redis缓存 可以使用Spring Cache注解将方法结果缓存到Redis中,例如: ```java @Service @CacheConfig(cacheNames = "user") public class UserService { @Autowired private UserDao userDao; @Cacheable(key = "#id") public User getUserById(int id) { return userDao.getUserById(id); } @CachePut(key = "#user.id") public User updateUser(User user) { userDao.updateUser(user); return user; } @CacheEvict(key = "#id") public void deleteUserById(int id) { userDao.deleteUserById(id); } } ``` 上面的代码使用了@Cacheable注解将getUserById方法的结果缓存到名为"user"的缓存中,使用@CachePut注解将updateUser方法的结果更新到缓存中,使用@CacheEvict注解从缓存中删除deleteUserById方法的结果。 以上就是使用Spring Boot集成Redis实战步骤,希望能够帮助到你。 ### 回答2: Spring Boot是一个非常强大的Java应用程序开发框架,它支持快速开发和部署应用程序,并且提供了大量的插件和集成库,可以帮助开发者快速构建高效的应用程序。其中,集成Redis是非常常见的需求,因为Redis提供了快速和可扩展的缓存和持久化解决方案Spring BootRedis集成非常简单,可以通过在应用程序中添加适当的依赖和配置来完成。首先,需要在maven或gradle中添加spring-boot-starter-data-redis的依赖,以便在应用程序中使用Spring Data Redis模块。 接下来,需要在application.properties文件中添加Redis的配置信息。其中,包括Redis服务器的主机名、端口号、密码以及连接池的一些基本配置信息等等。例如: spring.redis.host=localhost spring.redis.port=6379 spring.redis.password=123456 除了以上的配置信息,还需要在项目中创建一个RedisTemplate对象来连接到Redis服务器,同时在需要使用Redis功能的类中注入RedisTemplate对象,以便进行各种Redis操作。 最后,可以利用Spring Boot提供的注解来实现Redis的缓存或消息队列功能。例如,使用@Cacheable注解为方法提供缓存支持,使用@RedisListener注解为方法提供消息订阅支持等等。 总而言之,Spring Boot集成Redis非常简单且易于维护,在项目中可以经常使用Redis作为缓存或消息队列,从而提高应用程序的响应速度和可靠性。 ### 回答3: Spring Boot是一个轻量级的Java框架,能够快速构建和部署Java应用程序。Redis是一种流行的内存数据结构存储,常用于缓存和消息传递。将Spring Boot集成Redis是非常重要的,因为它可以提高应用程序的性能和扩展性,同时也可以减少数据库负载。以下是Spring Boot集成Redis的实践: 1. 引入redis依赖 在pom.xml文件中加入redistemplate和jedis依赖。 ``` <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>3.1.0</version> </dependency> ``` 2. 配置Redis 在application.properties文件中添加Redis配置。这里涉及到Redis服务器、连接池大小、超时时间等参数的设置。 ``` spring.redis.host=localhost spring.redis.port=6379 spring.redis.timeout=30000 spring.redis.pool.max-idle=8 spring.redis.pool.min-idle=0 spring.redis.pool.max-active=8 spring.redis.password=123456 ``` 3. 编写Redis工具类 在src/main/java包下,创建RedisUtil.java文件,实现Redis的连接管理和基本操作(如set、get、delete等)。 ``` @Component public class RedisUtil { @Autowired private StringRedisTemplate stringRedisTemplate; public void set(String key, String value) { stringRedisTemplate.opsForValue().set(key, value); } public String get(String key) { return stringRedisTemplate.opsForValue().get(key); } public void delete(String key) { stringRedisTemplate.delete(key); } } ``` 4. 在应用程序中使用Redis 在需要使用Redis的类中,注入RedisUtil并调用对应的方法即可。 ``` @RestController @RequestMapping("/redis") public class RedisController { @Autowired private RedisUtil redisUtil; @GetMapping("/set") public String setRedis(String key, String value) { redisUtil.set(key, value); return "Set redis success."; } @GetMapping("/get") public String getRedis(String key) { return redisUtil.get(key); } @GetMapping("/delete") public String deleteRedis(String key) { redisUtil.delete(key); return "Delete redis success."; } } ``` 上述代码中,RedisController中的setRedis、getRedis、deleteRedis分别对应RedisUtil中的set、get、delete操作。这里使用@RestController注解,表示这是一个REST风格的控制器,可以对外提供接口服务。 5. 运行应用程序 将应用程序打成jar包并运行,可以使用Postman等工具测试接口。测试方法如下: - 调用/set接口,传入key和value,将数据写入Redis中。 - 调用/get接口,传入key,获取Redis中保存的value。 - 调用/delete接口,传入key,删除Redis中保存的value。 以上是Spring Boot集成Redis实战过程。通过配置Redis依赖,设置Redis连接参数,编写Redis操作工具类和控制器,即可在Spring Boot应用程序中轻松使用RedisSpring Boot集成Redis可以提高应用程序的性能和扩展性,同时也可以减少数据库负载,是值得推荐的实践。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学海无涯,行者无疆

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值