Springboot2.x集成Redis集群模式

Springboot2.x集成Redis集群模式

說明

Redis集群模式是Redis高可用方案的一種實現(xiàn)方式,通過集群模式可以實現(xiàn)Redis數(shù)據(jù)多處存儲蛀柴,以及自動的故障轉(zhuǎn)移。如果想了解更多集群模式的相關(guān)知識介紹咽块,歡迎往上爬樓氯庆。

準(zhǔn)備條件

pom.xml中引入相關(guān)jar

        <!-- 集成Redis -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-redis</artifactId>
        </dependency>
    
        <!-- Jedis 客戶端 -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
        </dependency>
    
        <!-- lettuce客戶端需要使用到 -->
          <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-pool2</artifactId>
           </dependency>

application.yml集群模式配置屬性示例裁良。

spring:
  redis:
    host: 192.168.8.121
    port: 6379
    password: enjoyitlife
    timeout: 30000
    jedis:
      pool:
        max-active: 256
        max-wait: 30000
        max-idle: 64
        min-idle: 32
    lettuce:
      pool:
        max-active: 256
        max-idle: 64
        max-wait: 30000
        min-idle: 32
    cluster:
      nodes:
      - 192.168.8.121:7000
      - 192.168.8.121:7001
      - 192.168.8.121:7002
      - 192.168.8.121:7003
      - 192.168.8.121:7004
      - 192.168.8.121:7005
      - 192.168.8.121:7006
      - 192.168.8.121:7007

nodes節(jié)點讀取瓤漏。因為nodes是集合方式腾夯,所以spring中的@value$("xxx.xxx.xx")是無法讀取的,本文提供了一種獲取改節(jié)點屬性的方式蔬充。

RedisClusterNodesCfg.java 獲取nodes節(jié)點數(shù)據(jù)的代碼示例蝶俱。

package top.enjoyitlife.redis;

import java.util.List;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

@Component
@ConfigurationProperties(prefix = "spring.redis.cluster")
public class RedisClusterNodesCfg {

        private List<String> nodes;

        public List<String> getNodes() {
            return nodes;
        }

        public void setNodes(List<String> nodes) {
            this.nodes = nodes;
        }
    
}

集群模式下的整合教程

Jedis客戶端整合

JedisClusterConfig.java 相關(guān)配置

package top.enjoyitlife.redis.jedis;

import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import top.enjoyitlife.redis.RedisClusterNodesCfg;

@Configuration
@Profile("JedisCluster")
public class JedisClusterConfig {
    
    @Autowired
     private RedisClusterNodesCfg redisClusterNodesCfg;
    
     @Bean
     public JedisConnectionFactory redisPoolFactory()  throws Exception{
            RedisClusterConfiguration rcc=new RedisClusterConfiguration();
            List<String> nodesList=redisClusterNodesCfg.getNodes();
            String host=null;
            int port=0;
            for(String node:nodesList) {
                host=node.split(":")[0];
                port=Integer.valueOf(node.split(":")[1]);
                rcc.addClusterNode(new RedisNode(host,port));
            }
            return new JedisConnectionFactory(rcc);
     }
    
     @Bean
        public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
            RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
            template.setKeySerializer(new StringRedisSerializer());
            template.setValueSerializer(new StringRedisSerializer());
            template.setConnectionFactory(redisConnectionFactory);
            return template;
        }
     
     
}

Lettuce客戶端整合

package top.enjoyitlife.redis.lettuce;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisNode;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import top.enjoyitlife.redis.RedisClusterNodesCfg;

@Configuration
@Profile("lettuceCluster")
public class LettuceClusterConfig {
    
    @Autowired
     private RedisClusterNodesCfg redisClusterNodesCfg;
    
    
    @Bean
    public LettuceConnectionFactory redisConnectionFactory() {
        RedisClusterConfiguration rcc=new RedisClusterConfiguration();
        List<String> nodesList=redisClusterNodesCfg.getNodes();
        String host=null;
        int port=0;
        for(String node:nodesList) {
            host=node.split(":")[0];
            port=Integer.valueOf(node.split(":")[1]);
            rcc.addClusterNode(new RedisNode(host,port));
        }
        return new LettuceConnectionFactory(rcc);
    }
    

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new StringRedisSerializer());
        template.setConnectionFactory(redisConnectionFactory);
        return template;
    }
}

Springboot通過RedisClusterConfiguration來統(tǒng)一了連接集群的方式,區(qū)別Jedis客戶端是通過JedisConnectionFactory進(jìn)行初始化饥漫,而Lettuce客戶端是通過LettuceConnectionFactory初始化榨呆。

單元測試

Jedis單元測試

package top.enjoyitlife.redis.jedis;
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;
import org.springframework.test.context.ActiveProfiles;

@SpringBootTest
@ActiveProfiles("JedisCluster")
class JedisClusterTest {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Test
    void contextLoads() {
        String name=redisTemplate.opsForValue().get("name").toString();
        redisTemplate.opsForValue().set("hahha", "enjoyitlife2020");
        System.out.println(name);
    }
}

Lettuce 單元測試

package top.enjoyitlife.redis.lettuce;

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;
import org.springframework.test.context.ActiveProfiles;


@SpringBootTest
@ActiveProfiles("lettuceCluster")
class LettuceClusterTest {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    
    @Test
    void contextLoads() {
        String name = redisTemplate.opsForValue().get("name").toString();
        System.out.println(name);
    }

}

好了以上就是Springboot2.x集成Redis集群模式的代碼示例,希望對你能有所幫助趾浅。謝謝閱讀愕提。

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末馒稍,一起剝皮案震驚了整個濱河市皿哨,隨后出現(xiàn)的幾起案子浅侨,更是在濱河造成了極大的恐慌,老刑警劉巖证膨,帶你破解...
    沈念sama閱讀 218,525評論 6 507
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件如输,死亡現(xiàn)場離奇詭異,居然都是意外死亡央勒,警方通過查閱死者的電腦和手機(jī)不见,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,203評論 3 395
  • 文/潘曉璐 我一進(jìn)店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來崔步,“玉大人稳吮,你說我怎么就攤上這事【簦” “怎么了灶似?”我有些...
    開封第一講書人閱讀 164,862評論 0 354
  • 文/不壞的土叔 我叫張陵,是天一觀的道長瑞你。 經(jīng)常有香客問我酪惭,道長,這世上最難降的妖魔是什么者甲? 我笑而不...
    開封第一講書人閱讀 58,728評論 1 294
  • 正文 為了忘掉前任春感,我火速辦了婚禮,結(jié)果婚禮上虏缸,老公的妹妹穿的比我還像新娘鲫懒。我一直安慰自己,他們只是感情好刽辙,可當(dāng)我...
    茶點故事閱讀 67,743評論 6 392
  • 文/花漫 我一把揭開白布窥岩。 她就那樣靜靜地躺著,像睡著了一般扫倡。 火紅的嫁衣襯著肌膚如雪谦秧。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 51,590評論 1 305
  • 那天撵溃,我揣著相機(jī)與錄音疚鲤,去河邊找鬼。 笑死缘挑,一個胖子當(dāng)著我的面吹牛集歇,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播语淘,決...
    沈念sama閱讀 40,330評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼诲宇,長吁一口氣:“原來是場噩夢啊……” “哼际歼!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起姑蓝,我...
    開封第一講書人閱讀 39,244評論 0 276
  • 序言:老撾萬榮一對情侶失蹤鹅心,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后纺荧,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體旭愧,經(jīng)...
    沈念sama閱讀 45,693評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,885評論 3 336
  • 正文 我和宋清朗相戀三年宙暇,在試婚紗的時候發(fā)現(xiàn)自己被綠了输枯。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 40,001評論 1 348
  • 序言:一個原本活蹦亂跳的男人離奇死亡占贫,死狀恐怖桃熄,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情型奥,我是刑警寧澤瞳收,帶...
    沈念sama閱讀 35,723評論 5 346
  • 正文 年R本政府宣布,位于F島的核電站桩引,受9級特大地震影響缎讼,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜坑匠,卻給世界環(huán)境...
    茶點故事閱讀 41,343評論 3 330
  • 文/蒙蒙 一血崭、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧厘灼,春花似錦夹纫、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,919評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至闪朱,卻和暖如春月匣,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背奋姿。 一陣腳步聲響...
    開封第一講書人閱讀 33,042評論 1 270
  • 我被黑心中介騙來泰國打工锄开, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人称诗。 一個月前我還...
    沈念sama閱讀 48,191評論 3 370
  • 正文 我出身青樓萍悴,卻偏偏與公主長得像,于是被迫代替她去往敵國和親绰上。 傳聞我的和親對象是個殘疾皇子启搂,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,955評論 2 355

推薦閱讀更多精彩內(nèi)容