master选举使用场景及结构
现在很多时候我们的服务需要7*24小时工作,假如一台机器挂了,我们希望能有其它机器顶替它继续工作。此类问题现在多采用master-salve模式,也就是常说的主从模式,正常情况下主机提供服务,备机负责监听主机状态,当主机异常时,可以自动切换到备机继续提供服务(这里有点儿类似于数据库主库跟备库,备机正常情况下只监听,不工作),这个切换过程中选出下一个主机的过程就是master选举。
对于以上提到的场景,传统的解决方式是采用一个备用节点,这个备用节点定期给当前主节点发送ping包,主节点收到ping包后会向备用节点发送应答ack,当备用节点收到应答,就认为主节点还活着,让它继续提供服务,否则就认为主节点挂掉了,自己将开始行使主节点职责。如图1所示:
Maven依赖信息
<parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.0.RELEASE</version> </parent> <dependencies> <dependency> <groupId>com.101tec</groupId> <artifactId>zkclient</artifactId> <version>0.10</version> <exclusions> <exclusion> <artifactId>slf4j-api</artifactId> <groupId>org.slf4j</groupId> </exclusion> <exclusion> <artifactId>log4j</artifactId> <groupId>log4j</groupId> </exclusion> <exclusion> <artifactId>slf4j-log4j12</artifactId> <groupId>org.slf4j</groupId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> </dependencies>
IndexController
@RestController public class IndexController { // 获取服务信息 @RequestMapping("/getServerInfo") public String getServerInfo() { return ElectionMaster.isSurvival ? "当前服务器为主节点" : "当前服务器为从节点"; } }
MyApplicationRunner
@Component public class MyApplicationRunner implements ApplicationRunner { // 创建zk连接 ZkClient zkClient = new ZkClient("127.0.0.1:2181"); private String path = "/election"; @Value("${server.port}") private String serverPort; public void run(ApplicationArguments args) throws Exception { System.out.println("项目启动完成..."); createEphemeral(); // 创建事件监听 zkClient.subscribeDataChanges(path, new IZkDataListener() { // 节点被删除 public void handleDataDeleted(String dataPath) throws Exception { // 主节点已经挂了,重新选举 System.out.println("主节点已经挂了,重新开始选举"); createEphemeral(); } public void handleDataChange(String dataPath, Object data) throws Exception { } }); } private void createEphemeral() { try { zkClient.createEphemeral(path, serverPort); ElectionMaster.isSurvival = true; System.out.println("serverPort:" + serverPort + ",选举成功...."); } catch (Exception e) { ElectionMaster.isSurvival = false; } } }
ElectionMaster
@Component public class ElectionMaster { // 服务器info信息 是否存活 public static boolean isSurvival; }