The underlying implementation principle of Nacos & the two calling methods of the registration center

Table of Contents

1. The underlying implementation principle of Nacos

1.1 Implementation principle of automatic refresh of configuration center

1.2 The underlying implementation principle of the registration center

2. Two ways to call the Nacos registration center

2.1 How to call RestTemplate + Spring Cloud LoadBalancer

2.2 Using OpenFeign + Spring Cloud LoadBalancer


1. The underlying implementation principle of Nacos

1.1 Implementation Principle of Automatic Refresh of Configuration Center

The bottom layer of the automatic refresh of the Nacos configuration center is based on long polling + event-driven approach.

Long polling: The client implements a monitoring mechanism for configuration updates by sending an HTTP long polling request to the Nacos server. The purpose of this is to reduce frequent requests and ensure that the client can be quickly notified when configuration updates are made.

Event-driven: When the registration center changes and an event occurs, the event will be pushed to subscribers.

Compare long connections to understand long polling >>

Persistent Connection:

  • A long connection means that after a connection is established, the connection between the client and the server will remain active until one of the parties explicitly closes the connection.
  • In a long connection, the TCP connection will not be closed immediately after transmitting the HTTP response by default, but can be used to transmit multiple requests and responses.
  • Long connections reduce the overhead of frequently establishing and closing connections, but if there are too many connections, the resource pressure on the server will be greater.

Long Polling:

  • Long polling means that the client initiates a request to the server. If there is no data update on the server side, it will not respond immediately, but will keep the request open (maintain the connection for a period of time) until there is data update or timeout.
  • When data is updated, the server responds to the request and sends the update to the client. After the client processes the response, it will initiate a new request again and start long polling again.
  • Long polling is not a continuous network connection. The connection will be closed after each polling is completed, and then the client will initiate a new request. This results in a short delay between each polling cycle.

Based on the above comparison, it can also be seen that long polling is helpful for Nacos to perform health detection, because health detection is to send heartbeat packets at intervals.

The specific execution process of the configuration center is as follows:

1. The client sends a long polling request with a listener to the Nacos server to obtain the value of a specific configuration.

2. After receiving this long polling request, the Nacos server will check whether the configuration has changed. If there are no changes, the request will be blocked until timeout or the configuration changes. (Usually set a longer timeout, such as 30 seconds)

3. When the configuration changes, the Nacos server will respond immediately and respond to the client with the new configuration.

4. After the client receives the new configuration value, it can update its own configuration as needed.

1.2 The underlying implementation principle of the registration center

The underlying implementation of the Nacos registry mainly relies on two key components:Service registration + service discovery.

If you don’t understand service registration and service discovery very well, you can read my article first: https://blog.csdn.net/xaiobit_hl/article/details/134142521

The execution process of Nacos registration center is as follows

1. Service registration:

  • When the service starts, it will send a registration request to the Nacos server, including its own metadata information.
  • After receiving the registration request, the Nacos server will maintain a registry in the memory, and then store the service provider’s information (such as service name, IP, port, health status, etc.) into the service registry for subsequent service discovery. .

2. Service synchronization (if multiple Nacos instances are deployed):

  • The service synchronization mechanism in the Nacos cluster ensures that all Nacos instances contain the latest information about all services.
  • The synchronization process is usually coordinated internally by the Nacos cluster to ensure data consistency of each instance.

3. Heartbeat mechanism:

  • The service instance periodically sends heartbeats to the Nacos server to keep its registration information active, indicating its health status and availability.
  • If Nacos does not receive a heartbeat from a service instance within the configured heartbeat time, it will consider the instance to be unavailable and may remove it from the service list.

4.. Service discovery:

  • When a service consumer calls a service, it will send a service discovery request to Nacos.
  • Nacos will return a list of available service instances, and the client will select an instance to call based on this list through the load balancing policy.

5. Load balancing:

  • During the service discovery process, Nacos also provides load balancing support. Consumers can choose an appropriate load balancing strategy to select one or more instances for invocation.
  • There are two load balancing strategies in Nacos: weight + CMDB.

2. Two ways to call the Nacos registration center

When Nacos registers the Restful interface, there are two main ways to call it:

  1. Using RestTemplate + Spring Cloud LoadBalancer
  2. Using OpenFeign + Spring Cloud LoadBalancer

2.1 How to call RestTemplate + Spring Cloud LoadBalancer

Implementation steps:

  1. Add dependencies: nacos + loadbalancer
  2. Set configuration information
  3. Write calling code

① Add dependencies: nacos + loadbalancer

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-loadbalancer</artifactId>
</dependency>

② Set configuration information

spring:
  application:
    name: nacos-discovery-business
  cloud:
    nacos:
      discovery:
        server-addr: localhost:8848
        username: nacos
        password: nacos
        register-enabled: false #Set the consumer not to register to Nacos

③Write the calling code

This is divided into two steps to achieve:

  1. Add LoadBalanced support for RestTemplate
  2. Use RestTemplate to call the interface

1. Add RestTemplate’s LoadBalanced support

Add the @EnableDiscoveryClient annotation on the Spring Boot startup class, and then replace the RestTemplate in the Ioc container with the @LoadBalanced annotation.

@SpringBootApplication
@EnableDiscoveryClient // Add RestTemplate’s LoadBalanced support
public class ConsumerApplication {

    @LoadBalanced
    @Bean
    public RestTemplate restTemplate() {
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(ConsumerApplication.class, args);
    }
}

2. Use RestTemplate to call the interface

@RestController // Consumer
public class BusinessController2 {

    @Autowired
    private RestTemplate restTemplate;

    @RequestMapping("/getnamebyid")
    public String getNameById(Integer id) {
        return restTemplate.getForObject("http://nacos-discovery-demo/
user/getnamebyid?id=" + id,String.class);
    }
}

2.2 Using OpenFeign + Spring Cloud LoadBalancer

Using this method to call the registration center, the implementation steps are divided into the following 5 steps:

  1. Add framework support [nacos discovery, spring cloud LoadBalancer, spring cloud OpenFeign]
  2. Configure Nacos connection information
  3. Turn on OpenFeign function
  4. Declare OpenFeign-style Service [Producer Service]
  5. Call service [call producer’s service]

For the specific implementation code, please refer to my last blog: https://blog.csdn.net/xaiobit_hl/article/details/134142521

The knowledge points of the article match the official knowledge files, and you can further learn relevant knowledge. Cloud native entry-level skills treeHomepageOverview 16,929 people are learning the system