springcloud uses nacos for service registration and discovery

Since the open source of spring-cloud-alibaba, the registration and discovery of services using nacos in springcloud has become very easy, just need to introduce "spring-cloud-starter-alibaba-nacos-discovery", and then open @EnableDiscoveryClient can seamlessly replace registries such as eureka and consul.

The following demonstrates how to use nacos in springcloud by giving a simple case.

nacos-discovery-stater principle

First, let's take a look at the principle of service registration and discovery in nacos in springcloud.

service registration

spring-cloud-starter-alibaba-nacos-discovery follows the spring-cloud-common standard and implements the three interfaces of AutoServiceRegistration, ServiceRegistry, and Registration.

In the startup phase of the springcloud application, the WebServerInitializedEvent event is monitored. When the Web container is initialized, that is, after receiving the WebServerInitializedEvent event, the registration action will be triggered, and the register method of the ServiceRegistry will be called to register the service to Nacos Server.

service discovery

NacosServerList implements the com.netflix.loadbalancer.ServerList interface and performs automatic injection under the condition of @ConditionOnMissingBean, and integrates Ribbon by default.

If you need a more customized one, you can use @Autowired to inject a NacosRegistration instance, and directly call the Nacos API through the content of the NamingService field it holds.

nacos-service-provider

Create a service provider springcloud project and introduce the following dependencies:

    <properties>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
        <spring-cloud.alibaba.version>0.2.1.RELEASE</spring-cloud.alibaba.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud.alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
    </dependencies>

Configure the configuration information related to nacos in the application.yml file of the project as follows:

If you don't want to use Nacos as your service registration and discovery, you can set spring.cloud.nacos.discovery to false.

spring:
  application:
    name: nacos-service-provider
  cloud:
    nacos:
      discovery:
        register-enabled: true
        server-addr: 127.0.0.1:8848
        weight: 1
        namespace: dev
management:
  endpoints:
    web:
      exposure:
        include: "*"

server:
  port: 8080

The next step is to create a service for the caller to use. Don't forget to introduce the @EnableDiscoveryClient annotation in the main function.

package com.lazycece.scac.nacos.discovery.provider.controller;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

/**
 * @author lazycece
 * @date 2019/03/19
 */
@RestController
@RequestMapping("/nacos")
public class NacosProviderController {
    @GetMapping("/provider/{name}")
    public String provider(@PathVariable String name) {
        return "hello," + name;
    }
}

nacos-service-consumer

Create a springcloud project for service consumers, and introduce the following dependencies. Here, the dependencies of open-feign and ribbon are introduced to demonstrate the consumption of these two methods at the same time.

    <properties>
        <spring-cloud.version>Greenwich.SR1</spring-cloud.version>
        <spring-cloud.alibaba.version>0.2.1.RELEASE</spring-cloud.alibaba.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud.alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
        <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-ribbon</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
    </dependencies>

Configure the configuration information related to nacos in the application.yml file of the project as follows:

If you don't want to use Nacos for your service registration and discovery, you can set spring.cloud.nacos.discovery to false.

spring:
  application:
    name: nacos-service-consumer
  cloud:
    nacos:
      discovery:
        register-enabled: true
        server-addr: 127.0.0.1:8848
        weight: 1
        namespace: dev
management:
  endpoints:
    web:
      exposure:
        include: "*"

server:
  port: 8081

The code to create the service consumer is as follows, don't forget to introduce the @EnableDiscoveryClient annotation in the main function.

package com.lazycece.scac.nacos.discovery.consumer.controller;

import com.lazycece.scac.nacos.discovery.consumer.api.FeignConsumerApi;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.loadbalancer.LoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

/**
 * @author lazycece
 * @date 2019/03/19
 */
@RestController
@RequestMapping("/nacos/consumer")
public class NacosConsumerController {

    private LoadBalancerClient loadBalancerClient;
    private RestTemplate restTemplate;
    private FeignConsumerApi feignConsumerApi;

    @Autowired
    public NacosConsumerController(LoadBalancerClient loadBalancerClient, RestTemplate restTemplate,
                                   FeignConsumerApi feignConsumerApi) {
        this.loadBalancerClient = loadBalancerClient;
        this.restTemplate = restTemplate;
        this.feignConsumerApi = feignConsumerApi;
    }

    @GetMapping("/rest/{name}")
    public String rest(@PathVariable String name) {
        ServiceInstance serviceInstance = loadBalancerClient.choose("nacos-service-provider");
        String url = String.format("http://%s:%s/nacos/provider/%s",
                serviceInstance.getHost(), serviceInstance.getPort(), name);
        System.out.println("url -> " + url);
        return restTemplate.getForObject(url, String.class);
    }

    @GetMapping("/feign/{name}")
    public String feign(@PathVariable String name) {
        return feignConsumerApi.provider(name);
    }


    @GetMapping("/ribbon/{name}")
    public String ribbon(@PathVariable String name) {
        return restTemplate.getForObject("http://nacos-service-provider/nacos/provider/" +
                name, String.class);
    }
}

To consume in rest mode, you need to inject RestTemplate. If you need to use ribbon for load balancing, you can annotate it with @LoadBalanced, otherwise you can not add it.

package com.lazycece.scac.nacos.discovery.consumer.config;

import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.client.RestTemplate;

/**
 * @author lazycece
 * @date 2019/03/19
 */
@Configuration
public class RestTemplateConfig {

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

To consume in feign mode, you need a feign client, as follows, and the project main function also needs to introduce the @EnableFeignClients
annotation.

package com.lazycece.scac.nacos.discovery.consumer.api;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

/**
 * @author lazycece
 * @date 2019/03/19
 */
@FeignClient("nacos-service-provider")
@RequestMapping("/nacos")
public interface FeignConsumerApi {

    @GetMapping("/provider/{name}")
    String provider(@PathVariable String name);
}

Service registration and discovery case verification

You need to start the nacos-server service first. For installation and deployment, see nacos installation and deployment .

Service EndPoint

spring-cloud-starter-alibaba-nacos-discovery provides an EndPoint when implemented, and the access address of EndPoint is http://ip:port/actuator/nacos-discovery. Because we added the spring-boot-starter-actuator dependency, we can view the endpoint information. There are two main types of EndPoint information:

  • subscribe: shows which service subscribers are currently
  • NacosDiscoveryProperties: Displays the basic configuration of the current service instance about Nacos

The information for one of the service instances accessing the EndPoint is as follows:

{
    "subscribe":[

    ],
    "NacosDiscoveryProperties":{
        "serverAddr":"127.0.0.1:8848",
        "endpoint":"",
        "namespace":"dev",
        "logName":"",
        "service":"nacos-service-provider",
        "weight":1,
        "clusterName":"DEFAULT",
        "namingLoadCacheAtStart":"false",
        "metadata":{

        },
        "registerEnabled":true,
        "ip":"192.168.3.8",
        "networkInterface":"",
        "port":8080,
        "secure":false,
        "accessKey":"",
        "secretKey":""
    }
}

nacos tube interface

Visit http://localhost:8848/nacos/ to enter the management interface of nacos, check the Service Management->Service List module, you can see that our service consumers and providers have been registered with nacos, as shown in the following figure:

insert image description here

service consumption

Here you need to start the nacos service first, then start the above two services, and visit the following address:
http://localhost:8081/nacos/consumer/rest/lazycece
http://localhost:8081/nacos/consumer/ribbon/lazycece
http: //localhost:8081/nacos/consumer/feign/lazycece

Output information: hello, lazycece

More springcloud nacos information

Other configuration information about spring-cloud-starter-alibaba-nacos-discovery is shown in the following figure:

insert image description here

Case source code

Case source address:
https://github.com/lazycece/springcloud-actual-combat/tree/master/springcloud-ac-alibaba/springcloud-ac-alibaba-nacos-discovery

Guess you like

Origin blog.csdn.net/m0_54850604/article/details/123684660