单数据源版
1.引入依赖
<!--Web组件--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--Redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--Redis连接池--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.9.0</version></dependency>
2.yml文件增加配置
#Spring配 置spring:#Redis配置redis:host: 8.142.132.135port: 6379password:database: 0jedis:pool:max-active: 150max-wait: 100max-idle: 100min-idle: 50timeout: 5000ms
- max-active:最大激活连接数
- max-wait:连接最大等待时间
- max-idle:最大空闲连接数量
- min-idle:最小空闲连接数
3.增加配置类
```java import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
/**
- @author 冯铁城 [17615007230@163.com]
- @date 2022-05-06 16:18:18
@describe: Redis配置类 */ @Configuration public class RedisConfig {
@Bean @ConditionalOnMissingBean(name = “redisTemplate”) public RedisTemplate
redisTemplate(RedisConnectionFactory redisConnectionFactory) { //1.创建序列化类Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);jackson2JsonRedisSerializer.setObjectMapper(om);//2.设置序列化规则RedisTemplate<String, Object> template = new RedisTemplate<>();template.setConnectionFactory(redisConnectionFactory);template.setKeySerializer(jackson2JsonRedisSerializer);template.setValueSerializer(jackson2JsonRedisSerializer);template.setHashKeySerializer(jackson2JsonRedisSerializer);template.setHashValueSerializer(jackson2JsonRedisSerializer);template.afterPropertiesSet();//3.返回模板return template;
4.编写单元测试验证
```java import org.junit.Assert; import org.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.data.redis.core.RedisTemplate;
@SpringBootTest class RedistryApplicationTests {
@Autowiredprivate RedisTemplate<String, Object> redisTemplate;@Testvoid testRedis() {redisTemplate.opsForValue().set("key", "value");Object key = redisTemplate.opsForValue().get("key");Assert.assertNotNull(key);Assert.assertEquals("value", key);}
}
<a name="EH8UY"></a>## 多数据源版<a name="TTfJR"></a>### 1.引入依赖```xml<!--Web组件--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><!--Redis--><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId></dependency><!--Redis连接池--><dependency><groupId>org.apache.commons</groupId><artifactId>commons-pool2</artifactId><version>2.9.0</version></dependency>
2.yml文件增加配置
#配置Redis数据源(支持多数据源)redis:#默认Redis连接default-redis:host: 8.142.132.135port: 6379password:database: 0timeout: 6000max-active: 150max-wait: 100max-idle: 100min-idle: 50#其他Redis连接other-redis:host: 8.142.132.135port: 6379password:database: 1timeout: 6000max-active: 150max-wait: 100max-idle: 100min-idle: 50
3.添加Redis配置接口
/*** @author 冯铁城 [fengtiecheng@cyou-inc.com]* @date 2022-01-07 16:53:28* @describe:*/public interface RedisConfig {/*** 获取主机信息** @return*/String getHost();/*** 获取端口** @return*/int getPort();/*** 获取密码** @return*/String getPassword();/*** 获取数据库信息** @return*/int getDatabase();/*** 获取连接超时时间** @return*/long getTimeOut();/*** 获取最大激活连接数** @return*/int getMaxActive();/*** 获取最大等待时间** @return*/int getMaxWait();/*** 获取最大等待连接中的数量** @return*/int getMaxIdle();/*** 获取最小等待连接中的数量** @return*/int getMinIdle();}
4.添加Redis配置实现类
import lombok.Setter;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/*** @author 冯铁城 [fengtiecheng@cyou-inc.com]* @date 2022-01-07 16:59:24* @describe: 平台默认Redis配置*/@Component@ConfigurationProperties(prefix = "redis.default-redis")@Setterpublic class DefaultRedisConfig implements RedisConfig {/*** 主机信息*/private String host;/*** 端口*/private int port;/*** 密码*/private String password;/*** 数据库*/private int database;/*** 连接超时时间*/private long timeOut;/*** 最大激活连接数*/private int maxActive;/*** 最大等待时间*/private int maxWait;/*** 最大等待连接中的数量*/private int maxIdle;/*** 最小等待连接中的数量*/private int minIdle;@Overridepublic String getHost() {return this.host;}@Overridepublic int getPort() {return this.port;}@Overridepublic String getPassword() {return this.password;}@Overridepublic int getDatabase() {return this.database;}@Overridepublic long getTimeOut() {return this.timeOut;}@Overridepublic int getMaxActive() {return this.maxActive;}@Overridepublic int getMaxWait() {return this.maxWait;}@Overridepublic int getMaxIdle() {return this.maxIdle;}@Overridepublic int getMinIdle() {return this.minIdle;}}
import lombok.Setter;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.stereotype.Component;/*** @author 冯铁城 [fengtiecheng@cyou-inc.com]* @date 2022-01-07 16:59:24* @describe: 其他Redis配置*/@Component@ConfigurationProperties(prefix = "redis.other-redis")@Setterpublic class OtherRedisConfig implements RedisConfig {/*** 主机信息*/private String host;/*** 端口*/private int port;/*** 密码*/private String password;/*** 数据库*/private int database;/*** 连接超时时间*/private long timeOut;/*** 最大激活连接数*/private int maxActive;/*** 最大等待时间*/private int maxWait;/*** 最大等待连接中的数量*/private int maxIdle;/*** 最小等待连接中的数量*/private int minIdle;@Overridepublic String getHost() {return this.host;}@Overridepublic int getPort() {return this.port;}@Overridepublic String getPassword() {return this.password;}@Overridepublic int getDatabase() {return this.database;}@Overridepublic long getTimeOut() {return this.timeOut;}@Overridepublic int getMaxActive() {return this.maxActive;}@Overridepublic int getMaxWait() {return this.maxWait;}@Overridepublic int getMaxIdle() {return this.maxIdle;}@Overridepublic int getMinIdle() {return this.minIdle;}}
5.添加Redis连接生成工厂
import com.fasterxml.jackson.annotation.JsonAutoDetect;import com.fasterxml.jackson.annotation.PropertyAccessor;import com.fasterxml.jackson.databind.ObjectMapper;import org.apache.commons.pool2.impl.GenericObjectPoolConfig;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import org.springframework.data.redis.connection.RedisConnectionFactory;import org.springframework.data.redis.connection.RedisStandaloneConfiguration;import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;import org.springframework.data.redis.core.RedisTemplate;import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;import org.springframework.data.redis.serializer.StringRedisSerializer;import java.time.Duration;/*** @author 冯铁城 [fengtiecheng@cyou-inc.com]* @date 2022-01-07 17:33:43* @describe: 多数据源Redis工厂*/@Configurationpublic class RedisTemplateConstructor {@Autowired@Qualifier("defaultRedisConfig")private RedisConfig defaultRedisConfig;@Autowired@Qualifier("otherRedisConfig")private RedisConfig otherRedisConfig;/*** 创建默认RedisTemplate** @return 默认RedisTemplate*/@Bean(name = "defaultRedis")@Primarypublic RedisTemplate<String, Object> defaultRedisTemplate() {//1.创建连接工厂LettuceConnectionFactory connectionFactory = this.lettuceConnectionFactory(defaultRedisConfig);//2.创建RedisTemplate返回return this.createRedisTemplate(connectionFactory);}/*** 创建其他RedisTemplate** @return 默认RedisTemplate*/@Bean(name = "otherRedis")public RedisTemplate<String, Object> otherRedisTemplate() {//1.创建连接工厂LettuceConnectionFactory connectionFactory = this.lettuceConnectionFactory(otherRedisConfig);//2.创建RedisTemplate返回return this.createRedisTemplate(connectionFactory);}/*** 创建lettuce连接池工厂** @param redisConfig Redis配置* @return lettuce 连接池工厂*/private LettuceConnectionFactory lettuceConnectionFactory(RedisConfig redisConfig) {//1.线程池设置GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();poolConfig.setMaxTotal(redisConfig.getMaxActive());poolConfig.setMaxWaitMillis(redisConfig.getMaxWait());poolConfig.setMaxIdle(redisConfig.getMaxIdle());poolConfig.setMinIdle(redisConfig.getMinIdle());//2.线程池客户端设置LettuceClientConfiguration clientConfiguration = LettucePoolingClientConfiguration.builder().commandTimeout(Duration.ofSeconds(redisConfig.getTimeOut())).poolConfig(poolConfig).build();//3.Redis基础设置RedisStandaloneConfiguration configuration = new RedisStandaloneConfiguration();configuration.setHostName(redisConfig.getHost());configuration.setDatabase(redisConfig.getDatabase());configuration.setPassword(redisConfig.getPassword());configuration.setPort(redisConfig.getPort());//4.返回连接池工厂LettuceConnectionFactory lettuceConnectionFactory = new LettuceConnectionFactory(configuration, clientConfiguration);lettuceConnectionFactory.setShareNativeConnection(true);lettuceConnectionFactory.afterPropertiesSet();return lettuceConnectionFactory;}/*** 创建RedisTemplate并设置序列化规则** @param redisConnectionFactory redis连接池*/private RedisTemplate<String, Object> createRedisTemplate(RedisConnectionFactory redisConnectionFactory) {//1.创建Redis连接模板RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();//2.设置连接工厂redisTemplate.setConnectionFactory(redisConnectionFactory);//3.设置keyValue序列化规则redisTemplate.setKeySerializer(new StringRedisSerializer());redisTemplate.setValueSerializer(new StringRedisSerializer());//4.创建Hash序列化规则Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);ObjectMapper om = new ObjectMapper();om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);jackson2JsonRedisSerializer.setObjectMapper(om);//5.设置HashKeyValue序列化规则redisTemplate.setHashKeySerializer(jackson2JsonRedisSerializer);redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);//6.返回redisTemplate.afterPropertiesSet();return redisTemplate;}}
6.编写单元测试验证
import org.junit.Assert;import org.junit.jupiter.api.Test;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.beans.factory.annotation.Qualifier;import org.springframework.boot.test.context.SpringBootTest;import org.springframework.data.redis.core.RedisTemplate;@SpringBootTestclass RedistryApplicationTests {@Autowired@Qualifier("defaultRedis")private RedisTemplate<String, Object> defaultRedis;@Autowired@Qualifier("otherRedis")private RedisTemplate<String, Object> otherRedis;@Testvoid testRedis() {defaultRedis.opsForValue().set("defaultKey", "defaultValue");Object defaultKey = defaultRedis.opsForValue().get("defaultKey");Assert.assertNotNull(defaultKey);Assert.assertEquals("defaultValue", defaultKey);otherRedis.opsForValue().set("otherKey", "otherValue");Object otherKey = otherRedis.opsForValue().get("otherKey");Assert.assertNotNull(otherKey);Assert.assertEquals("otherValue", otherKey);}}
