redis sentinel安装及配置(单机版)


1、安装

cd /usr/src   #进入下载目录(这个目录自己定)
#安装依赖
yum install -y wget gcc make tcl 
 
#下载源码包
wget http://download.redis.io/releases/redis-6.0.1.tar.gz 

#解压
tar xzf redis-6.0.1.tar.gz   

#进入redis目录
cd redis-6.0.1 

#编译与测试
make && make test  

#PREFIX安装指定目录
make install PREFIX=/usr/local/redis   

 

2、启动redis服务,检查redis是否安装成功

#启动redis服务
[redis-server 目录]./redis-server  

 

3、搭建哨兵模式

3.1、主从定义和数据节点、哨兵节点端口定义

目标:1主2从
主数据节点端口:6380
从数据节点端口:6381,6382
哨兵节点端口:26380,26381,26382 

 

3.2、在/usr/local/ 下新建一个目录redis-sentinel,然后创建数据节点和哨兵节点配置和数据文件夹

数据节点配置和数据文件夹
6380,6381,6382

哨兵节点配置和数据文件夹
26380,26381,26382

#创建相关文件夹命令
mkdir /usr/local/redis-sentinel
mkdir /usr/local/redis-sentinel/{6380,6381,6382}
mkdir /usr/local/redis-sentinel/{26380,26381,26382}

#复制redis.conf配置文件
cp /usr/local/redis-6.0.1/redis.conf /usr/local/redis-sentinel/6380/redis_6380.conf
cp /usr/local/redis-6.0.1/redis.conf /usr/local/redis-sentinel/6381/redis_6381.conf
cp /usr/local/redis-6.0.1/redis.conf /usr/local/redis-sentinel/6382/redis_6382.conf

#复制sentinel.conf配置文件
cp /usr/local/redis-6.0.1/redis.conf /usr/local/redis-sentinel/26380/sentinel_26380.conf
cp /usr/local/redis-6.0.1/redis.conf /usr/local/redis-sentinel/26381/sentinel_26381.conf
cp /usr/local/redis-6.0.1/redis.conf /usr/local/redis-sentinel/26382/sentinel_26382.conf
 
3.3、数据节点配置(即:redis实例):将redis安装目录下配置文件reids.conf拷贝6380,6381,6382文件夹下,将其中一些配置自定义如下(其他配置不变):
#Redis默认不是以守护进程的方式运行,可以通过该配置项修改,使用yes启用守护进程
daemonize yes
#当Redis以守护进程方式运行时,Redis默认会把pid写入/var/run/redis.pid文件,可以通过pidfile指定
pidfile /var/run/redis_6380.pid
#指定Redis监听端口,默认端口为6379
port 6380
#绑定的主机地址(bind 0.0.0.0允许跨网络访问)
bind 0.0.0.0
#日志记录方式,默认为标准输出,日志输出至指定日志文件
logfile "./redis-6380.log"
#指定本地数据库存放目录
dir "/usr/local/redis-sentinel/6380"
#当master服务设置了密码保护时,slave服务连接master的密码,可以不设置(可选)。设置在slave上,指定master的密码。
#masterauth admin.123
#设置Redis连接密码,如果配置了连接密码,客户端在连接Redis时需要通过AUTH <password>命令提供密码,默认关闭,可以不设置(可选),设置在master上,指定master密码。
#requirepass admin.123
#指定是否在每次更新操作后进行日志记录,Redis在默认情况下是异步的把数据写入磁盘,如果不开启,可能会在断电时导致一段时间内的数据丢失。
#因为 redis本身同步数据文件是按上面save条件来同步的,所以有的数据会在一段时间内只存在于内存中。默认为no
appendonly yes
#设置当本机为slave服务时,设置master服务的IP地址及端口,在Redis启动时,它会自动从master进行数据同步(本例以6380端口的为主,6381和6382为从,故以下只需在6381和6382配置中即可)。此处需要注意。。。
slaveof 127.0.0.0 6380

 

3.4、哨兵配置:将redis安装目录下的sentinel.conf拷贝6380,6381,6382文件夹下,其自定义配置如下:

#============================================自定义配置开始========================================
#Redis默认不是以守护进程的方式运行,可以通过该配置项修改,使用yes启用守护进程
daemonize yes
#指定sentinel端口。(其它哨兵配置需要改否则引起端口冲突)
port 26380
#指定本地数据库存放目录。(其它哨兵配置需要改成对应路径)
dir "/usr/local/redis-sentinel/26380"
#日志记录方式,默认为标准输出,日志输出至指定日志文件。(其它哨兵配置需要改成对应路径和文件)
logfile "/usr/local/redis-sentinel/26380/sentinel_26380.log"
#指定别名  主节点地址  端口  哨兵个数(有几个哨兵监控到主节点宕机执行转移)。所有的哨兵都指向主节点地址和端口。注意如果是服务器127.0.0.1需要改成服务器ID地址,否则通过Java连接不成功。
sentinel monitor mymaster 127.0.0.0 6380 1
#如果哨兵3s内没有收到主节点的心跳,哨兵就认为主节点宕机了,默认是30秒  
sentinel down-after-milliseconds mymaster 3000
#选举出新的主节点之后,可以同时连接从节点的个数
sentinel parallel-syncs mymaster 1
#如果10秒后,master仍没活过来,则启动failover,默认180s  
sentinel failover-timeout mymaster 10000
#配置连接redis主节点密码(可选),所有哨兵配置文件都要加上,如果master主节点配置了密码。
#sentinel auth-pass mymaster admin.123
#============================================自定义配置结束========================================
 

4、redis服务启动

4.1.先启动主从

[appuser@uxt210196 redis-6.0.1]$ ./src/redis-server /usr/local/redis-sentinel/6380/redis_6380.conf
[appuser@uxt210196 redis-6.0.1]$ ./src/redis-server /usr/local/redis-sentinel/6381/redis_6381.conf
[appuser@uxt210196 redis-6.0.1]$ ./src/redis-server /usr/local/redis-sentinel/6382/redis_6382.conf

查看服务信息,如果信息返回,证明数据节点没有起来。查看启动命令是否正确。注意redis-server启动不需要加--sentinel
[appuser@uxt210196 redis-6.0.1]$ ./src/redis-cli -h 127.0.0.1 -p 6380 info replication
# Replication
role:master
connected_slaves:2
slave0:ip=10.16.70.142,port=6381,state=online,offset=1394550,lag=1
slave1:ip=10.16.70.142,port=6382,state=online,offset=1394550,lag=1
master_replid:bed7630a4c86f762a6f95497ed98379c44d97a88
master_replid2:0000000000000000000000000000000000000000
master_repl_offset:1394690
second_repl_offset:-1
repl_backlog_active:1
repl_backlog_size:1048576
repl_backlog_first_byte_offset:346115
repl_backlog_histlen:1048576

 

4.2、启动哨兵

[appuser@uxt210196 redis-6.0.1]$ ./src/redis-sentinel /usr/local/redis-sentinel/26380/sentinel_26380.conf
[appuser@uxt210196 redis-6.0.1]$ ./src/redis-sentinel /usr/local/redis-sentinel/26381/sentinel_26381.conf
[appuser@uxt210196 redis-6.0.1]$ ./src/redis-sentinel /usr/local/redis-sentinel/26382/sentinel_26382.conf

 

4.3、查看进程

3个redis-server进程,3个sentinel进程。

[appuser@uxt210196 redis-6.0.1]$ ps -ef |grep redis
appuser      4204     1  0 08:53 ?        00:00:17 ./src/redis-server 0.0.0.0:6380                    
appuser      4213     1  0 08:54 ?        00:00:20 ./src/redis-server 0.0.0.0:6381                    
appuser      4236     1  0 08:55 ?        00:01:11 ./src/redis-sentinel 0.0.0.0:26380 [sentinel]           
appuser      4241     1  0 08:55 ?        00:01:11 ./src/redis-sentinel 0.0.0.0:26381 [sentinel]           
appuser      4354     1  0 09:03 ?        00:00:20 ./src/redis-server 0.0.0.0:6382                    
appuser      4372     1  0 09:04 ?        00:01:07 ./src/redis-sentinel 0.0.0.0:26382 [sentinel]           
appuser      5163  5108  0 10:59 pts/0    00:00:00 grep redis

 

5、启动尝试连接

a、首先确定本地能访问
b、尝试使用redis后尝试使用redis desktop manager工具连接下,确保外面能访问。
c、若外网访问不了,查看是否没关防火窗
d、检查配置文件的bind

 

6、java连接redis哨兵

public static void main(String[] args) {
        // 建立连接池配置参数
        JedisPoolConfig poolConfig = new JedisPoolConfig();

        //控制一个pool最多有多少个状态为idle(空闲)的jedis实例
        poolConfig.setMaxIdle(10);

        //需要使用哨兵端口,才能实现高可用
        String masterName = "mymaster";
        Set<String> sentinelSet = new HashSet<String>();
        sentinelSet.add("127.0.0.1:26380");
        sentinelSet.add("127.0.0.1:26381");
        sentinelSet.add("127.0.0.1:26382");

        JedisSentinelPool sentinelPool = new JedisSentinelPool(masterName, sentinelSet, poolConfig, 60000);
        Jedis jedis = null;
        try {
            jedis = sentinelPool.getResource();
            //设置操作数据库,不设置默认使用0
            jedis.select(1);

            //测试是否可以设值
            jedis.set("name","zhangsan");

            //获取值
            System.out.println("redis:"+jedis.get("name"));
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

 

7、SpringBoot整合Redis Sentinel哨兵

7.1、依赖jar

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>

 

7.2、redis哨兵模式配置文件:application.yml

#redis哨兵模式配置文件:application.yml
spring.redis.database=0
spring.redis.sentinel.master=mymaster
spring.redis.sentinel.nodes=127.0.0.1:26380,127.0.0.1:26381,127.0.0.1:26382

 

7.3、springboot redis哨兵连接配置类(创建redisTemplate缓存操作对象)

package com.hababa.config;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @Classname RedisSentinelConfig
 * @Description
 * @Date 2020/5/14 9:21
 * @Created by
 */
@EnableCaching
@Configuration
@ConditionalOnClass(RedisOperations.class)
@EnableConfigurationProperties(RedisProperties.class)
public class RedisSentinelConfig {

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

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

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


    @Bean
    public JedisPoolConfig jedisPoolConfig(){
        JedisPoolConfig config = new JedisPoolConfig();
        return config;
    }

    //redis哨兵配置
    @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;
    }

    @Bean
    public JedisConnectionFactory jedisConnectionFactory(JedisPoolConfig jedisPoolConfig,RedisSentinelConfiguration sentinelConfig) {
        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory(sentinelConfig,jedisPoolConfig);
        return jedisConnectionFactory;
    }


    @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(jedisPoolConfig(),redisSentinelConfiguration()));
        
        template.afterPropertiesSet();
        return template;
    }
    
}

 

8、测试springboot是否成功整合redis sentinel

/**
 * @Classname TestController
 * @Description 测试springboot是否成功整合redis sentinel
 * @Date 2020/5/14 14:32
 * @Created by 
 */
@RestController
@RequestMapping("test")
public class TestController {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;


    @GetMapping("redisHandler")
    public String redisHandler(){
        redisTemplate.opsForValue().set("key_lisi","lisi");
        
        System.out.println(redisTemplate.opsForValue().get("key_lisi"));
    }
    
}

 

9、linux shell脚本启动redis和sentinel (文件名称:redis_sentinel_start_stop_restart.sh)

 9.1、执行脚本需要传入参数start或者stop或者restart

#!/bin/sh

start(){
   nohup /usr/local/redis-6.0.1/src/redis-server /usr/local/redis-6.0.1/redis-sentinel/6380/redis.conf
   nohup /usr/local/redis-6.0.1/src/redis-server /usr/local/redis-6.0.1/redis-sentinel/6381/redis.conf
   nohup /usr/local/redis-6.0.1/src/redis-server /usr/local/redis-6.0.1/redis-sentinel/6382/redis.conf

  nohup /usr/local/redis-6.0.1/src/redis-sentinel /usr/local/redis-6.0.1/redis-sentinel/6380/sentinel.conf
  nohup /usr/local/redis-6.0.1/src/redis-sentinel /usr/local/redis-6.0.1/redis-sentinel/6381/sentinel.conf
  nohup /usr/local/redis-6.0.1/src/redis-sentinel /usr/local/redis-6.0.1/redis-sentinel/6382/sentinel.conf

}

stop(){
    ps -ef|grep redis|grep -v grep|awk '{print $2}'|while read pid
    do
        kill -9 $pid
        echo " kill $pid success "
    done
}

case "$1" in
start)
    start
    ;;
stop)
    stop
    ;;
restart)
    stop
    sleep 1s
    start
    ;;
*)
    printf 'Usage: %s {start|stop|restart}\n' "$prog"
    exit 1
    ;;
    
esac

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM