【笔记】spring操作redis之jedis与lettuce

一、jedis与lettuce

1、Jedis:
在实现上是直连 redis server,多线程环境下非线程安全,除非使用连接池,为每个 redis实例增加 物理连接。
2、Lettuce:
是 一种可伸缩,线程安全,完全非阻塞的Redis客户端,多个线程可以共享一个RedisConnection,它利用Netty NIO 框架来高效地管理多个连接,从而提供了异步和同步数据访问方式,用于构建非阻塞的反应性应用程序。

二、连接池参数配置详情
GenericObjectPoolConfig  config = new GenericObjectPoolConfig();
//连接耗尽时是否阻塞, false报异常,ture阻塞直到超时, 默认true
config.setBlockWhenExhausted(true);
//设置的逐出策略类名, 默认DefaultEvictionPolicy(当连接超过最大空闲时间,或连接数超过最大空闲连接数)
config.setEvictionPolicyClassName("org.apache.commons.pool2.impl.DefaultEvictionPolicy");
//是否启用pool的jmx管理功能, 默认true
config.setJmxEnabled(true);
//是否启用后进先出, 默认true
config.setLifo(true);
//最大空闲连接数, 默认8个
config.setMaxIdle(10);
//最大连接数, 默认8个
config.setMaxTotal(50);
//获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
config.setMaxWaitMillis(30000);
//资源池中资源最小空闲时间(单位为毫秒),达到此值后空闲资源将被移除  默认1800000毫秒(30分钟)
config.setMinEvictableIdleTimeMillis(60000);
//最小空闲连接数, 默认0
config.setMinIdle(0);
//每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3
config.setNumTestsPerEvictionRun(3);
//对象空闲多久后逐出, 当空闲时间>该值 且 空闲连接>最大空闲数 时直接逐出,不再根据MinEvictableIdleTimeMillis判断  (默认逐出策略)
config.setSoftMinEvictableIdleTimeMillis(1800000);
//在获取连接的时候检查有效性, 默认false
config.setTestOnBorrow(false);
//是否开启空闲资源监测, 默认false
config.setTestWhileIdle(true);
//空闲资源的检测周期(单位为毫秒) 如果为负数,则不运行逐出线程, 默认-1
config.setTimeBetweenEvictionRunsMillis(-1);
三、redis连接池详细配置实现

1、yml文件配置

server:
  port: 10000

spring:
  redis:
    timeout: 1000
    host: 127.0.0.1
    database: 1
    password:
    lettuce:
      pool:
        max-wait: 2000
        max-idle: 10
        min-idle: 10
        max-active: 10
    port: 6379

2、redis连接池配置


@Configuration
@EnableCaching
public class RedisConfig   extends CachingConfigurerSupport {

    @Value("${spring.redis.database}")
    int database;
    @Value("${spring.redis.timeout}")
    long timeout;
    @Value("${spring.redis.lettuce.pool.max-active}")
    int maxActive;
    @Value("${spring.redis.lettuce.pool.max-wait}")
    int maxWait;
    @Value("${spring.redis.lettuce.pool.max-idle}")
    int maxIdle;
    @Value("${spring.redis.lettuce.pool.min-idle}")
    int minIdle;
    @Value("${spring.redis.host}")
    String hostName;
    @Value("${spring.redis.port}")
    int port;
    @Value("${spring.redis.password}")
    String password;

    @Bean
    public GenericObjectPoolConfig genericObjectPoolConfig() {
        GenericObjectPoolConfig config = new GenericObjectPoolConfig();
        config.setMaxIdle(maxIdle);
        config.setMaxTotal(maxActive);
        config.setMinIdle(minIdle);
        config.setMaxWaitMillis(maxWait);
        config.setBlockWhenExhausted();
        return config;
    }

    @Bean
    public RedisTemplate redisTemplate(GenericObjectPoolConfig config ) {

        RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();
        configuration.setHostName(hostName);
        configuration.setPort(port);
        configuration.setDatabase(database);
        if (!ObjectUtils.isEmpty(password)) {
            RedisPassword redisPassword = RedisPassword.of(password);
            configuration.setPassword(redisPassword);
        }

        /* ========= jedis pool ========= */
//        JedisClientConfiguration.DefaultJedisClientConfigurationBuilder builder = (JedisClientConfiguration.DefaultJedisClientConfigurationBuilder) JedisClientConfiguration
//                .builder();
//        builder.connectTimeout(Duration.ofSeconds(timeout));
//        builder.usePooling();
//        builder.poolConfig(genericObjectPoolConfig());
//        JedisConnectionFactory connectionFactory = new JedisConnectionFactory(configuration, builder.build());
//        connectionFactory.afterPropertiesSet();

        /* ========= lettuce pool ========= */

        LettucePoolingClientConfiguration lpc = LettucePoolingClientConfiguration.builder()
                                                                                   .commandTimeout(Duration.ofSeconds(timeout))
                                                                                   .poolConfig(config)
                                                                                   .build();
        LettuceConnectionFactory connectionFactory = new LettuceConnectionFactory(configuration, lpc);
        // 连接池初始化
        connectionFactory.afterPropertiesSet();
        return createRedisTemplate(connectionFactory);
    }

    public RedisTemplate createRedisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);

        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        //加入这段保证value对象不实现Serializable接口也可以序列化value
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        //保证key值用string 类型显示
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        return redisTemplate;
    }
   }
 
  

                            
                        
                    
                    
                    

你可能感兴趣的:(java,redis,spring,jedis,lettuce,连接池)