通过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 Cluster模式配置

《RedisCluster模式配置》:本文主要介绍RedisCluster模式配置,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录分片 一、分片的本质与核心价值二、分片实现方案对比 ‌三、分片算法详解1. ‌范围分片(顺序分片)‌2. ‌哈希分片3. ‌虚

Springboot整合Redis主从实践

《Springboot整合Redis主从实践》:本文主要介绍Springboot整合Redis主从的实例,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录前言原配置现配置测试LettuceConnectionFactory.setShareNativeConnect

Windows的CMD窗口如何查看并杀死nginx进程

《Windows的CMD窗口如何查看并杀死nginx进程》:本文主要介绍Windows的CMD窗口如何查看并杀死nginx进程问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地... 目录Windows的CMD窗口查看并杀死nginx进程开启nginx查看nginx进程停止nginx服务

Redis过期删除机制与内存淘汰策略的解析指南

《Redis过期删除机制与内存淘汰策略的解析指南》在使用Redis构建缓存系统时,很多开发者只设置了EXPIRE但却忽略了背后Redis的过期删除机制与内存淘汰策略,下面小编就来和大家详细介绍一下... 目录1、简述2、Redis http://www.chinasem.cn的过期删除策略(Key Expir

Java进程CPU使用率过高排查步骤详细讲解

《Java进程CPU使用率过高排查步骤详细讲解》:本文主要介绍Java进程CPU使用率过高排查的相关资料,针对Java进程CPU使用率高的问题,我们可以遵循以下步骤进行排查和优化,文中通过代码介绍... 目录前言一、初步定位问题1.1 确认进程状态1.2 确定Java进程ID1.3 快速生成线程堆栈二、分析

Redis指南及6.2.x版本安装过程

《Redis指南及6.2.x版本安装过程》Redis是完全开源免费的,遵守BSD协议,是一个高性能(NOSQL)的key-value数据库,Redis是一个开源的使用ANSIC语言编写、支持网络、... 目录概述Redis特点Redis应用场景缓存缓存分布式会话分布式锁社交网络最新列表Redis各版本介绍旧

Java如何从Redis中批量读取数据

《Java如何从Redis中批量读取数据》:本文主要介绍Java如何从Redis中批量读取数据的情况,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录一.背景概述二.分析与实现三.发现问题与屡次改进3.1.QPS过高而且波动很大3.2.程序中断,抛异常3.3.内存消

Redis中的Lettuce使用详解

《Redis中的Lettuce使用详解》Lettuce是一个高级的、线程安全的Redis客户端,用于与Redis数据库交互,Lettuce是一个功能强大、使用方便的Redis客户端,适用于各种规模的J... 目录简介特点连接池连接池特点连接池管理连接池优势连接池配置参数监控常用监控工具通过JMX监控通过Pr

python操作redis基础

《python操作redis基础》Redis(RemoteDictionaryServer)是一个开源的、基于内存的键值对(Key-Value)存储系统,它通常用作数据库、缓存和消息代理,这篇文章... 目录1. Redis 简介2. 前提条件3. 安装 python Redis 客户端库4. 连接到 Re

Redis迷你版微信抢红包实战

《Redis迷你版微信抢红包实战》本文主要介绍了Redis迷你版微信抢红包实战... 目录1 思路分析1.1hCckRX 流程1.2 注意点①拆红包:二倍均值算法②发红包:list③抢红包&记录:hset2 代码实现2.1 拆红包splitRedPacket2.2 发红包sendRedPacket2.3 抢