1. 程式人生 > >Spring boot配置多個Redis資料來源操作例項

Spring boot配置多個Redis資料來源操作例項

原文:https://www.jianshu.com/p/c79b65b253fa

 

 

Spring boot配置多個Redis資料來源操作例項

在SpringBoot是專案中整合了兩個Redis的操作例項,可以增加多個;
一般在一個微服務生態群中是不會出現多個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(); } }; } /** * 建立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, "臨汾", "[email protected]", "1324567891")); redisTemplate1.opsForValue().set("person", new Person("李大壯", 35, "西安", "[email protected]", "1324567891")); } } 

7、結果

使用redis視覺化工具檢視是否成功;

 

  redisresult.jpg