SpringBoot整合redis连接池Jedis和lettuce连接池 SpringBoot使用Jedis连接池或者使用lettuce连接池SpringBoot整合Jedis和lettuce连接池

本文详细介绍了如何在SpringBoot应用中使用Lettuce和Jedis连接池,并提供了配置示例,以及如何自定义RedisTemplate以支持不同的序列化策略。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

SpringBoot整合redis连接池Jedis和lettuce连接池 SpringBoot使用Jedis连接池或者使用lettuce连接池SpringBoot整合Jedis和lettuce连接池

1、使用 Lettuce连接池

Lettuce是Springboot - redis默认使用的连接池

公共依赖

	
	<!--连接池依赖-->
	<dependency>
		<groupId>org.apache.commons</groupId>
		<artifactId>commons-pool2</artifactId>
	</dependency>
	
	<!--JAVA 8 日期格式化 -->
	<dependency>
	    <groupId>com.fasterxml.jackson.datatype</groupId>
	    <artifactId>jackson-datatype-jsr310</artifactId>
	</dependency>

1.1、加入依赖

        <!--redis依赖- 默认使用lettuce-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>

1.2、连接池配置

spring:
  redis:
    # 地址
    host: 127.0.0.1
    # 端口号
    port: 6379
    # 密码
    password:
    # 超时时间,单位毫秒
    timeout: 10000
    # 数据库编号
    database: 1
    # 配置lettuce
    lettuce:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 0
        # 连接池中的最大空闲连接
        max-idle: 5
        # 连接池最大连接数(使用负值表示没有限制,不要配置过大,否则可能会影响redis的性能)
        max-active: 40
        # 连接池最大阻塞等待时间(使用负值表示没有限制);单位毫秒
        max-wait: 5000
        #设置驱逐空闲连接的时间间隔
        time-between-eviction-runs: 30000
      #关闭超时时间;单位毫秒
      shutdown-timeout: 5000

2、使用Jedis连接池

1.1、加入依赖

注意jedis的版本,我使用的SpringBoot版本是 2.1.X对应的版本在 2.9.x,请根据自己不同版本对应
不然启动会异常

        <!--redis依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
            <!-- 不使用lettuce连接池,改为jedis -->
            <exclusions>
                <exclusion>
                    <groupId>io.lettuce</groupId>
                    <artifactId>lettuce-core</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <!-- Jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.1</version>
        </dependency>

2.2、连接池配置

spring:
  redis:
    # 地址
    host: 127.0.0.1
    # 端口号
    port: 6379
    # 密码
    password:
    # 超时时间,单位毫秒
    timeout: 10000
    # 数据库编号
    database: 1
    # 配置 jedis
    jedis:
      pool:
        # 连接池中的最小空闲连接
        min-idle: 0
        # 连接池中的最大空闲连接
        max-idle: 5
        # 连接池最大连接数(使用负值表示没有限制,不要配置过大,否则可能会影响redis的性能)
        max-active: 40
        # 连接池最大阻塞等待时间(使用负值表示没有限制);单位毫秒
        max-wait: 5000
        #设置驱逐空闲连接的时间间隔
        time-between-eviction-runs: 30000

3、配置 自定义 redisTemplate模版

键使用String序列化,value使用 Jackson2JsonRedisSerializer序列号,也可以使用其他的序列化器

可以在 Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class); 这行代码打一个断点测试,查看redisConnectionFactory 连接池使用的是 Jedis还是lettuce

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateDeserializer;
import com.fasterxml.jackson.datatype.jsr310.deser.LocalDateTimeDeserializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateSerializer;
import com.fasterxml.jackson.datatype.jsr310.ser.LocalDateTimeSerializer;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.listener.RedisMessageListenerContainer;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Redis配置
 */
@Configuration
@EnableCaching
public class redisConfig {
	
	/**
	 * 构造自定义RedisTemplate
	 *
	 * @param redisConnectionFactory redis连接工厂,默认为Lettuce
	 * @return key使用String序列化,value使用 Jackson2JsonRedisSerializer<Object>
	 */
	@Bean
	RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
		
		Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
		
		ObjectMapper om = new ObjectMapper();
		
		om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
		
		// 激活默认的类型信息处理
		om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
		
		// LocalDatetime序列化
		JavaTimeModule timeModule = new JavaTimeModule();
		timeModule.addDeserializer(LocalDate.class, new LocalDateDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
		timeModule.addDeserializer(LocalDateTime.class, new LocalDateTimeDeserializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
		timeModule.addSerializer(LocalDate.class, new LocalDateSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
		timeModule.addSerializer(LocalDateTime.class, new LocalDateTimeSerializer(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));
		
		om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
		om.registerModule(timeModule);
		
		jackson2JsonRedisSerializer.setObjectMapper(om);
		RedisTemplate<String, Object> template = new RedisTemplate<>();
		template.setConnectionFactory(redisConnectionFactory);
		
		// key序列化器
		template.setKeySerializer(new StringRedisSerializer());
		template.setHashKeySerializer(new StringRedisSerializer());
		
		// value序列化器
		template.setValueSerializer(jackson2JsonRedisSerializer);
		template.setHashValueSerializer(jackson2JsonRedisSerializer);
		
		template.afterPropertiesSet();
		return template;
	}
}

4、使用

@RestController
public class Controller {
	
	private final RedisTemplate<String, Object> redisTemplate;
	
	public Controller (RedisTemplate<String, Object> redisTemplate){
		this.redisTemplate = redisTemplate;
	}
	
	/**
	 * 存储字符串到redis
	 */
	@GetMapping(value = "/set")
	public String set() {
		redisTemplate.opsForValue().set("test:set", "测试值");
		return "success";
	}
}
<< Spring Boot使用 Redis 连接池通常是基于 `lettuce` 或者 `jedis` 客户端实现的,默认情况下 Spring Boot 使用的是 Lettuce(从 2.x 版本开始)。Redis 连接池的主要目的是为了管理与 Redis 的连接,避免每次请求都创建销毁新的连接,从而提升性能并减少资源消耗。 ### 如何配置 Redis 连接池? #### 方法一:直接通过 `application.properties` 配置文件 ```properties # Redis服务器地址 spring.redis.host=localhost # Redis服务器端口 spring.redis.port=6379 # 设置最大空闲连接数 spring.redis.lettuce.pool.max-idle=5 # 设置最小空闲连接数 spring.redis.lettuce.pool.min-idle=0 # 设置最大连接数 spring.redis.lettuce.pool.max-active=8 # 最大等待时间 spring.redis.lettuce.pool.max-wait=-1ms ``` 以上配置项中: - **max-idle**:控制池中的空闲连接的最大数量。 - **min-idle**:控制池中的最低空闲连接的数量。 - **max-active**:设置同时活动连接的最大数目。 - **max-wait**:当池用完时,连接获取的最大等待时间。如果为 `-1ms` 表示无限期等待。 如果你仍然想使用 Jedis,则可以将依赖替换为 jedis,并调整相应的属性名称到 `spring.redis.jedis.*` 命名空间下。 #### 方法二:自定义配置类 你可以手动定制更复杂的 Redis 池参数,比如以下是一个基于 Java Config 的例子: ```java import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisStandaloneConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration; import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory; import io.lettuce.core.ClientOptions; @Configuration public class RedisConfig { @Bean public LettuceConnectionFactory redisConnectionFactory() { // 配置 Redis 单机模式 (也可以修改为集群模式) RedisStandaloneConfiguration standaloneConf = new RedisStandaloneConfiguration("localhost", 6379); // 自定义 lettuce pool 参数 LettuceClientConfiguration clientConfig = LettuceClientConfiguration.builder() .clientOptions(ClientOptions.builder().disconnectedBehavior(ClientOptions.DisconnectedBehavior.REJECT_COMMANDS).build()) .build(); return new LettuceConnectionFactory(standaloneConf, clientConfig); } } ``` 此外还可以引入 Apache Commons Pool 来进一步增强对连接池的支持: ```xml <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> </dependency> ``` 然后可以通过 `GenericObjectPoolConfig` 对其进行详细配置: ```java @Bean public GenericObjectPoolConfig<?> genericObjectPoolConfig(){ var config = new GenericObjectPoolConfig<>(); config.setMaxTotal(10); // 总共可用连接数限制为 10 config.setMinIdle(5); // 至少保持 5个闲置链接不被回收 return config; } ``` 最后将其注入到 Redis 配置工厂即可生效. --- ### 解释: 1. 在分布式系统架构设计里,缓存服务是非常重要的一环,而 Redis 是最流行的内存数据库之一; 2. 访问频率高的业务场景通常会对后端存储带来压力,这时就需要借助像 Redis 这样的中间件来缓解; 3. 同样由于频繁访问造成过多线程阻塞、上下文切换等问题也需要合理利用连接池技术去优化性能表现; 因此正确地配置好 Redis 连接池对于保证应用稳定性提高吞吐量至关重要。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值