Redis哨兵模式高可用部署和配置

1、Redis 安裝配置

1.下載redis安裝包 wget http://download.redis.io/releases/redis-4.0.9.tar.gzjava

2.解壓安裝包 tar -zxvf redis-4.0.9.tar.gz -C /usr/local/node

3.安裝gcc依賴redis

先經過gcc -v是否有安裝gcc,若是沒有安裝,執行命令sudo yum install -y gccspring

4.cd到redis的解壓目錄下,並執行緩存

cd /usr/local/redis-4.0.9/ 此處目錄根據下載的redis版本及解壓路徑調整bash

5.編譯安裝服務器

make MALLOC=libcapp

將/usr/local/redis-4.0.9/src目錄下的文件加到/usr/local/bin目錄ide

cd src && make install測試

6.測試是否安裝成功

cd /usr/local/redis-4.0.9/src/

./redis-server

2、Redis主從複製配置

master的redis.conf文件(其他是默認設置)

port 6379
daemonize yes
# 這個文件夾要改爲本身的目錄
dir "/home/redis/redis_master_s"

slaver1和slaver2的redis.conf文件

port 6378
# 主服務器端口爲6379
slaveof 127.0.0.1 6379
dir "/home/redis/redis_slaver1_s"
port 6377
# 主服務器端口爲6379
slaveof 127.0.0.1 6379
dir "/home/redis/redis_slaver2_s"

這個主從服務器就配置好了。

啓動服務

./redis-server redis.conf

 此時Redis的主從複製配置完畢,主從複製的功能: 
1. 主服務器寫入,從服務器能夠讀取到 
2. 從服務器不能寫入

3、Redis的哨兵模式配置

sentinel是哨兵,用於監視主從服務器的運行情況,若是主服務器掛掉,會在從服務器中選舉一個做爲主服務器。 
配置文件以下 
master的sentinel.conf

port 26379
# 初次配置時的狀態,這個sentinel會自動更新
sentinel monitor mymaster 127.0.0.1 6379 2
daemonize yes
logfile "./sentinel_log.log"
sentinel down-after-milliseconds mymaster 10000
sentinel failover-timeout mymaster 10000
sentinel config-epoch mymaster 2
bind 192.168.171.128 127.0.0.1
sentinel leader-epoch mymaster 2

slaver1和slaver2的sentinel.conf

port 26378
# 初次配置時的狀態,這個sentinel會自動更新
sentinel monitor mymaster 127.0.0.1 6379 2
daemonize yes
logfile "./sentinel_log.log"
sentinel down-after-milliseconds mymaster 10000
sentinel failover-timeout mymaster 10000
sentinel config-epoch mymaster 2
bind 192.168.171.128 127.0.0.1
sentinel leader-epoch mymaster 2

再次啓動redis全部的服務端

./redis-server redis.conf
./redis-server sentinel.conf --sentinel

分別開啓redis的客戶端

./redis-cli
./redis-cli -h 127.0.0.1 -p 6378
./redis-cli -h 127.0.0.1 -p 6377

使用一下命令查看三個redis服務的狀態

info replication  

 4、代碼支持

RedisCacheConfig

package com.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.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.cache.annotation.CachingConfigurerSupport;
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.RedisNode;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
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 java.lang.reflect.Method;

/**
 * @author David
 */
@Configuration
@EnableAutoConfiguration
@EnableCaching //加上這個註解是的支持緩存註解
public class RedisCacheConfig extends CachingConfigurerSupport {

    @Value("${spring.redis.host}")
    private String host;

    @Value("${spring.redis.port}")
    private int port;

    @Value("${spring.redis.timeout}")
    private int timeout;

    @Value("${spring.redis.database}")
    private int database;

    @Value("${spring.redis.password}")
    private String password;

    @Value("${spring.redis.sentinel.nodes}")
    private String redisNodes;

    @Value("${spring.redis.sentinel.master}")
    private String master;


    /**
     * redis哨兵配置
     * @return
     */
    @Bean
    public RedisSentinelConfiguration redisSentinelConfiguration(){
        RedisSentinelConfiguration configuration = new RedisSentinelConfiguration();
        String[] host = redisNodes.split(",");
        for(String redisHost : host){
            String[] item = redisHost.split(":");
            String ip = item[0];
            String port = item[1];
            configuration.addSentinel(new RedisNode(ip, Integer.parseInt(port)));
        }
        configuration.setMaster(master);
        return configuration;
    }

    /**
     * 鏈接redis的工廠類
     *
     * @return
     */
    @Bean
    public JedisConnectionFactory jedisConnectionFactory() {
        JedisConnectionFactory factory = new JedisConnectionFactory(redisSentinelConfiguration());
        factory.setHostName(host);
        factory.setPort(port);
        factory.setTimeout(timeout);
        factory.setPassword(password);
        factory.setDatabase(database);
        return factory;
    }

    /**
     * 配置RedisTemplate
     * 設置添加序列化器
     * key 使用string序列化器
     * value 使用Json序列化器
     * 還有一種簡答的設置方式,改變defaultSerializer對象的實現。
     *
     * @return
     */
    @Bean
    public RedisTemplate<Object, Object> redisTemplate() {
        //StringRedisTemplate的構造方法中默認設置了stringSerializer
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        //設置開啓事務
        template.setEnableTransactionSupport(true);
        //set key serializer
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        template.setKeySerializer(stringRedisSerializer);
        template.setHashKeySerializer(stringRedisSerializer);

        template.setConnectionFactory(jedisConnectionFactory());
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 設置RedisCacheManager
     * 使用cache註解管理redis緩存
     *
     * @return
     */
    @Override
    @Bean
    public RedisCacheManager cacheManager() {
        RedisCacheManager redisCacheManager = new RedisCacheManager(redisTemplate());
        return redisCacheManager;
    }

    /**
     * 自定義生成redis-key
     *
     * @return
     */
    @Override
    public KeyGenerator keyGenerator() {
        return new KeyGenerator() {
            @Override
            public Object generate(Object o, Method method, Object... objects) {
                StringBuilder sb = new StringBuilder();
                sb.append(o.getClass().getName()).append(".");
                sb.append(method.getName()).append(".");
                for (Object obj : objects) {
                    sb.append(obj.toString());
                }
                System.out.println("keyGenerator=" + sb.toString());
                return sb.toString();
            }
        };
    }
}

application.properties

#========================redis \u914D\u7F6E=============================
# Redis\u6570\u636E\u5E93\u7D22\u5F15\uFF08\u9ED8\u8BA4\u4E3A0\uFF09,\u5982\u679C\u8BBE\u7F6E\u4E3A1\uFF0C\u90A3\u4E48\u5B58\u5165\u7684key-value\u90FD\u5B58\u653E\u5728select 1\u4E2D
spring.redis.database=0 
# Redis\u670D\u52A1\u5668\u5730\u5740
spring.redis.host=localhost
# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u7AEF\u53E3
spring.redis.port=6379 
# Redis\u670D\u52A1\u5668\u8FDE\u63A5\u5BC6\u7801\uFF08\u9ED8\u8BA4\u4E3A\u7A7A\uFF09
spring.redis.password=
#\u8FDE\u63A5\u6C60\u6700\u5927\u8FDE\u63A5\u6570\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09
spring.redis.pool.max-active=8 
# \u8FDE\u63A5\u6C60\u6700\u5927\u963B\u585E\u7B49\u5F85\u65F6\u95F4\uFF08\u4F7F\u7528\u8D1F\u503C\u8868\u793A\u6CA1\u6709\u9650\u5236\uFF09
spring.redis.pool.max-wait=-1 
# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5927\u7A7A\u95F2\u8FDE\u63A5
spring.redis.pool.max-idle=8 
# \u8FDE\u63A5\u6C60\u4E2D\u7684\u6700\u5C0F\u7A7A\u95F2\u8FDE\u63A5
spring.redis.pool.min-idle=0 
# \u8FDE\u63A5\u8D85\u65F6\u65F6\u95F4\uFF08\u6BEB\u79D2\uFF09
spring.redis.timeout=0
### \u4E3B\u4ECE\u914D\u7F6E
# name of Redis server  \u54E8\u5175\u76D1\u542C\u7684Redis server\u7684\u540D\u79F0
spring.redis.sentinel.master=mymaster
# comma-separated list of host:port pairs  \u54E8\u5175\u7684\u914D\u7F6E\u5217\u8868
spring.redis.sentinel.nodes=127.0.0.1:26379,127.0.0.1:26378,127.0.0.1:26377
相關文章
相關標籤/搜索