In previous articles, we introduced microservices and learned about the Microservices Gateway. Now let’s learn about the registry of microservices. What is the registry? Now each of our microservices is deployed on an independent machine or docker, and each has an independent IP address, so service discovery is basically to obtain the IP address deployed by the service in some way. If service A invokes service B in microservice mode, it needs to obtain the IP address and port of the machine on which service B is deployed from the registry in order to invoke service B. So you can imagine that registries are very important in the overall microservices system. We often hear about ZooKeeper as one of the service discovery components, including eureka, which is provided in the springcloud system. Today we’re going to look at NACOS and why we want to replace Eureka with nacos.

What is a nacos

Nacos is alibaba’s open source application that can be used as a service discovery component and a configuration center component. Take a look at the NACOS architecture and ecology:Nacos can be integrated with Spring, Spring Boot, Spring Cloud, And can replace Spring Cloud Eureka, Spring Cloud Config. The commercial products of Alibaba correspond to ACM and EDAS.

  • Dynamic configuration changes are implemented through Nacos Server and spring-cloud-starter-alibaba-nacos-config.
  • Nacos Server and spring-cloud-starter- alia-NacOS-Discovery are used to realize service registration and discovery.

The use of nacos

Service registration and discovery using Nacos

The link and function of registry in the whole microservice system. A simple process as shown in the figure below is that the service provider starts to register with NACOS and informs NACOS of my IP and port. After that, the service consumer receives the corresponding synchronization message from NACOS. The Consumer then gets the provider’s unfamiliar machine IP and port to call the service.ZooKeeper, Eureka, Consul, and Nacos can all be used as registries to compare each other:Pictured above nacos support AP and CP mode at the same time, the temporary and permanent he choose according to the service registry to determine the AP mode or CP, support the CP mode I understand he here, should be central to configure the cluster, because nacos can at the same time as the registry and configuration center, because of his information is saved in nacos configuration center If the configuration information has not been synchronized after one of the NACOS machines has died, the configuration inconsistency may occur. Nacos currently supports temporary instances to be kept alive by heartbeat reporting. The default period for sending a heartbeat is 5 seconds. The Nacos server will set the instance as unhealthy after 15 seconds without a heartbeat, and remove the temporary instance after 30 seconds without a heartbeat.

Performance:

Nacos Service Discovery (3 nodes)

  1. The number of services under pressure testing can reach 60W, and the number of instances registered can reach 110W. The cluster runs steadily and meets expectations.
  2. Registration/query instance TPS reached more than 13000, interface reached the expected;

Nacos configuration center

  1. Release and listening time difference, within 100ms can basically listen to the configuration changes

Nacos registry configuration process

Download nacos (github.com/alibaba/nac…

  1. Linux/Unix/Mac: sh startup.sh -m standalone
  2. Windows: CMD startup. CMD -m standalone

The startup.sh script is stored in the bin directory after Nacos is decompressed. This section mainly introduces the integrated use of Spring Cloud and Nacos. After startup is complete, access:http://127.0.0.1:8848/nacos/, can enter the Nacos service management page, specific as follows: A friend made a public service nacOS for everyone to use, I don’t know if it is still available now, you can try it, I used it before. Public Nacos services: Nacos Console

  • Address: nacos.didispace.com/nacos/index…
  • The account and password are both nacos

Client use configuration

  • Using the registry service: spring.cloud.nacos.discovery.server-addr=nacos.didispace.com: 80
  • Using the configuration center service: spring.cloud.nacos.config.server-addr=nacos.didispace.com: 80

(2) Build application access Nacos registry

  • Service provider
  1. Create a Spring Boot application that you can name alibaba-nacos-discovery-server.
  2. Edit the pom.xml to add the necessary dependency configuration.
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.0. 5.RELEASE</version> <relativePath/> <! -- lookup parent from repository --> </parent> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> <version>0.22..RELEASE</version>
</dependency>
Copy the code

One important note here: Be aware of version requirements and mappings when integratingWhen the package is introduced, springcloud official and alibaba are used. If you use one, try not to mix itIf springBoot1. x is used, use version 1.5.0. If SpringBoot2. x is used, use version 2.0.0 or later.3. Add the @enableDiscoveryClient annotation to the startup class and provide an API interface

@EnableDiscoveryClient
@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
    @Slf4j
    @RestController
    static class TestController {
        @GetMapping("/hello1")
        public String hello1(@RequestParam String name) {
            log.info("name = " + name);
            return "hello1: "+ name; }}}Copy the code
  1. Yml or properties
spring.application.name=alibaba-nacos-discovery-server
server.port=8001
spring.cloud.nacos.discovery.server-addr=127.0. 01.:8848
Copy the code
  1. Start the service. If the following information is displayed on the console or in logs, the service is registered successfully
INFO 18473 --- [main] o.s.c.a.n.registry.NacosServiceRegistry  : nacos registry, alibaba-nacos-discovery-server 10.1124.69.:8001 register finished
Copy the code

Then visit the previous page address to see the following:

  • Service consumer
  1. Create a Spring Boot application that you can name alibaba-nacos-discovery-client-Consumer.
  2. Edit the dependencies in pom.xml, as above.
  3. Annotate the main class and invoke the service interface using LoadBalancerClient
@EnableDiscoveryClient
@SpringBootApplication
public class TestApplication {
    public static void main(String[] args) {
        SpringApplication.run(TestApplication.class, args);
    }
    @Slf4j
    @RestController
    static class TestController {
        @Autowired
        LoadBalancerClient loadBalancerClient;
        @GetMapping("/test1")
        public String test1(a) {
            // Use the load balancing interface in Spring Cloud Common to select the service provider node for interface invocation
            ServiceInstance serviceInstance = loadBalancerClient.choose("alibaba-nacos-discovery-server");
            String url = serviceInstance.getUri() + "/hello1? name=" + "lalalala";
            RestTemplate restTemplate = new RestTemplate();
            String result = restTemplate.getForObject(url, String.class);
            return The result returned is:+ result; }}}Copy the code

The yML configuration is the same as that of the service provider. After starting the consumer side, we repeatedly request the Test1 interface to find that the IP address of the calling service provider is different, which indirectly indicates that the load balancing of the service provider instance has been achieved when obtaining the service instance through the LoadBalancerClient interface.

Communication between services

  • Use RestTemplate
    @Bean
    @LoadBalanced
    public RestTemplate restTemplate(a) {
        return new RestTemplate();
    }
Copy the code
  • Using WebClient
    @Bean
    @LoadBalanced
    public WebClient.Builder loadBalancedWebClientBuilder(a) {
        return WebClient.builder();
    }
Copy the code
  • Use Feign (recommended)
    @FeignClient("alibaba-nacos-discovery-server")
   public interface AaService{
       @GetMapping("/hello1")
       String hello1(@RequestParam(name = "name") String name);
   }
Copy the code

To use it, just inject the AaService object in the corresponding call and call the hello1 method directly. Whether we’re using RestTempalte, WebClient, or Feign, it doesn’t matter if I’m using Nacos or not. Both Eureka and Consul implement service invocation in the same way. For Spring Cloud, even if we change Nacos as the new service registry, there is no impact on our application level code. So why does Spring Cloud provide such a perfect coding experience? In fact, this is all due to the encapsulation of Spring Cloud Common, due to the abstraction of service registration and discovery, client load balancing, etc., which the upper-layer applications rely on, rather than specific middleware implementations. So, in the Spring Cloud, it’s easy to switch the middleware for service governance. We will continue with the configuration and pits of NACos as another feature, Config, in the next article. If you want to know more, please pay attention to “IT Technology small stack “, I will wait for you there ~~~