springboot2 用lettuce客户端配置多个redisTemplate

MAVEN依赖


    org.springframework.boot
    spring-boot-starter-cache


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


    org.apache.commons
    commons-pool2

 

application.yml配置文件

spring:

  redis:
    activity: 
      hostName: 127.0.0.1
      port: 1000
      password: dddsiedXdf
    lettuce: 
      pool: 
        maxIdle: 10
        minIdle: 0
        maxTotal: 20
        maxWaitMillis: 5000

配置类:

@Configuration
public class RedisConfig {
    
    @Bean
    @ConfigurationProperties(prefix = "spring.redis.lettuce.pool")
    @Scope(value = "prototype")
    public GenericObjectPoolConfig redisPool(){
        return new GenericObjectPoolConfig();
    }
    
    @Bean
    @ConfigurationProperties(prefix = "spring.redis.activity")
    public RedisStandaloneConfiguration redisConf() {
        return new RedisStandaloneConfiguration();
    }
    
    @Bean
    @Primary
    public LettuceConnectionFactory factory(GenericObjectPoolConfig config, RedisStandaloneConfiguration redisConf) {
        LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder()
                .poolConfig(config).commandTimeout(Duration.ofMillis(config.getMaxWaitMillis())).build();
        return new LettuceConnectionFactory(redisConf, clientConfiguration);
    }
    
    @Bean(name = "redisTemplate")
    public StringRedisTemplate redisTemplateA(LettuceConnectionFactory factory) {
        StringRedisTemplate template = new StringRedisTemplate(factory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        template.setHashValueSerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        return template;
    }
}

 

在业务类里引入redisTemplate:

@Resource
    private RedisTemplate redisTemplate;

就可以使用了

你可能感兴趣的:(JAVA缓存与数据库)