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";
	}
}

更多推荐