Spring boot配置多個Redis數據源操作實例
在SpringBoot是項目中整合了兩個Redis的操作實例,可以增加多個银亲;
一般在一個微服務生態(tài)群中是不會出現多個Redis中間件的捍靠,所以這種場景很少見助泽,但也不可避免楞慈,但是不建議使用旺嬉,個人建議败潦,勿噴本冲。
- 基于Maven3.0搭建准脂,spring1.5.9.RELEASE和JDK1.8
1、新建SpringBoot項目檬洞,添加依賴
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
2意狠、application.yml配置文件
spring:
redis:
database: 6 # Redis數據庫索引(默認為0)
host: redis.lilian.com # Redis服務器地址
port: 7481 # Redis服務器連接端口
password: # Redis服務器連接密碼(默認為空)
timeout: 0 # 連接超時時間(毫秒)
pool:
max-active: -1 # 連接池最大連接數(使用負值表示沒有限制)
max-wait: -1 # 連接池最大阻塞等待時間(使用負值表示沒有限制)
max-idle: 8 # 連接池中的最大空閑連接
min-idle: 0 # 連接池中的最小空閑連接
redis2:
database: 6 # Redis數據庫索引(默認為0)
host: redis.lilian.com # Redis服務器地址
port: 7480 # Redis服務器連接端口
password: # Redis服務器連接密碼(默認為空)
timeout: 0 # 連接超時時間(毫秒)
3、新建RedisConfig類
package com.lilian.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;
import java.lang.reflect.Method;
/**
* spring-boot-data-packing 設置Redis多實例的基類
*
* @Author 孫龍
* @Date 2018/8/13
*/
@EnableCaching
@Configuration
public class RedisConfig {
@Value("${spring.redis.pool.max-active}")
private int redisPoolMaxActive;
@Value("${spring.redis.pool.max-wait}")
private int redisPoolMaxWait;
@Value("${spring.redis.pool.max-idle}")
private int redisPoolMaxIdle;
@Value("${spring.redis.pool.min-idle}")
private int redisPoolMinIdle;
/**
* 配置Key的生成方式
*
* @return
*/
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object o, Method method, Object... objects) {
StringBuilder stringBuilder = new StringBuilder();
stringBuilder.append(o.getClass().getName())
.append(method.getName());
for (Object object : objects) {
stringBuilder.append(object.toString());
}
return stringBuilder.toString();
}
};
}
/**
* 創(chuàng)建redis連接工廠
*
* @param dbIndex
* @param host
* @param port
* @param password
* @param timeout
* @return
*/
public JedisConnectionFactory createJedisConnectionFactory(int dbIndex, String host, int port, String password, int timeout) {
JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
jedisConnectionFactory.setDatabase(dbIndex);
jedisConnectionFactory.setHostName(host);
jedisConnectionFactory.setPort(port);
jedisConnectionFactory.setPassword(password);
jedisConnectionFactory.setTimeout(timeout);
jedisConnectionFactory.setPoolConfig(setPoolConfig(redisPoolMaxIdle, redisPoolMinIdle, redisPoolMaxActive, redisPoolMaxWait, true));
return jedisConnectionFactory;
}
/**
* 配置CacheManager
*
* @param redisTemplate
* @return
*/
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate);
return redisCacheManager;
}
/**
* 設置連接池屬性
*
* @param maxIdle
* @param minIdle
* @param maxActive
* @param maxWait
* @param testOnBorrow
* @return
*/
public JedisPoolConfig setPoolConfig(int maxIdle, int minIdle, int maxActive, int maxWait, boolean testOnBorrow) {
JedisPoolConfig poolConfig = new JedisPoolConfig();
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setMaxTotal(maxActive);
poolConfig.setMaxWaitMillis(maxWait);
poolConfig.setTestOnBorrow(testOnBorrow);
return poolConfig;
}
/**
* 設置RedisTemplate的序列化方式
*
* @param redisTemplate
*/
public void setSerializer(RedisTemplate redisTemplate) {
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
//設置鍵(key)的序列化方式
redisTemplate.setKeySerializer(new StringRedisSerializer());
//設置值(value)的序列化方式
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
}
}
4疮胖、使用Java類注入多個數據源
- 數據源一
package com.lilian.config;
import org.springframework.beans.factory.annotation.Value;
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.core.RedisTemplate;
/**
* llld-parent 配置默認Redis操作實例 到Spring中
*
* @Author 孫龍
* @Date 2018/8/2
*/
@Configuration
@EnableCaching
public class DefaultRedisConfig extends RedisConfig {
@Value("${spring.redis.database}")
private int dbIndex;
@Value("${spring.redis.host}")
private String host;
@Value("${spring.redis.port}")
private int port;
@Value("${spring.redis.password}")
private String password;
@Value("${spring.redis.timeout}")
private int timeout;
/**
* 配置redis連接工廠
*
* @return
*/
@Bean
public RedisConnectionFactory defaultRedisConnectionFactory() {
return createJedisConnectionFactory(dbIndex, host, port, password, timeout);
}
/**
* 配置redisTemplate 注入方式使用@Resource(name="") 方式注入
*
* @return
*/
@Bean(name = "defaultRedisTemplate")
public RedisTemplate defaultRedisTemplate() {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(defaultRedisConnectionFactory());
setSerializer(template);
template.afterPropertiesSet();
return template;
}
}
- 數據源二
package com.lilian.config;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.annotation.EnableCaching;
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.core.RedisTemplate;
/**
* llld-parent 配置緩存Redis操作實例 到Spring中
*
* @Author 孫龍
* @Date 2018/8/2
*/
@Configuration
@EnableCaching
public class CacheRedisConfig extends RedisConfig {
@Value("${spring.redis2.database}")
private int dbIndex;
@Value("${spring.redis2.host}")
private String host;
@Value("${spring.redis2.port}")
private int port;
@Value("${spring.redis2.password}")
private String password;
@Value("${spring.redis2.timeout}")
private int timeout;
/**
* 配置redis連接工廠
*
* @return
*/
@Primary
@Bean
public RedisConnectionFactory cacheRedisConnectionFactory() {
return createJedisConnectionFactory(dbIndex, host, port, password, timeout);
}
/**
* 配置redisTemplate 注入方式使用@Resource(name="") 方式注入
*
* @return
*/
@Bean(name = "cacheRedisTemplate")
public RedisTemplate cacheRedisTemplate() {
RedisTemplate template = new RedisTemplate();
template.setConnectionFactory(cacheRedisConnectionFactory());
setSerializer(template);
template.afterPropertiesSet();
return template;
}
}
- 數據源三同理环戈。。澎灸。
5院塞、隨便定義一個實體類
package com.lilian.entity;
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* jpa-demo
*
* @Author 孫龍
* @Date 2018/7/3
*/
@Data
@AllArgsConstructor
public class Person {
/**
* 姓名
*/
private String name;
/**
* 年齡
*/
private Integer age;
/**
* 地址
*/
private String address;
/**
* 郵箱
*/
private String email;
/**
* 手機號碼
*/
private String phoneNum;
}
6、測試方法
package com.lilian;
import com.lilian.entity.Person;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
import javax.annotation.Resource;
/**
* spring-boot-data-packing
*
* @Author 孫龍
* @Date 2018/8/13
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class MultiRedisTest {
@Resource(name = "defaultRedisTemplate")
private RedisTemplate<String, Object> redisTemplate;
@Resource(name = "cacheRedisTemplate")
private RedisTemplate<String, Object> redisTemplate1;
@Test
public void stringRedisTest() {
redisTemplate.opsForValue().set("slzzzz", "111111");
redisTemplate1.opsForValue().set("slzzzz", "222222");
}
@Test
public void objectRedisTest() {
redisTemplate.opsForValue().set("person", new Person("李飛", 20, "臨汾", "lf@lilian.com", "1324567891"));
redisTemplate1.opsForValue().set("person", new Person("李大壯", 35, "西安", "ldz@lilian.com", "1324567891"));
}
}
7性昭、結果
使用redis可視化工具查看是否成功拦止;
聲明:該博文是自己結合其他博主經驗自己實踐的一些總結,希望能幫到你糜颠,如果幫到你請幫我點一個星星汹族;
Github代碼示例
參考博客:http://www.cnblogs.com/lchb/articles/7222870.html