SpringBoot-Jedis哨兵

1.application.properties

spring.redis.sentinel.nodes= ***:*, ***:*, ***:*
spring.redis.sentinel.password=*
spring.redis.sentinel.master=*
spring.redis.sentinel.command-timeout=10000
spring.redis.sentinel.max-attempts=2
spring.redis.sentinel.max-redirects=3
spring.redis.sentinel.max-active=16
spring.redis.sentinel.max-wait=3000
spring.redis.sentinel.max-idle=8
spring.redis.sentinel.min-idle=0
spring.redis.sentinel.test-on-borrow=true

2.RedisConfig

@Configuration
@ConditionalOnClass(JedisCluster.class)
public class RedisConfig {
    Logger logger = LoggerFactory.getLogger(RedisCacheConfiguration.class);

    @Resource
    private RedisProperties redisProperties;

    /**
     * 配置 Redis 連接池信息
     */
    @Bean
    public JedisPoolConfig getJedisPoolConfig() {
        JedisPoolConfig jedisPoolConfig =new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());
        jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWait());
        jedisPoolConfig.setTestOnBorrow(redisProperties.isTestOnBorrow());

        return jedisPoolConfig;
    }

    //哨兵
    @Bean
    public JedisSentinelPool jedisSentinelPool() {

        Set<String> nodeSet = new HashSet<>();
        String[] nodeStr = redisProperties.getNodes().split(",");
        for(String node:nodeStr){
            nodeSet.add(node);
        }
        //JedisSentinelPool其實本質(zhì)跟JedisPool類似誉帅,都是與redis主節(jié)點建立的連接池
        //JedisSentinelPool并不是說與sentinel建立的連接池淀散,而是通過sentinel發(fā)現(xiàn)redis主節(jié)點并與其建立連接
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxIdle(redisProperties.getMaxIdle());
        jedisPoolConfig.setMaxTotal(redisProperties.getMaxActive());
        jedisPoolConfig.setMinIdle(redisProperties.getMinIdle());
        jedisPoolConfig.setMaxWaitMillis(redisProperties.getMaxWait());
        return new JedisSentinelPool(redisProperties.getMaster(), nodeSet, jedisPoolConfig, redisProperties.getPassword());
    }
    /**
     * 設置數(shù)據(jù)存入redis 的序列化方式
     *  redisTemplate序列化默認使用的jdkSerializeable
     *  存儲二進制字節(jié)碼,導致key會出現(xiàn)亂碼蚜锨,所以自定義序列化類
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<Object, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);

        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.afterPropertiesSet();
        logger.info("redis cluster集群連接成功");
        return redisTemplate;
    }
}

3.RedisProperties

@Component
@ConfigurationProperties(prefix = "spring.redis.sentinel")
@Data
public class RedisProperties {

    private String nodes;

    private String password;

    private Integer commandTimeout;

    private Integer maxAttempts;

    private Integer maxRedirects;

    private Integer maxActive;

    private Integer maxWait;

    private Integer maxIdle;

    private Integer minIdle;

    private boolean testOnBorrow;

    private String master;

    public String getMaster() {
        return master;
    }

    public void setMaster(String master) {
        this.master = master;
    }

    public String getNodes() {
        return nodes;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public Integer getCommandTimeout() {
        return commandTimeout;
    }

    public void setCommandTimeout(Integer commandTimeout) {
        this.commandTimeout = commandTimeout;
    }

    public Integer getMaxAttempts() {
        return maxAttempts;
    }

    public void setMaxAttempts(Integer maxAttempts) {
        this.maxAttempts = maxAttempts;
    }

    public Integer getMaxRedirects() {
        return maxRedirects;
    }

    public void setMaxRedirects(Integer maxRedirects) {
        this.maxRedirects = maxRedirects;
    }

    public Integer getMaxActive() {
        return maxActive;
    }

    public void setMaxActive(Integer maxActive) {
        this.maxActive = maxActive;
    }

    public Integer getMaxWait() {
        return maxWait;
    }

    public void setMaxWait(Integer maxWait) {
        this.maxWait = maxWait;
    }

    public Integer getMaxIdle() {
        return maxIdle;
    }

    public void setMaxIdle(Integer maxIdle) {
        this.maxIdle = maxIdle;
    }

    public Integer getMinIdle() {
        return minIdle;
    }

    public void setMinIdle(Integer minIdle) {
        this.minIdle = minIdle;
    }

    public boolean isTestOnBorrow() {
        return testOnBorrow;
    }

    public void setTestOnBorrow(boolean testOnBorrow) {
        this.testOnBorrow = testOnBorrow;
    }

    @Override
    public String toString() {
        return "RedisProperties{" +
                "nodes='" + nodes + '\'' +
                ", password='" + password + '\'' +
                ", commandTimeout=" + commandTimeout +
                ", maxAttempts=" + maxAttempts +
                ", maxRedirects=" + maxRedirects +
                ", maxActive=" + maxActive +
                ", maxWait=" + maxWait +
                ", maxIdle=" + maxIdle +
                ", minIdle=" + minIdle +
                ", testOnBorrow=" + testOnBorrow +
                '}';
    }
}

4.JedisUtil

@Component
public class JedisUtil {
    private static final Logger LOGGER = LoggerFactory.getLogger(JedisUtil.class);
    @Autowired
    private JedisSentinelPool jedisSentinelPool;
    @Resource
    private RedisProperties redisProperties;

    public <T> void setObject(String key, int expireTime, T obj) {
       Jedis jedis = null;
        try {
            //獲取客戶端
            jedis = jedisSentinelPool.getResource();
            //執(zhí)行命令
            jedis.setex(key, expireTime, JSON.toJSONString(obj));
        } catch (Exception e) {
            LOGGER.error("JedisUtil setex error", e);
        }finally {
            if (jedis != null) {
                //這里使用的close不代表關閉連接档插,指的是歸還資源
                jedis.close();
            }
        }
    }

    public String getObject(String key) {
        Jedis jedis = null;
        try {
            //獲取客戶端
            jedis = jedisSentinelPool.getResource();
        } catch (Exception e) {
            LOGGER.error("JedisUtil get error", e);
        }finally {
            if (jedis != null) {
                jedis.close();
            }
        }
        return jedis.get(key);
    }
}
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市亚再,隨后出現(xiàn)的幾起案子郭膛,更是在濱河造成了極大的恐慌,老刑警劉巖氛悬,帶你破解...
    沈念sama閱讀 212,542評論 6 493
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件则剃,死亡現(xiàn)場離奇詭異,居然都是意外死亡如捅,警方通過查閱死者的電腦和手機棍现,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,596評論 3 385
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來伪朽,“玉大人轴咱,你說我怎么就攤上這事。” “怎么了朴肺?”我有些...
    開封第一講書人閱讀 158,021評論 0 348
  • 文/不壞的土叔 我叫張陵窖剑,是天一觀的道長。 經(jīng)常有香客問我戈稿,道長西土,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 56,682評論 1 284
  • 正文 為了忘掉前任鞍盗,我火速辦了婚禮需了,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘般甲。我一直安慰自己肋乍,他們只是感情好,可當我...
    茶點故事閱讀 65,792評論 6 386
  • 文/花漫 我一把揭開白布敷存。 她就那樣靜靜地躺著墓造,像睡著了一般。 火紅的嫁衣襯著肌膚如雪锚烦。 梳的紋絲不亂的頭發(fā)上觅闽,一...
    開封第一講書人閱讀 49,985評論 1 291
  • 那天,我揣著相機與錄音涮俄,去河邊找鬼蛉拙。 笑死,一個胖子當著我的面吹牛彻亲,可吹牛的內(nèi)容都是我干的孕锄。 我是一名探鬼主播,決...
    沈念sama閱讀 39,107評論 3 410
  • 文/蒼蘭香墨 我猛地睜開眼睹栖,長吁一口氣:“原來是場噩夢啊……” “哼硫惕!你這毒婦竟也來了?” 一聲冷哼從身側(cè)響起野来,我...
    開封第一講書人閱讀 37,845評論 0 268
  • 序言:老撾萬榮一對情侶失蹤恼除,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后曼氛,有當?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體豁辉,經(jīng)...
    沈念sama閱讀 44,299評論 1 303
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 36,612評論 2 327
  • 正文 我和宋清朗相戀三年舀患,在試婚紗的時候發(fā)現(xiàn)自己被綠了徽级。 大學時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 38,747評論 1 341
  • 序言:一個原本活蹦亂跳的男人離奇死亡聊浅,死狀恐怖餐抢,靈堂內(nèi)的尸體忽然破棺而出现使,到底是詐尸還是另有隱情,我是刑警寧澤旷痕,帶...
    沈念sama閱讀 34,441評論 4 333
  • 正文 年R本政府宣布碳锈,位于F島的核電站,受9級特大地震影響欺抗,放射性物質(zhì)發(fā)生泄漏售碳。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 40,072評論 3 317
  • 文/蒙蒙 一绞呈、第九天 我趴在偏房一處隱蔽的房頂上張望贸人。 院中可真熱鬧,春花似錦佃声、人聲如沸艺智。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,828評論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽力惯。三九已至,卻和暖如春召嘶,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背哮缺。 一陣腳步聲響...
    開封第一講書人閱讀 32,069評論 1 267
  • 我被黑心中介騙來泰國打工弄跌, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人尝苇。 一個月前我還...
    沈念sama閱讀 46,545評論 2 362
  • 正文 我出身青樓铛只,卻偏偏與公主長得像,于是被迫代替她去往敵國和親糠溜。 傳聞我的和親對象是個殘疾皇子淳玩,可洞房花燭夜當晚...
    茶點故事閱讀 43,658評論 2 350

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