This is the first day of my participation in the August Challenge. For details, see:August is more challenging

Reading reminder:

  1. This article is intended for those with some springBoot background
  2. The Hoxton RELEASE of Spring Cloud is used in this tutorial

This paper gives an overview of

  • What is a registry?
  • What is a configuration center?
  • How to use Nacos in springcloud?

preface

Before using NACOS, we need to understand what role NACOS plays in the overall microservices architecture, where the registry is one of the very core infrastructure services that appeared in distributed architectures before microservices became popular. For example, Dubbo, which is a popular distributed architecture in China, is also a very practical framework, providing relatively complete service governance functions, and the implementation of service governance mainly depends on the registry.

The source address for the demo used in this article: github.com/WinterChenS…

What is a registry?

The registry is the “address book” of the microservices architecture, recording the mapping between services and their addresses. In a distributed architecture, services are registered here, and when a service needs to call another service, it finds the address of the service and makes the call.

Here’s a simple example:

  1. To call Xiao Hong, Xiao Ming needs to get Xiao Hong’s phone number (service address) from the address book (registration center);
  2. Xiao Ming calls Xiao Hong’s phone number (service request) according to the phone number in the address book.
  3. Xiao Hong gets through and finishes the call;
  4. Dialing xiao Hong’s phone number later can be done through the phone saved number (local cache);

Nacos ACTS as the address book in the whole micro service architecture, the role of service between the invocation, monitoring and so on all need through the registry access service address port mapping, and generally will be the local cache server, before the next request can query the local mapping information service, improve service throughput can reduce network request.

What is a configuration center?

The configuration center is simple, literally. By centralizing the configuration of services in the configuration center, dynamic changes can be implemented, avoiding the embarrassment of having to republish services every time the configuration file is modified.

Download nacOS and start

Nacos is dedicated to helping you discover, configure, and manage microservices. Nacos provides a set of easy-to-use features that help you quickly implement dynamic service discovery, service configuration, service metadata, and traffic management. Download at github.com/alibaba/nac…

After the download is complete, decompress it. In the /bin directory of the decompressed file, click startup. CMD on Windows to start nacos. Linux or MAC Run the following command to start nacos.

sh startup.sh -m standalone

Landing page: http://localhost:8848/nacos/ login user nacos, password for nacos.

JDK version

  • The JDK: 1.8
  • Maven: 3.3.9
  • Nacos: 2.0

Springcloud and SpringBoot versions

  • springcloud: Hoxton.RELEASE
  • Springboot: 2.2.13. RELEASE
  • Springcloud – alibaba: 2.2.0. RELEASE

Configuration center

First, let’s create a new SpringBoot foundation project named spring-cloud-Hoxton-Study

Project Structure:

- spring - the cloud - hoxton - study | - spring - the cloud - nacos - consumer | - pom. The XMLCopy the code

Add dependencies to parent POM files (spring-cloud-hoxton-study) :


<properties>
        <java.version>1.8</java.version>
        <spring-cloud.version>Hoxton.RELEASE</spring-cloud.version>
        <spring-boot.version>2.2.13. RELEASE</spring-boot.version>
        <spring-cloud-alibaba.version>2.2.0. RELEASE</spring-cloud-alibaba.version>
    </properties>
    <dependencyManagement>
        <dependencies>
            <! -- springCloud dependency -->
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>${spring-cloud.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

            <! -- springBoot dependency -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-dependencies</artifactId>
                <version>${spring-boot.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>

						<! -- Spring Cloud alibaba dependency -->
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>${spring-cloud-alibaba.version}</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
Copy the code

Child POM modification (spring-cloud-nacos-Consumer) : parent

<parent>
    <groupId>com.winterchen</groupId>
    <artifactId>spring-cloud-hoxton-study</artifactId>
    <version>0.0.1 - the SNAPSHOT</version>
</parent>
Copy the code

Subpom to add dependencies (spring-cloud-nacos-Consumer) :

				<dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

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

Note: This is just the main Maven dependencies. If you want to see all the dependencies, check out the demo source code

Create configuration:bootstrap.propertiesorbootstrap.yml

bootstrap.properties

Spring. Cloud. Nacos. Config. Server - addr = 127.0.0.1:8848 spring. Application. The name = winter - nacos - consumer spring.profiles.active=devCopy the code

bootstrap.yml

spring:
  cloud:
    nacos:
      config:
        server-addr: 127.0. 01.: 8848
        file-extension: yaml
  application:
    name: winter-nacos-consumer
  profiles:
    active: dev
Copy the code

127.0.0.1:8848 is the nacOS service built above

You need to configure spring.application.name because by default nacos gets the configuration file as dataId by name

In Nacos Spring Cloud, the complete dataId format is as follows:

${prefix}-${spring.profiles.active}.${file-extension}
Copy the code
  • The default for the prefixspring.application.name, or through the configuration itemspring.cloud.nacos.config.prefixTo configure.
  • spring.profiles.activeThat is, corresponding to the current environmentprofileDetails can be referred toSpring BootThe document. Note: whenspring.profiles.activeWhen null, the corresponding hyphen – will also not exist, and the dataId concatenation format will become${prefix}.${file-extension}
  • file-exetensionTo configure the data format of the content, you can run the configuration itemspring.cloud.nacos.config.file-extensionTo configure. Currently only supportspropertiesyamlType.

Create a configuration file in the NACOS configuration center

Configuration details:

Data ID: winter-nacos-consumer-dev.yaml

Group: DEFAULT_GROUP

Configuration content:

server:
  port: 16011

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0. 01.: 8848

test:
  config:
    refresh: true
Copy the code

Automatically refresh

The Spring Cloud native annotation @refreshScope implements automatic configuration updates:

@Api("nacos api")
@RestController
@RequestMapping("/nacos")
@RefreshScope
public class NacosController extends BaseController {

    @Value("${test.config.refresh:true}")
    private boolean refresh;

    @GetMapping("/")
    public CommonResult<Boolean> get(a) {
        returnCommonResult.success(refresh); }}Copy the code

How to test

We can request the above interface: http://127.0.0.1:16011/nacos

The result is: true

Then modify the configuration center:

test:
  config:
    refresh: false
Copy the code

You can see that the console logs are printed:

2021-07-27 11:25:13.973  INFO 17240-- -- -8.2536.41 _8848.] o.s.c.e.event.RefreshEventListener       : Refresh keys changed: [test.config.refresh]
Copy the code

If you ask again, the result will be: false

Service registration and discovery

Still use the above project

Add a dependency:

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

Increase the configuration

Here is the complete configuration

server:
  port: 16011

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0. 01.: 8848

test:
  config:
    refresh: true
Copy the code

The startup class @enableDiscoveryClient was added to enable service registration and discovery

@SpringBootApplication(exclude= {DataSourceAutoConfiguration.class})
@EnableDiscoveryClient
public class SpringCloudNacosApplication {

    public static void main(String[] args) { SpringApplication.run(SpringCloudNacosApplication.class, args); }}Copy the code

Next, we need to test whether the service registration and discovery function is normal, so we need to copy the original service spring-cloud-nacos-Consumer and rename it as: Spring-cloud-nacos-provider

Current engineering structure:

- spring - the cloud - hoxton - study | - spring - the cloud - nacos - consumer | - spring - the cloud - nacos - provider | - pom. The XMLCopy the code

Add the NacosController in the spring-cloud-nacos-Consumer service by echo

@RestController
@RequestMapping("/nacos")
@RefreshScope
public class NacosController {

    @Value("${test.config.refresh:true}")
    private boolean refresh;

    private final RestTemplate restTemplate;

    @Autowired
    public NacosController(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @GetMapping("")
    public boolean get(a) {
        return refresh;
    }

    @GetMapping("/echo/{str}")
    public String echo(@PathVariable String str) {
        return restTemplate.getForObject("http://winter-nacos-provider/nacos/echo/"+ str, String.class); }}Copy the code

Add the NacosController in the spring-cloud-nacos-Provider service by using echo

@RestController
@RequestMapping("/nacos")
@RefreshScope
public class NacosController {

    @Value("${test.config.refresh:true}")
    private boolean refresh;

    @GetMapping("")
    public boolean get(a) {
        return refresh;
    }

    @GetMapping("/echo/{string}")
    public String echo(@PathVariable String string) {
        return "Hello Nacos Discovery "+ string; }}Copy the code

Start testing:

Before testing, you need to configure the configuration center for Spring-cloud-NACos-Provider:

  1. Modify thebootstrap.ymlspring.application.name=winter-nacos-provider ;
  2. Add a configuration file in the Configuration center:winter-nacos-provider-dev.yamlThe configuration is as follows:
server:
  port: 16012

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 118.2536.. 41: 8848
  profiles:
    active: dev

test:
  config:
    refresh: true
Copy the code

Start two service respectively, and then call interface: http://127.0.0.1:16011/nacos/echo/hello

Result of request:

conclusion

This article describes how springcloud uses nacos as a configuration center and registry, two basic features that are core to microservices and require proficiency in real-world use. It also describes how to use it in combination with other components.

The restTemplate used above for service invocation is obviously very inconvenient in actual use, so how to use remote invocation in real application? The next article will show you how to use Open Feign for remote service calls.

The source address

Github.com/WinterChenS…

References:

Nacos Spring Cloud starts quickly