This is the 8th day of my participation in the First Challenge 2022. For details: First Challenge 2022.

Nacos in Spring Cloud Alibaba technology system provides two important functions: registry (service registration and discovery) function and configuration center function.

The registry has solved the micro service invocation, the service provider and service the caller’s decoupling, lets developers don’t need too much attention to the service provider and the caller’s execution details, only need through Nacos registry can be achieved both connectivity, equivalent to realize the remote service localization, and provides a health check mechanism, etc.

The Nacos registry provides two methods for registering and discovering services: the OpenAPI method and the (Nacos) SDK method.

The so-called OpenAPI refers to the registration and discovery of services through the OpenAPI address provided by Nacos; The SDK method is through the SDK framework provided by Nacos, that is, the spring-cloud-starter-Alibaba-Nacos-discovery framework is used to realize the function of service registration and discovery.

1. Service registration

1.1 Service Registration: OpenAPI mode

OpenAPI is relatively simple to use. First, open the command line of the system and use the following command line to register the service:

The curl -x POST ‘http://127.0.0.1:8848/nacos/v1/ns/instance? ServiceName = spring – the cloud – nacos – producer&ip = 192.168.76.224 & port = 8081 ‘

The following figure shows the execution result of the preceding commands:If OK is displayed, the service is successfully registered.

  • ServiceName: indicates the serviceName.
  • IP: IP address of the client program.
  • Port: indicates the port number of the client program.

At the same time, when we open the Nacos management background, we can also see our registered services, as shown in the picture below:Click service Details, you can see our registered IP address and port, as shown below:

1.2 Service Registration: SDK mode

SDK model needs to first create a Spring Cloud project, please refer to the project creation method: mp.weixin.qq.com/s/c4EHDWAlT… The SDK framework of Nacos is supported, and the relevant information of Nacos can be configured at last. The specific implementation is as follows.

1.2.1 add the SDK

Add Nacos SDK framework support to POM.xml, and the specific configuration is as follows:

<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Copy the code

1.2.2 Nacos configuration

After the SDK framework is added, you need to add the corresponding configuration in the configuration file of the project. The specific configuration content is as follows:

# app name
spring.application.name=spring-cloud-nacos-producer
# Nacos authentication information
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=nacos
# Nacos service discovery and registration configuration, where the sub-attribute server-addr specifies the Nacos server host and port
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
Register with the specified namespace of nacOS. Default is public
spring.cloud.nacos.discovery.namespace=public
Copy the code

After setting the above configuration, start the current project and the application will automatically register itself with the Nacos server.

2. Service discovery

Once the service is properly registered with Nacos, the normal invocation of the service provider exposed methods can be discovered through the service, which is still implemented in the following two ways.

2.1 Service Discovery: OpenAPI mode

Use the following command from the system command line to implement service discovery:

The curl -x GET http://127.0.0.1:8848/nacos/v1/ns/instance/list? serviceName=nacos.naming.serviceName’

The following information is displayed:The following information is displayed after JSON formatting:

{
  "name": "DEFAULT_GROUP@@spring-cloud-nacos-producer"."groupName": "DEFAULT_GROUP"."clusters": ""."cacheMillis": 10000."hosts": [{"instanceId": "192.168.76.224 # 8081 # DEFAULT# DEFAULT_GROUP @ @ spring - the cloud - nacos - producer." "."ip": "192.168.76.224"."port": 8081."weight": 1."healthy": true."enabled": true."ephemeral": true."clusterName": "DEFAULT"."serviceName": "DEFAULT_GROUP@@spring-cloud-nacos-producer"."metadata": {
        "preserved.register.source": "SPRING_CLOUD"
      },
      "instanceHeartBeatInterval": 5000."instanceHeartBeatTimeOut": 15000."ipDeleteTimeout": 30000}]."lastRefTime": 1644210068852."checksum": ""."allIPs": false."reachProtectionThreshold": false."valid": true
}
Copy the code

Among them:

  • Healthy: indicates whether to enable the health detection function, that is, to regularly report their health status to the Nacos server.
  • Ephemeral: Indicates whether it is a temporary instance. After being offline for a certain period of time, the temporary instance is removed by Nacos.
  • “” instanceHeartBeatInterval” : 5000 “said: once every 5 s implementation of health inspection.
  • “InstanceHeartBeatTimeOut “: 15000 “: Indicates that if no heartbeat packet is received within 15 seconds, the instance is set to unhealthy.
  • “IpDeleteTimeout “: 30000: indicates that if the heartbeat packet is not received within 30 seconds, the temporary instance is deleted.

2.2 Service Discovery: SDK mode

Similar to the steps of SDK to implement service registration, service discovery is to create a Spring Cloud project, add the Nacos SDK framework, configure nacOS-related information, and finally write code to invoke the methods provided by the service provider.

2.2.1 add the SDK

Add Nacos SDK framework support to the pom. XML file of the project as follows:

<dependency>
  <groupId>com.alibaba.cloud</groupId>
  <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Copy the code

2.2.2 configuration Nacos

Add the following configuration for Nacos to the project configuration file:

# app name
spring.application.name=springcloud-nacos-consumer
# Nacos authentication information
spring.cloud.nacos.discovery.username=nacos
spring.cloud.nacos.discovery.password=nacos
# Nacos service discovery and registration configuration, where the sub-attribute server-addr specifies the Nacos server host and port
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
Register with the specified namespace of nacOS. Default is public
spring.cloud.nacos.discovery.namespace=public
Copy the code

2.2.3 Invoking the Service Provider

The final step is to use the RestTemplate object in the project to implement the method exposed by invoking the service provider. First we need a RestTemplate object, which looks like this:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@EnableDiscoveryClient
public class SpringcloudNacosConsumerApplication {
    public static void main(String[] args) {
        SpringApplication.run(SpringcloudNacosConsumerApplication.class, args);
    }
    @LoadBalanced
    @Bean
    public RestTemplate restTemplate(a) {
        return newRestTemplate(); }}Copy the code

Now that we have the RestTemplate object, we can call the service provider as follows:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@RestController
public class TestController {
    @Autowired
    private RestTemplate restTemplate;
    @RequestMapping("/hi")
    public String hi(String name) {
        // Call the service provider's sayhi method and return the result
        return restTemplate.getForObject("http://spring-cloud-nacos-producer/sayhi/"+ name,String.class); }}Copy the code

Spring-cloud-nacos-producer in http://spring-cloud-nacos-producer/sayhi/xxx is the service name of NACOS, and /sayhi/ XXX is the method access address provided by the service provider. As you can see, there is no need for the service caller to know the exact address of the service provider, just to call the service name provided by Nacos, thus decoupling the service provider from the caller.

summary

Nacos registry provides two methods for service registration and discovery: OpenAPI and SDK. The most common one is the implementation of SDK, which is to add THE SDK of Nacos in the project, and then configure the relevant configuration of Nacos to realize the automatic registration and invocation of services.

Judge right and wrong from yourself, praise to listen to others, gain and loss in the number.

Public account: Java Chinese Community

Java Interview Collection: gitee.com/mydb/interv…