Spring boot配置多個Redis數據源操作實例

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可視化工具查看是否成功拦止;

redisresult.jpg

聲明:該博文是自己結合其他博主經驗自己實踐的一些總結,希望能幫到你糜颠,如果幫到你請幫我點一個星星汹族;
Github代碼示例
參考博客:http://www.cnblogs.com/lchb/articles/7222870.html

?著作權歸作者所有,轉載或內容合作請聯系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市其兴,隨后出現的幾起案子顶瞒,更是在濱河造成了極大的恐慌,老刑警劉巖元旬,帶你破解...
    沈念sama閱讀 206,968評論 6 482
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件榴徐,死亡現場離奇詭異,居然都是意外死亡匀归,警方通過查閱死者的電腦和手機坑资,發(fā)現死者居然都...
    沈念sama閱讀 88,601評論 2 382
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來穆端,“玉大人袱贮,你說我怎么就攤上這事√鍐” “怎么了攒巍?”我有些...
    開封第一講書人閱讀 153,220評論 0 344
  • 文/不壞的土叔 我叫張陵,是天一觀的道長狡赐。 經常有香客問我窑业,道長,這世上最難降的妖魔是什么枕屉? 我笑而不...
    開封第一講書人閱讀 55,416評論 1 279
  • 正文 為了忘掉前任常柄,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘西潘。我一直安慰自己卷玉,他們只是感情好,可當我...
    茶點故事閱讀 64,425評論 5 374
  • 文/花漫 我一把揭開白布喷市。 她就那樣靜靜地躺著相种,像睡著了一般。 火紅的嫁衣襯著肌膚如雪品姓。 梳的紋絲不亂的頭發(fā)上寝并,一...
    開封第一講書人閱讀 49,144評論 1 285
  • 那天,我揣著相機與錄音腹备,去河邊找鬼衬潦。 笑死,一個胖子當著我的面吹牛植酥,可吹牛的內容都是我干的镀岛。 我是一名探鬼主播,決...
    沈念sama閱讀 38,432評論 3 401
  • 文/蒼蘭香墨 我猛地睜開眼友驮,長吁一口氣:“原來是場噩夢啊……” “哼漂羊!你這毒婦竟也來了?” 一聲冷哼從身側響起卸留,我...
    開封第一講書人閱讀 37,088評論 0 261
  • 序言:老撾萬榮一對情侶失蹤走越,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后艾猜,有當地人在樹林里發(fā)現了一具尸體买喧,經...
    沈念sama閱讀 43,586評論 1 300
  • 正文 獨居荒郊野嶺守林人離奇死亡捻悯,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 36,028評論 2 325
  • 正文 我和宋清朗相戀三年匆赃,在試婚紗的時候發(fā)現自己被綠了。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片今缚。...
    茶點故事閱讀 38,137評論 1 334
  • 序言:一個原本活蹦亂跳的男人離奇死亡算柳,死狀恐怖,靈堂內的尸體忽然破棺而出姓言,到底是詐尸還是另有隱情瞬项,我是刑警寧澤,帶...
    沈念sama閱讀 33,783評論 4 324
  • 正文 年R本政府宣布何荚,位于F島的核電站囱淋,受9級特大地震影響,放射性物質發(fā)生泄漏餐塘。R本人自食惡果不足惜妥衣,卻給世界環(huán)境...
    茶點故事閱讀 39,343評論 3 307
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧税手,春花似錦蜂筹、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,333評論 0 19
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至兵扬,卻和暖如春麻裳,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背器钟。 一陣腳步聲響...
    開封第一講書人閱讀 31,559評論 1 262
  • 我被黑心中介騙來泰國打工掂器, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人俱箱。 一個月前我還...
    沈念sama閱讀 45,595評論 2 355
  • 正文 我出身青樓国瓮,卻偏偏與公主長得像,于是被迫代替她去往敵國和親狞谱。 傳聞我的和親對象是個殘疾皇子乃摹,可洞房花燭夜當晚...
    茶點故事閱讀 42,901評論 2 345

推薦閱讀更多精彩內容