当前位置:网站首页>Custom RPC project - frequently asked questions and explanations (Registration Center)

Custom RPC project - frequently asked questions and explanations (Registration Center)

2022-07-06 13:36:00 Li bohuan

          Take the book back , Customize RPC project —— Common problems and detailed explanations (Netty piece )_ Li bohuan's blog -CSDN Blog , Let's talk about it later , This RPC Frequently asked questions about the project :

Project address :https://blog.csdn.net/qq_40856284/category_10138756.html

        Four 、 Registry Center  

         1. Why use a registry ?

        Before using and learning the registry , First of all, we need to be clear , Why use a registry ? With the development of Internet architecture ( Single application architecture ==> Vertical application architecture ==> Distributed architecture ==>SOA framework ==> Microservice architecture ), More and more services , The dependencies between services are also more complex , It is difficult to directly call services , The implementation process is also more complex , And to improve the reliability of the service , The registration center came into being .

         The concept of registry plays an important role in the architecture of service-oriented design , Whether in SOA Architecture is still in the microservice architecture , The role of the registry can be summed up in a word Storage and scheduling services , Implement services and registries , Services and communication between services . The registry can be said to be in the microservice architecture ” Mail list “, It records the mapping relationship between service and service address . In a distributed architecture , The service will register here , When a service needs to call another service , Just find the address of the service here , To call . Here are some common registry features :

          2. Why use Nacos As the registration center of the project ?

        Nacos Alibaba is an open-source dynamic service discovery that is easier to build cloud native applications 、 Configuration management and service management platform .( Configuration center 、 Registry Center ) 

        Look at the watch above ,nacos The most comprehensive features supported . Open the box , Simple to use , I haven't found a big hole yet ,nacos More features , The community is more active .  If you are interviewing Ali , Direct said Because it was developed by Ali , Stand the test of various applications in large factories , There must be no problem .

        3. Common registry differences ?

        See this article . Microservices : Registry Center ZooKeeper、Eureka、Consul 、Nacos contrast _ Qiyan's blog -CSDN Blog _consul nacos

        4. What are the minimum conditions for a registration center ?      

Service registration interface : The service provider completes the service registration by calling the service registration interface .

Service de registration interface : The service provider calls the service deregistration interface to complete the service deregistration .

Heartbeat reporting interface : The service provider completes the node survival status reporting by calling the heartbeat reporting interface .

Service subscription interface : The service consumer completes the service subscription by calling the service subscription interface , Get the list of available service provider nodes .

Service change query interface : The service consumer changes the query interface by calling the service , Get the latest list of available service nodes .

Service query interface : Query the service information currently registered in the registry .

Service modification interface : Modify the information of a service in the registry .

        5. The registration center is a single machine or a cluster , What if one of them hangs up ? Uniformity , How to guarantee reliability ? 

          In my project , It is a stand-alone version nacos.nacos You can see the following blog for the cluster deployment scheme of

Nacos Service registration and discovery 、 Cluster deployment scheme _ Qi _z The blog of -CSDN Blog _nacos Service cluster configuration

        Then we need to realize the registration center from stand-alone version to distributed cluster , There are several key problems to be solved :

  • The relationship between cluster members and member discovery problems

  • Data replication and consistency among cluster members

  • Data replication mechanism and data partition strategy

        Specific solutions can be seen : Design principle and implementation of distributed cluster in microservice registry Golang Realization (136.la) 

        6. What do distributed data consistency protocols know ?

        (1 Bar message ) Common distributed consistency protocols _TJtulong The blog of -CSDN Blog _ Distributed consistency protocol

       7.CAP Theoretical understanding ?

         CAP Theory is the most important theory in distributed architecture

  1. C Uniformity : For each read operation of the client , Or read the latest data , Either the read failed . let me put it another way , Consistency is from the perspective of distributed system , A commitment to clients accessing the system : Or I'll return you an error , Or I'll return you the absolutely consistent latest data , It's not hard to see. , It emphasizes that the data is correct .
  2. A Usability : Any client request can get response data , There are no response errors . let me put it another way , Availability is from the perspective of distributed systems , Another commitment to customers accessing the system : I will definitely return the data to you , It won't return you an error , But the data is not guaranteed to be up-to-date , The emphasis is not to make mistakes .
  3. P Zone tolerance : Because the distributed system communicates through the network , The network is unreliable . When any number of messages are lost or arrive late , The system will continue to provide services , Will not hang up . let me put it another way , Partition tolerance is from the perspective of distributed system , Another commitment to the client accessing the system : I'll keep running , No matter what kind of data synchronization problem occurs inside me , The emphasis is not to hang up .

         All distributed systems must have partition tolerance , Because partition tolerance is the basic condition of distributed systems , But there can only be one consistency and availability , It's just CP perhaps AP The system of , There is no such thing as CAP All established systems . Because in order to meet the consistency, the system must copy the data to each micro service , This leads to a great performance consumption , There will be usability problems , So you can't have both .

        8. Any request ( Traffic ) Will you call the registration center when you come here ? 

        First meeting , When Ask the registry after , Save the service list locally ( Consumer memory ), Convenient for future use . 

        9. If it's how you design one nacos ,rpc How to call .

         【Nacos】Nacos Principle analysis _Coinker The blog of -CSDN Blog _nacos Principle

        10.raft Understand ?

        Nacos Of Raft Algorithm _ Overtime crazy blog -CSDN Blog _nacos raft

        11. In the project nacos Specific use of the registry

          Introduce dependencies

        <dependency>
            <groupId>com.alibaba.nacos</groupId>
            <artifactId>nacos-client</artifactId>
            <version>1.3.0</version>
        </dependency>

        First, define an interface ,ServiceRegistry As a remote registry (Nacos) Use

public interface ServiceRegistry {

    /**
     *  Register a service into the registry 
     *
     * @param serviceName  The service name 
     * @param inetSocketAddress  The address where the service is provided 
     */
    void register(String serviceName, InetSocketAddress inetSocketAddress);
}

        register The method is to put the name of the service ( The interface name ) And address are registered in the service registration center , The interface has , We can write implementation classes , We achieve one Nacos As the implementation class of the registry :NacosServiceRegistry, We can also use ZooKeeper As a registry , Just implement the interface .

public class NacosServiceRegistry implements ServiceRegistry {

    private static final Logger logger = LoggerFactory.getLogger(NacosServiceRegistry.class);

    @Override
    public void register(String serviceName, InetSocketAddress inetSocketAddress) {
        try {
            NacosUtil.registerService(serviceName, inetSocketAddress);
        } catch (NacosException e) {
            logger.error(" An error occurred while registering the service :", e);
            throw new RpcException(RpcError.REGISTER_SERVICE_FAILED);
        }
    }
}

        Here is a Nacos The utility class registerService Method to register the service ,NacosUtil Class is defined as follows , Three methods are mainly implemented , Registration service , Get all instances of the service and log out of the service .

public class NacosUtil {

    private static final Logger logger = LoggerFactory.getLogger(NacosUtil.class);

    private static final NamingService namingService;
    private static final Set<String> serviceNames = new HashSet<>();
    private static InetSocketAddress address;

    private static final String SERVER_ADDR = "127.0.0.1:8848";

    static {
        namingService = getNacosNamingService();
    }

    public static NamingService getNacosNamingService() {
        try {
            return NamingFactory.createNamingService(SERVER_ADDR);
        } catch (NacosException e) {
            logger.error(" Connect to Nacos Errors occur from time to time : ", e);
            throw new RpcException(RpcError.FAILED_TO_CONNECT_TO_SERVICE_REGISTRY);
        }
    }

    public static void registerService(String serviceName, InetSocketAddress address) throws NacosException {
        namingService.registerInstance(serviceName, address.getHostName(), address.getPort());
        NacosUtil.address = address;
        serviceNames.add(serviceName);
    }

    public static List<Instance> getAllInstance(String serviceName) throws NacosException {
        return namingService.getAllInstances(serviceName);
    }

    public static void clearRegistry() {
        if(!serviceNames.isEmpty() && address != null) {
            String host = address.getHostName();
            int port = address.getPort();
            Iterator<String> iterator = serviceNames.iterator();
            while(iterator.hasNext()) {
                String serviceName = iterator.next();
                try {
                    namingService.deregisterInstance(serviceName, host, port);
                } catch (NacosException e) {
                    logger.error(" Log out of service  {}  Failure ", serviceName, e);
                }
            }
        }
    }
}

        Nacos It's easy to use , adopt NamingFactory establish NamingService Connect Nacos, The connection process is written in a static code block , Automatically connect when the class is loaded .namingService It provides two very convenient interfaces ,registerInstance and getAllInstances Method , The former can be directed to Nacos Registration service , The latter can get a list of all providers that provide a service . So the two methods of the interface only need to be wrapped .

         stay NacosUtil In which we pass getAllInstance After getting the list of all providers of a service , You have to choose one , This involves the load balancing strategy , Here we choose the first 0 individual , Later, we will explain load balancing in detail .

        Next , We modify RpcServer Interface , Add a new method publishService, Used to direct to Nacos Registration service :

<T> void publishService(Object service, Class<T> serviceClass);

         Then you just need to implement this method , With NettyServer For example ,NettyServer You need to create a ServiceRegistry 了 :

 public NettyServer(String host, int port) {
        this.host = host;
        this.port = port;
        serviceRegistry = new NacosServiceRegistry();
        serviceProvider = new ServiceProviderImpl();
    }
public <T> void publishService(Object service, Class<T> serviceClass) {
        if(serializer == null) {
            logger.error(" Serializer not set ");
            throw new RpcException(RpcError.SERIALIZER_NOT_FOUND);
        }
        serviceProvider.addServiceProvider(service);
        serviceRegistry.register(serviceClass.getCanonicalName(), new InetSocketAddress(host, port));
    }

        there serviceProvider Is the instance object of the local saved service class ,publishService The service needs to be saved in the local registry , Also register to Nacos On .

        Finally, there is the service discovery part , Let's summarize it later with load balancing ! I think it's useful for everyone , You can give bloggers a compliment ~

原网站

版权声明
本文为[Li bohuan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/187/202207060916514733.html