承接国内外服务器租用托管、定制开发、网站代运营、网站seo优化托管接单、网站代更新,新老站点皆可!!咨询QQ:3787320601

redis 主从备份及其主备切换的操作

管理员 2023-07-07 08:03:10 互联网圈 8 ℃ 0 评论 13576字 收藏

首先原文是用了3 个服务器,我是用了一个服务器;

然后再原文的基础上,略加了自己的整理。

条件:

redis中,主从切换场景中,没有绝对的主和从,只有初始化的主和从,然后当主down后,从就变成主了,而主即便连接上,也是从,不会变成主

1.redis-server的主备关系:

master : redis⑴

slave1 : redis⑵

slave3 : redis⑶

2. 首先进行主从备份:

修改从服务 redis⑴ redis⑵ 的redis.conf

在从服务上 修改redis.conf 加入 slaveof 127.0.0.1 6379

主从备份: 这里设置成功以后,会进行主服务进行set以后,可在从服务进行get key ,可是一旦主服务宕机,从服务没法再进行set key

3.设置主从切换

三个服务器都修改 sentinel-test.conf

加入

sentinel monitor MyMaster 127.0.0.1 6381 1
sentinel down-after-milliseconds MyMaster 5000
sentinel failover-timeout MyMaster 900000
sentinel parallel-syncs MyMaster 2

第一行配置唆使 Sentinel 去监视一个名为 mymaster 的主服务器, 这个主服务器的 IP 地址为 127.0.0.1 , 端口号为 6379 , 而将这个主服务器判断为失效最少需要 2 个 Sentinel 同意 (只要同意 Sentinel 的数量不达标,自动故障迁移就不会履行)。

第二行down-after-milliseconds 选项指定了 Sentinel 认为服务器已断线所需的毫秒数。

如果服务器在给定的毫秒数以内, 没有返回 Sentinel 发送的 PING 命令的回复, 或返回一个毛病, 那末 Sentinel 将这个服务器标记为主观下线(subjectively down,简称 SDOWN )。

不过只有一个 Sentinel 将服务器标记为主观下线其实不一定会引发服务器的自动故障迁移: 只有在足足数量的 Sentinel 都将一个服务器标记为主观下线以后, 服务器才会被标记为客观下线(objectively down, 简称 ODOWN ), 这时候自动故障迁移才会履行。

将服务器标记为客观下线所需的 Sentinel 数量由对主服务器的配置决定。

第三行暂时不知道是甚么意思;

第四行 parallel-syncs 选项指定了在履行故障转移时, 最多可以有多少个从服务器同时对新的主服务器进行同步, 这个数字越小, 完成故障转移所需的时间就越长。

如果从服务器被设置为允许使用过期数据集(参见对 redis.conf 文件中对 slave-serve-stale-data 选项的说明), 那末你可能不希望所有从服务器都在同一时间向新的主服务器发送同步要求, 由于虽然复制进程的绝大部份步骤都不会阻塞从服务器, 但从服务器在载入主服务器发来的 RDB 文件时, 依然会造成从服务器在一段时间内不能处理命令要求: 如果全部从服务器一起对新的主服务器进行同步, 那末便可能会造成所有从服务器在短时间内全部不可用的情况出现。

你可以通过将这个值设为 1 来保证每次只有一个从服务器处于不能处理命令要求的状态。

4.启动

启动redis-server
# ./src/redis-server redis.conf
启动redis-sentinel
# ./src/redis-sentinelsentinel-test.conf

注意: 三台服务器都是这么启动的哦!~

补充:Redis CLuster主备切换、故障转移测试

redis版本5.0.5

测试redis Cluster主备切换、故障转移

1.下线一个从节点,此时它的主节点打印的日志

集群状态

2.下线一台主节点,此时它的从节点打印的日志

集群状态

测试主备切换时客户端状态

第一步:查看当前集群状态

可以看到六个节点都是可用状态,其中83.46的6379是81.64上的6380的从节点,计划Kill掉81.64上的6380主节点,然后视察83.46的6379节点日志

第二步:kill掉81.64上的6380

10:11:25:kill掉81.64上的6380,可以看到其从节点很快提示连接主节点失败,并且开始一秒钟一次的重连操作

此时查看集群的节点状态以下,可以看到槽 5461⑴0922在这个主节点上,此时全部reidis集群处于不可用状态

10:12:24:利用程序报错,redis操作超时

10:11:43 :在重连17次失败次数以后,从节点将主节点标记为失败,并且全部集群的状态切换为不可用,以后不甘心,又去尝试连接主节点

10:12:03:在重连20次失败后,从节点打印日志,等待投票选举,但是没有到达多数同意,因而继续重连之前的主节点

10:12:14:提示选举失败,选举过期,又继续重连

10:12:45:选举成功胜出,成了新的主节点,全部集群的状态变成可用

10:13:39:大概一分钟以后,redis客户端自动刷新了集群配置,成功连接上redis集群,此时主备切换和故障转移完成

此前项目中存在的问题

redis master宕机以后,会出现利用程序连接不上redis cluster的问题,需要重启服务才能解决

排查缘由以后发现是spring boot 2.x版本默许使用了lettuce作为redis客户端,而lettuce默许是不开启自动刷新集群拓扑的,当redis master宕机并且集群完成故障转移/主从切换以后,客户端使用的或者之前毛病的集群信息,就会致使利用程序一直连接不上redis集群。解决方案就是修改redis客户端配置,开启开启自适应刷新拓扑

配置文件以下

spring.redis.cluster.nodes=${redis.nodes}
spring.redis.password=${redis.pass}
spring.redis.timeout=60000
# 最大重定向次数
spring.redis.cluster.max-redirects=3
spring.redis.lettuce.pool.max-active=64
spring.redis.lettuce.pool.max-idle=16
spring.redis.lettuce.pool.min-idle=0
spring.redis.lettuce.pool.max-wait=60000ms
spring.redis.lettuce.shutdown-timeout=100ms

完全的配置类以下

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.RedisPassword;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import java.time.Duration;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Configuration
public class RedisConfig {
    @Autowired
    private RedisProperties redisProperties;
    @Bean
    @SuppressWarnings("all")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
        RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
        template.setConnectionFactory(factory);
        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);
        StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
        // key采取String的序列化方式
        template.setKeySerializer(stringRedisSerializer);
        // hash的key也采取String的序列化方式
        template.setHashKeySerializer(stringRedisSerializer);
        // value序列化方式采取jackson
        template.setValueSerializer(jackson2JsonRedisSerializer);
        // hash的value序列化方式采取jackson
        template.setHashValueSerializer(jackson2JsonRedisSerializer);
        template.afterPropertiesSet();
        return template;
    }
    /**
     * 为RedisTemplate配置Redis连接工厂实现
     * LettuceConnectionFactory实现了RedisConnectionFactory接口
     * 这里要注意的是,在构建LettuceConnectionFactory 时,如果不使用内置的destroyMethod,可能会致使Redis连接早于其它Bean被烧毁
     *
     * @return 返回LettuceConnectionFactory
     */
    @Bean(destroyMethod = "destroy")
    public LettuceConnectionFactory lettuceConnectionFactory() {
        List<String> clusterNodes = redisProperties.getCluster().getNodes();
        Set<RedisNode> nodes = new HashSet<>();
        clusterNodes.forEach(address -> nodes.add(new RedisNode(address.split(":")[0].trim(), Integer.parseInt(address.split(":")[1]))));
        RedisClusterConfiguration clusterConfiguration = new RedisClusterConfiguration();
        clusterConfiguration.setClusterNodes(nodes);
        clusterConfiguration.setPassword(RedisPassword.of(redisProperties.getPassword()));
        clusterConfiguration.setMaxRedirects(redisProperties.getCluster().getMaxRedirects());
        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxIdle(redisProperties.getLettuce().getPool().getMaxIdle());
        poolConfig.setMinIdle(redisProperties.getLettuce().getPool().getMinIdle());
        poolConfig.setMaxTotal(redisProperties.getLettuce().getPool().getMaxActive());
        return new LettuceConnectionFactory(clusterConfiguration, getLettuceClientConfiguration(poolConfig));
    }
    /**
     * 配置LettuceClientConfiguration 开启自适应刷新拓扑 包括线程池配置和安全项配置
     *
     * @param genericObjectPoolConfig common-pool2线程池
     * @return lettuceClientConfiguration
     */
    private LettuceClientConfiguration getLettuceClientConfiguration(GenericObjectPoolConfig genericObjectPoolConfig) {
        /*
        ClusterTopologyRefreshOptions配置用于开启自适应刷新和定时刷新。如自适应刷新不开启,Redis集群变更时将会致使连接异常!
         */
        ClusterTopologyRefreshOptions topologyRefreshOptions = ClusterTopologyRefreshOptions.builder()
                //开启自适应刷新
                //.enableAdaptiveRefreshTrigger(ClusterTopologyRefreshOptions.RefreshTrigger.MOVED_REDIRECT, ClusterTopologyRefreshOptions.RefreshTrigger.PERSISTENT_RECONNECTS)
                //开启所有自适应刷新,MOVED,ASK,PERSISTENT都会触发
                .enableAllAdaptiveRefreshTriggers()
                // 自适应刷新超时时间(默许30秒)
                .adaptiveRefreshTriggersTimeout(Duration.ofSeconds(25)) //默许关闭开启后时间为30秒
                // 开周期刷新
                .enablePeriodicRefresh(Duration.ofSeconds(20))  // 默许关闭开启后时间为60秒 ClusterTopologyRefreshOptions.DEFAULT_REFRESH_PERIOD 60  .enablePeriodicRefresh(Duration.ofSeconds(2)) = .enablePeriodicRefresh().refreshPeriod(Duration.ofSeconds(2))
                .build();
        return LettucePoolingClientConfiguration.builder()
                .poolConfig(genericObjectPoolConfig)
                .clientOptions(ClusterClientOptions.builder().topologyRefreshOptions(topologyRefreshOptions).build())
                .build();
    }
}

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。如有毛病或未斟酌完全的地方,望不吝赐教。

文章来源:丸子建站

文章标题:redis 主从备份及其主备切换的操作

https://www.wanzijz.com/view/62396.html

X

截屏,微信识别二维码

微信号:weimawl

(点击微信号复制,添加好友)

打开微信