通过redis选主进程

2024-02-27 07:20
文章标签 redis 进程 选主

本文主要是介绍通过redis选主进程,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

选主进程的方式有很多,完善点的方案就是zookeeper来做。这里介绍的是一种基于redis选主的方案,快速开发,快速实现。

Springside4里有个MasterElector类,细读代码后整理出自己的总结如下。

1.      业务进程启动时生成hostId,hostId的规则是“主机名-随机数”,一台主机部署多个进程实例的情况,也可以改为“主机名-端口”。

2.      业务进程调用jedis.get(masterKey)获取masterFromRedis。

3.      如果masterFromRedis为空,调用setnx(masterKey, hostId)方法设值,方法返回值大于0当前进程选为主进程,并且expire(masterKey,expireSeconds)设置key的有效期。Setnx返回值小于等于0时不能选为主进程。

如果masterFromRedis等于hostId,当前进程选为主进程,并且expire(masterKey, expireSeconds)设置key的有效期。

4.      按时间间隔intervalSeconds定期执行第二步和第三步。

 

 

当get(masterKey)之后获取到的masterFromRdis为空,在setnx之前,有其他进程已经Set了masterKey的值,本进程再调用setnx返回0失败.reids api文档有详细介绍:

 

SETNX key value

将 key 的值设为 value ,当且仅当 key 不存在。

若给定的 key 已经存在,则 SETNX 不做任何动作。

SETNX 是『SET if Not eXists』(如果不存在,则 SET)的简写。

可用版本:

>= 1.0.0

时间复杂度:

O(1)

返回值:

设置成功,返回 1 。

设置失败,返回 0 。

 

intervalSeconds定时时间间隔设置短些,可以减少异常情况下没有主的情况。

附上springside4的代码

 

 

public class MasterElector implementsRunnable {

 

                   publicstatic final String DEFAULT_MASTER_KEY = "master";

 

                   privatestatic Logger logger = LoggerFactory.getLogger(MasterElector.class);

 

                   privatestatic AtomicInteger poolNumber = new AtomicInteger(1);

                   privateScheduledExecutorService internalScheduledThreadPool;

                   privateScheduledFuture electorJob;

                   privateint intervalSeconds;

 

                   privateJedisTemplate jedisTemplate;

 

                   privateint expireSeconds;

                   privateString hostId;

                   privateAtomicBoolean master = new AtomicBoolean(false);

                   privateString masterKey = DEFAULT_MASTER_KEY;

 

                   publicMasterElector(JedisPool jedisPool, int intervalSeconds, int expireSeconds) {

                                      jedisTemplate= new JedisTemplate(jedisPool);

                                      this.expireSeconds= expireSeconds;

                                      this.intervalSeconds= intervalSeconds;

                   }

 

                   /**

                    * 发挥目前该实例是否master

                    */

                   publicboolean isMaster() {

                                      returnmaster.get();

                   }

 

                   /**

                    * 启动抢注线程, 自行创建scheduler线程池.

                    */

                   publicvoid start() {

                                      internalScheduledThreadPool= Executors.newScheduledThreadPool(1,

                                                                            Threads.buildJobFactory("Master-Elector-"+ poolNumber.getAndIncrement() + "-%d"));

                                      start(internalScheduledThreadPool);

                   }

 

                   /**

                    * 启动抢注线程, 使用传入的scheduler线程池.

                    */

                   publicvoid start(ScheduledExecutorService scheduledThreadPool) {

                                      if(intervalSeconds >= expireSeconds) {

                                                         thrownew IllegalArgumentException("periodSeconds must less than expireSeconds.periodSeconds is "

                                                                                               +intervalSeconds + " expireSeconds is " + expireSeconds);

                                      }

 

                                      hostId= generateHostId();

                                      electorJob= scheduledThreadPool.scheduleAtFixedRate(new WrapExceptionRunnable(this), 0,intervalSeconds,

                                                                            TimeUnit.SECONDS);

                                      logger.info("masterElectorstart, hostName:{}.", hostId);

                   }

 

                   /**

                    * 停止分发任务,如果是自行创建的threadPool则自行销毁。

                    */

                   publicvoid stop() {

                                      electorJob.cancel(false);

 

                                      if(internalScheduledThreadPool != null) {

                                                         Threads.normalShutdown(internalScheduledThreadPool,5, TimeUnit.SECONDS);

                                      }

                   }

 

                   /**

                    * 生成host id的方法哦,可在子类重载.

                    */

                   protectedString generateHostId() {

                                      Stringhost = "localhost";

                                      try{

                                                         host= InetAddress.getLocalHost().getHostName();

                                      }catch (UnknownHostException e) {

                                                         logger.warn("cannot get hostName", e);

                                      }

                                      host= host + "-" + new SecureRandom().nextInt(10000);

 

                                      returnhost;

                   }

 

                   @Override

                   publicvoid run() {

                                      jedisTemplate.execute(newJedisActionNoResult() {// NOSONAR

                                                                                               @Override

                                                                                               publicvoid action(Jedis jedis) {

                                                                                                                  StringmasterFromRedis = jedis.get(masterKey);

 

                                                                                                                  logger.debug("masteris {}", masterFromRedis);

 

                                                                                                                  //if master is null, the cluster just start or the master had crashed, try toregister myself

                                                                                                                  //as master

                                                                                                                  if(masterFromRedis == null) {

                                                                                                                                     //use setnx to make sure only one client can register as master.

                                                                                                                                     if(jedis.setnx(masterKey, hostId) > 0) {

                                                                                                                                                        jedis.expire(masterKey,expireSeconds);

                                                                                                                                                        master.set(true);

 

                                                                                                                                                        logger.info("masteris changed to {}.", hostId);

                                                                                                                                                        return;

                                                                                                                                     }else {

                                                                                                                                                        master.set(false);

                                                                                                                                                        return;

                                                                                                                                     }

                                                                                                                  }

 

                                                                                                                  //if master is myself, update the expire time.

                                                                                                                  if(hostId.equals(masterFromRedis)) {

                                                                                                                                     jedis.expire(masterKey,expireSeconds);

                                                                                                                                     master.set(true);

                                                                                                                                     return;

                                                                                                                  }

 

                                                                                                                  master.set(false);

                                                                                               }

                                                                            });

                   }

 

                   /**

                    * 如果应用中有多种master,设置唯一的mastername

                    */

                   publicvoid setMasterKey(String masterKey) {

                                      this.masterKey= masterKey;

                   }

 

                   //for test

                   publicvoid setHostId(String hostId) {

                                      this.hostId= hostId;

                   }

}

 

这篇关于通过redis选主进程的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/751604

相关文章

Redis 的 SUBSCRIBE命令详解

《Redis的SUBSCRIBE命令详解》Redis的SUBSCRIBE命令用于订阅一个或多个频道,以便接收发送到这些频道的消息,本文给大家介绍Redis的SUBSCRIBE命令,感兴趣的朋友跟随... 目录基本语法工作原理示例消息格式相关命令python 示例Redis 的 SUBSCRIBE 命令用于订

sky-take-out项目中Redis的使用示例详解

《sky-take-out项目中Redis的使用示例详解》SpringCache是Spring的缓存抽象层,通过注解简化缓存管理,支持Redis等提供者,适用于方法结果缓存、更新和删除操作,但无法实现... 目录Spring Cache主要特性核心注解1.@Cacheable2.@CachePut3.@Ca

Redis实现高效内存管理的示例代码

《Redis实现高效内存管理的示例代码》Redis内存管理是其核心功能之一,为了高效地利用内存,Redis采用了多种技术和策略,如优化的数据结构、内存分配策略、内存回收、数据压缩等,下面就来详细的介绍... 目录1. 内存分配策略jemalloc 的使用2. 数据压缩和编码ziplist示例代码3. 优化的

redis-sentinel基础概念及部署流程

《redis-sentinel基础概念及部署流程》RedisSentinel是Redis的高可用解决方案,通过监控主从节点、自动故障转移、通知机制及配置提供,实现集群故障恢复与服务持续可用,核心组件包... 目录一. 引言二. 核心功能三. 核心组件四. 故障转移流程五. 服务部署六. sentinel部署

基于Redis自动过期的流处理暂停机制

《基于Redis自动过期的流处理暂停机制》基于Redis自动过期的流处理暂停机制是一种高效、可靠且易于实现的解决方案,防止延时过大的数据影响实时处理自动恢复处理,以避免积压的数据影响实时性,下面就来详... 目录核心思路代码实现1. 初始化Redis连接和键前缀2. 接收数据时检查暂停状态3. 检测到延时过

Redis实现分布式锁全过程

《Redis实现分布式锁全过程》文章介绍Redis实现分布式锁的方法,包括使用SETNX和EXPIRE命令确保互斥性与防死锁,Redisson客户端提供的便捷接口,以及Redlock算法通过多节点共识... 目录Redis实现分布式锁1. 分布式锁的基本原理2. 使用 Redis 实现分布式锁2.1 获取锁

Redis中哨兵机制和集群的区别及说明

《Redis中哨兵机制和集群的区别及说明》Redis哨兵通过主从复制实现高可用,适用于中小规模数据;集群采用分布式分片,支持动态扩展,适合大规模数据,哨兵管理简单但扩展性弱,集群性能更强但架构复杂,根... 目录一、架构设计与节点角色1. 哨兵机制(Sentinel)2. 集群(Cluster)二、数据分片

Linux系统管理与进程任务管理方式

《Linux系统管理与进程任务管理方式》本文系统讲解Linux管理核心技能,涵盖引导流程、服务控制(Systemd与GRUB2)、进程管理(前台/后台运行、工具使用)、计划任务(at/cron)及常用... 目录引言一、linux系统引导过程与服务控制1.1 系统引导的五个关键阶段1.2 GRUB2的进化优

redis数据结构之String详解

《redis数据结构之String详解》Redis以String为基础类型,因C字符串效率低、非二进制安全等问题,采用SDS动态字符串实现高效存储,通过RedisObject封装,支持多种编码方式(如... 目录一、为什么Redis选String作为基础类型?二、SDS底层数据结构三、RedisObject

Redis分布式锁中Redission底层实现方式

《Redis分布式锁中Redission底层实现方式》Redission基于Redis原子操作和Lua脚本实现分布式锁,通过SETNX命令、看门狗续期、可重入机制及异常处理,确保锁的可靠性和一致性,是... 目录Redis分布式锁中Redission底层实现一、Redission分布式锁的基本使用二、Red