Zookeeper in action | Zookeeper and Spring Cloud combine to solve distributed locks, service registration and discovery, and configuration management

A collection of columns that you can save for emergencies:

Spring Cloud 专栏:http://t.csdnimg.cn/WDmJ9

Python 专栏:http://t.csdnimg.cn/hMwPR

Redis 专栏:http://t.csdnimg.cn/Qq0Xc

TensorFlow 专栏:http://t.csdnimg.cn/SOien

Logback 专栏:http://t.csdnimg.cn/UejSC

Quantum computing:

Quantum Computing | Decrypting the famous quantum algorithms Shor's algorithm and Grover's algorithm

AI machine learning practice:

AI machine learning practice | Sentiment analysis using Python and scikit-learn library

AI machine learning | Speech recognition based on the librosa library and using classifiers in the scikit-learn library

Python practice:

Python Practical | Use Python and TensorFlow to build a convolutional neural network (CNN) for face recognition

Spring Cloud actual combat:

Spring Cloud Practical Combat | How to use distributed system flow control and circuit breaker degradation component Sentinel

Spring Cloud Practical Combat | Decrypting the underlying principles of Feign, including practical source code

Spring Cloud Practical Combat | Decrypting the underlying principles of load balancing Ribbon, including practical source code

1024 Programmers Day special article:

1024 Programmers Carnival Special | ELK+ collaborative filtering algorithm builds a personalized recommendation engine to intelligently realize "thousands of people, thousands of faces"

1024 Programmer's Day Special | Deciphering Spring Cloud Hystrix Meltdown to Improve System Availability and Fault Tolerance

1024 Programmer's Day Special | ELK+ uses user portraits to build a personalized recommendation engine to intelligently realize "thousands of people, thousands of faces"

1024 Programmer's Day Special | OKR VS KPI, who is more suitable?

1024 Programmers Day Special | Spring Boot Practical MongoDB Sharding or Replica Set Operation

Spring practical series of articles:

Spring Practical | Spring AOP Core Tips - Sunflower Collection

Spring Practice | The secret that Spring IOC cannot tell?

National Day and Mid-Autumn Festival special series of articles:

National Day and Mid-Autumn Festival Special (8) How to use JPA in Spring Boot projects

National Day and Mid-Autumn Festival Special (7) 20 Common Programming Interview Questions for Java Software Engineers

National Day and Mid-Autumn Festival Special (6) 30 Common Treasure Programming Interview Questions for College Students

National Day and Mid-Autumn Festival Special (5) How to performance tune MySQL? Next article

National Day and Mid-Autumn Festival Special (4) How to performance tune MySQL? Previous article

National Day and Mid-Autumn Festival Special (3) Use Generative Adversarial Network (GAN) to generate paintings with a festive atmosphere, implemented by the deep learning frameworks TensorFlow and Keras

National Day and Mid-Autumn Festival Special (2) Romantic Blessings Using Generative Adversarial Networks (GAN) to generate paintings with a festive atmosphere

National Day and Mid-Autumn Festival Special (1) Romantic Blessing Method Use Recurrent Neural Network (RNN) or Long Short-Term Memory Network (LSTM) to generate blessing poems

Insert image description here

1. Zookeeper detailed introduction

Zookeeper is an open source distributed coordination service that originated from Google's Chubby project and became a basic component of the Hadoop distributed system. Zookeeper provides a simple set of primitives based on which distributed applications can implement synchronization services, configuration maintenance, naming services, etc.
The main roles of Zookeeper are coordinator (Controller) and client (Client). The coordinator is responsible for managing the logic of the distributed application, and the client is used to interact with the coordinator. In distributed applications, a master control node (Controller) is usually needed to manage other physically distributed child processes. Zookeeper provides a general distributed lock service to coordinate the execution of distributed applications.
Zookeeper has the following features:

  1. Simplicity: Zookeeper is designed to follow the principle of simplicity and is easy to understand and use.
  2. Expressive: Zookeeper provides a flexible client API that allows developers to implement custom operations as needed.
  3. High availability: Zookeeper supports cluster deployment and can automatically discover failed nodes and re-elect controllers to ensure normal operation of the system.
  4. Loosely coupled interaction method: Zookeeper adopts an event-driven mechanism, and each component communicates through message passing, which facilitates expansion and integration.
  5. Resource library: Zookeeper stores and manages the configuration, status and other information of distributed applications to facilitate application development and maintenance.
    The client of Zookeeper is mainly written in Java language. The following is a simple Zookeeper client example:
import org.apache.zookeeper.*;
public class ZookeeperClient {
    
    
    private static ZooKeeper zooKeeper;
    static {
    
    
        try {
    
    
            // 创建 ZooKeeper 实例
            zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new Watcher() {
    
    
                @Override
                public void process(WatchedEvent event) {
    
    
                    System.out.println("事件:" + event);
                }
            });
        } catch (Exception e) {
    
    
            e.printStackTrace();
        }
    }
    public static void main(String[] args) throws Exception {
    
    
        // 创建临时顺序节点
        String path = "/my_app/config";
        byte[] data = "我的配置信息".getBytes();
        CreateMode createMode = CreateMode.EPHEMERAL_SEQUENTIAL;
        zooKeeper.create(path, data, createMode);
        // 获取节点信息
        Stat stat = new Stat();
        byte[] result = zooKeeper.getData(path, false, stat);
        System.out.println("节点数据:" + new String(result));
        // 删除节点
        zooKeeper.delete(path, -1);
    }
}

In this example, we first create a ZooKeeper instance, then create a temporary sequence node and obtain its data. Finally, the node is deleted.
It should be noted that this example is only used to illustrate the basic usage of the Zookeeper client. In real applications, you need to write more complex code to handle distributed coordination tasks based on specific needs.

2. Combination of Zookeeper and Spring Cloud

After the combination of Zookeeper and Spring Cloud, it can be applied to various scenarios that require distributed coordination, service governance, configuration management and other functions. The following are some specific application scenarios and code examples:
Add the following dependencies in the pom.xml file of your Spring Boot project:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-zookeeper</artifactId>
</dependency>
  1. Service registration and discovery
    Using Zookeeper as the service registration center can easily realize service registration and discovery. Here is a simple usage example:
    Service Provider:
@Service
public class YourService {
    
    
    // ...
}

Service consumers:

@RestController
public class YourController {
    
    
    @Autowired
    private RestTemplate restTemplate;
    @GetMapping("/your-service/{version}")
    public String getYourService(@PathVariable String version) {
    
    
        // 通过 RestTemplate 调用服务提供者
        return restTemplate.getForObject("http://localhost:8002/your-service/" + version, YourService.class);
    }
}

Configuration file:

spring.application.name=your-service-provider
spring.cloud.zookeeper.connect-string=localhost:2181
  1. Distributed lock
    Using Zookeeper to implement distributed locks can ensure concurrency control for performing the same operation on multiple nodes. The following is a simple usage example:
    Service class:
@Service
public class YourService {
    
    
    @Autowired
    private CuratorFramework curatorFramework;
    public void doSomething() {
    
    
        // 创建分布式锁
        Lock lock = curatorFramework.getZookeeperClient().createLock("/your-lock", "your-lock", 0, CreateMode.EPHEMERAL);
        try {
    
    
            // 等待获取锁
            if (lock.acquire(10000, TimeUnit.MILLISECONDS)) {
    
    
                try {
    
    
                    // 获取锁后执行具体业务
                    // ...
                } finally {
    
    
                    // 释放锁
                    lock.release();
                }
            } else {
    
    
                // 未获取到锁,执行其他操作
                // ...
            }
        } catch (InterruptedException e) {
    
    
            // 等待获取锁时发生异常,可以进行重试或其他处理
            // ...
        }
    }
}

Configuration file:

spring.application.name=your-service-provider
spring.zookeeper.connect-string=localhost:2181
  1. Configuration Management
    Using Zookeeper to implement configuration management can improve the reliability and ease of maintenance of the configuration. The following is a simple usage example:
    Configuration class:
@ConfigurationProperties(prefix = "your.config")
public class YourConfig {
    
    
    private String value;
    // getter 和 setter
}

Configuration file:

<bean id="curatorFramework" class="org.springframework.cloud.zookeeper.core.ZookeeperClientFactoryBean">
    <property name="connectString" value="localhost:2181"/>
</bean>
<bean id="yourConfig" class="org.springframework.beans.factory.config.ConfigurableBeanFactoryLocator">
    <property name="factory" ref="curatorFramework"/>
</bean>
<bean id="yourConfigService" class="org.springframework.beans.factory.config.ConfigServiceBean">
    <property name="locator" ref="yourConfig"/>
</bean>

In the above example, by using Spring Cloud and Zookeeper, functions such as distributed locks, service registration and discovery, and configuration management can be implemented, thereby improving the performance and reliability of the entire distributed system.

おすすめ

転載: blog.csdn.net/superdangbo/article/details/134665190