springboot2 用lettuce客户端配置多个redisTemplate

  • Post author:
  • Post category:其他


MAVEN依赖

<dependency>

<groupId>org.springframework.boot</groupId>

<artifactId>spring-boot-starter-cache</artifactId>

</dependency>

<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>

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;

就可以使用了



版权声明:本文为jek123456原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。