Nacos listening and service discovery

Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

Get all instances

Get all service instances from nacOS Server by service name:

The Open API: / nacos/v1 / ns/instance/list (GET) the SDK:List<Instance> getAllInstances(String serviceName) throws NacosException;
List<Instance> getAllInstances(String serviceName,List<String> clusters) throws NacosException;
Copy the code

Call method:

NamingService namingService=NamingFactory.createNamingService(Systm.getProperty("serverAddr"));
List<Instance> instances=namingService.getAllInstances("server1");
Copy the code
Listening to the service

The monitoring service is the instance change under the service specified by the quiver. The instance that the client needs to obtain from the NACOS Server must be healthy, otherwise the client request will fail. The monitoring service mechanism enables the client to sense the change of the service provider instance in time

Open Api: /nacos/v1/ns/instance/list (GET)
SDK:
void subscribe(String serviceName,EventListenster listener) throwsNacosException;void subscribe(String serviceName,List<String> clusters,EventLister listener) throws NacosException;
Copy the code

Related parameters:

  • EventListener: An event callback is triggered when a service provider instance goes up or down.

SpringBoot integrates with Nacos for service registration and discovery

  1. Create a SpringBoot project

  2. Adding Maven dependencies

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

Create the Controller class, inject Nacos’s NamingService through @nacosinjected, and create a Discovery method to get the service address registered with Nacos based on service name

@RestController
public class DiscoveryController {

    @NacosInjected
    private NamingService namingService;
    
    public List<Instance> discovery(String serviceName) throws NacosException {
        returnnamingService.getAllInstances(serviceName); }}Copy the code

Add the configuration of the Nacos service address in application.xml

nacos:
  discovery:
    server-addr: 127.0. 01.: 8848
Copy the code

Through SpringBootNacosApplication start classes start project, through the postman send a get request to http://127.0.0.1:9090/discovery? ServiceName =server1 Query the IP address of server1 on the Nacos Server. In this case, an empty JSON array is returned because the Nacos Server has no service instance of server1.

Then register a service named Server1 with the Nacos Server through the OpenApi provided by Nacos.

http; / / 127.0.0.1:8848 / nacos/v1 / ns/instance? ServiceName = server1 = 127.0.0.1 & IP & port = 9090

Once again, visit http://127.0.0.1:9090/discovery? ServiceName =server1 Returns details about the service instance.