SpringCloudAlibaba: Nacos Learning for Service Registration and Discovery

Table of contents

1. Service Registration and Discovery Introduction

1. Common Registration Center

2. The basic process of service registration and discovery is:

3. The main benefits of service registration and discovery are:

2. Introduction of Alibaba Nacos

3. Basic use of Nacos

1. Linux installation package mode single node installation and deployment

1. jdk installation configuration

2. nacos installation

2. Nacos integrates SpringBoot to realize service registration and discovery

1. Create a parent project

2. Create a basic public module (common)

3. Create a user module (user-module)

4. Register the user module to nacos as a microservice

4. Realize service call based on Feign

1) What is Feign

2) What does load balancing mean?

3) Use of Feign (create order module order)

1. Create an order module and introduce dependencies

2. Add annotations to the startup class

3.yml file configuration

4. Write an OrderController

5. Add Fegin dependencies to the pom file of the user module

6. Add Fegin annotations to the user module on the startup class

7. Create a feign interface for the user module, and use Fegin to implement microservice calls

8. The controller calls and starts verification (the user service calls the order service)

Five, Nacos domain model division

1. Namespace division

(1) Create a namespace

(2) Configure the microservice namespace

2. Group division

6. Log Configuration

1. Local log configuration

method one:

way two

2. Global log configuration

(1) Add configuration file

(2) Lower the log level of springboot

Seven, Nacos unified configuration management

1. Why do we need a configuration center

2. Commonly used configuration centers

Several concepts of Nacos

3. Use of Nacos Configuration Center

(1) properties format

(2) yaml format

(3) profiles.active—granularity configuration

(4) Data Id configuration of custom extension (shared configuration)

(5) Priority

(6) Dynamic configuration refresh


1. Service Registration and Discovery Introduction

Service registration and discovery is one of the core components in the microservice architecture. Its main role is to manage the information of services and service instances, so that service consumers can dynamically find service instances that provide the required services.

Under the microservice architecture, a business service will be split into multiple microservices, and each service communicates with each other to complete the overall function. In addition, in order to avoid single point of failure, microservices will be deployed in cluster mode with high availability. The larger the cluster size, the higher the performance will be. Service consumers need to call the cluster composed of multiple service providers.

First, the service consumer needs to maintain the request address of each node of the service provider cluster in the local configuration file. Secondly, if a node in the service provider cluster goes offline or goes down, the request address of the node needs to be deleted synchronously in the local configuration of the service consumer to prevent the request from being sent to a downed node and causing the request to fail.

In order to solve such problems, it is necessary to introduce a service registration center, which mainly has the following functions:

  • Management of service addresses.

  • Service registration.

  • Service dynamic awareness.

1. Common Registration Center

There are many components that can realize such functions, such as ZooKeeper, Eureka Consul, Etcd, Nacos, etc. In this chapter, we mainly introduce Alibaba's Nacos.

  1. Eureka: Netflix's open source service registration and discovery component, Spring Cloud integrates it to provide out-of-the-box service registration and discovery functions.

  2. Consul: A part of Consul, a service grid solution produced by HashiCorp, which provides functions such as service registration and discovery, configuration management, and service monitoring.

  3. Zookeeper: Apache's top-level project is a tree-type directory service that supports change push and is suitable as a service registration and discovery component.

  4. Etcd: A distributed and reliable key-value storage developed by CoreOS, which is also commonly used as a storage medium for service registration and discovery.

  5. Nacos: Nacos is a dynamic service discovery, configuration management and service management platform that is easier to build cloud-native applications. It is one of the components of Spring Cloud Alibaba, responsible for service registration discovery and service configuration, which can be regarded as nacos=eureka+config.

2. The basic process of service registration and discovery is:

  1. When the service starts, register its own information with the designated registration center. Information includes service names, network addresses, port numbers, and more.

  2. The service consumer obtains the required service information from the registration center, and obtains a list of all service instances that provide the service.

  3. The service consumer selects a service instance based on a certain load balancing strategy and initiates a call.

  4. When the service instance stops, it will log out its own information to the registration center.

  5. The registration center pushes the instance change information to the consumer.

3. The main benefits of service registration and discovery are:

  1. Service consumers do not need to hard-code service instance addresses, and the registry acts as a service proxy to achieve loose coupling.

  2. Service providers can scale elastically without impacting consumers. The registration center will push the change information to consumers.

  3. It is easy to monitor and manage services, and you can see which services and their instances are in the system through the registration center.

  4. It helps to achieve gray scale release, and can control instance traffic in the registration center to perform smooth upgrades.

2. Introduction of Alibaba Nacos

Nacos is a dynamic service discovery, configuration management, and service management platform open sourced by Alibaba that makes it easier to build cloud-native applications. As an important component in the Spring Cloud Alibaba microservice ecosystem, it mainly provides the following functions:

  1. Service discovery and service health monitoring: support DNS-based and RPC-based service discovery, and provide real-time service health monitoring.

  2. Dynamic configuration service: supports two modes of centralized configuration and distributed configuration, and can push configuration changes in real time.

  3. Service management: Provides service management functions such as service orchestration management, service isolation, and weight management.

3. Basic use of Nacos

1. Linux installation package mode single node installation and deployment

Nacos can have three deployment modes:

  1. Stand-alone mode: for testing and development environments, does not support clusters.

  2. Cluster mode: used in production environments, supports cluster deployment, and ensures high availability.

  3. Multi-DataCenter mode: used in multi-datacenter scenarios, supports cross-datacenter deployment, and ensures maximum disaster recovery.

    Note: Nacos depends on the Java environment, and requires the use of JDK1.8 or higher.

There are two ways to install Nacos, one is source code installation, and the other is directly using the compiled installation package. Here choose to use the installation package to install.

1. jdk installation configuration

1) The following steps are required to install and configure JDK in Linux: Check whether JDK and JRE have been installed in the system. You can check with the following command:

[root@localhost /]# java -version

2) If JDK and JRE are not installed in the system, you need to download and install JDK. Refer to the Oracle official website to download the JDK installation package suitable for the system. Download link: Java Downloads | Oracle . Suppose the installation package is /opt/jdk-11.0.11_linux-x64_bin.tar.gz. Unzip the installation package. The following commands can be used:

tar -zxvf /opt/jdk-11.0.11_linux-x64_bin.tar.gz -C /opt/

3) Configure environment variables. Open the /etc/profile file:

sudo vi /etc/profile

4) Add the following at the end of the file:

export JAVA_HOME=/opt/jdk-11.0.9 
export PATH=$JAVA_HOME/bin:$PATH

5) Then save and exit the file. Execute the following command to make the configuration file take effect immediately:

source /etc/profile

6) Verify that the JDK is successfully installed and configured. The following commands can be used:

java -version

After executing this command, you should be able to see the installed JDK version information.

2. nacos installation

 1) Download the GitHub address of nacos

 2) Unzip the Nacos installation package

tar -zxvf nacos-server-2.2.2.tar.gz

After the decompression is complete, you will see a nacos folder in the decompressed directory.

3) Configure Nacos

Enter the decompressed nacos directory and modify the conf/application.properties file:

# 启用standalone模式(这个没有请自己添加)
nacos.standalone=true
# 修改端口号
server.port=8848
# 修改数据存储位置(XXX.XXX.XXX.XXX是网络中属性的IPv4地址,设置正确的数据库及用户名和密码)
spring.datasource.platform=mysql
db.num=1
db.url.0=jdbc:mysql://XXX.XXX.XXX.XXX:3306/nacos?characterEncoding=utf8&connectTimeout=1000&socketTimeout=3000&autoReconnect=true
db.user=your-db-username
db.password=your-db-password

4) Start the Nacos service and enter the nacos root directory, and execute the following command:

[root@bogon nacos]# sh bin/startup.sh -m standalone

In this way, the Nacos service will be started. During the startup process, if an error occurs, you can view the startup.log file in the logs directory to view the specific error information.

Error creating bean with name 'grpcSdkServer': Invocation of init method failed; nested exception is java.io.IOException: Failed to bind to address 0.0.0.0/0.0.0.0:9848

I reported this error at the time, it was always about port 9848

I tried two methods:

1. Shut down the service: [root@localhost bin]# sh shutdown.sh Try restarting the service again.

2. If there is another word, it is a problem with the configuration file /nacos/conf/application.properties

5) Access Nacos service (xxx.xxx.xxx.xxx use the ip a command to view the IP address) The default access address of Nacos is http://xxx.xxx.xxx.xxx:8848/nacos , which can be entered in the browser This address is used to access Nacos services. If everything is normal, you will see the Nacos login interface, enter the default account (nacos) and password (nacos) to log in.

So far, Nacos has been successfully installed.

At this point, a problem will be found:

Skip permission authentication, you can enter without logging in, you can read a blog I wrote before: Enable authentication

2. Nacos integrates SpringBoot to realize service registration and discovery

1. Create a parent project

Create a maven project, and then add the corresponding relationship of each version of the following content to the pom.xml file. Refer to the official website: official website version corresponding relationship description address

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>org.example</groupId>
    <artifactId>BK-SpringCloud</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <artifactId>spring-boot-starter-parent</artifactId>
        <groupId>org.springframework.boot</groupId>
        <version>2.6.11</version>
    </parent>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>2021.0.4</version>
                <type>pom</type>
				<scope>import</scope>
            </dependency>
            <dependency>
                <groupId>com.alibaba.cloud</groupId>
                <artifactId>spring-cloud-alibaba-dependencies</artifactId>
                <version>2021.0.4.0</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>

</project>

2. Create a basic public module (common)

Add dependencies in pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>BK-SpringCloud</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>alibaba-common</artifactId>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.2.15</version>
        </dependency>
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>3.0.0</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
        </dependency>
    </dependencies>
</project>

3. Create a user module (user-module)

step:

1 Create module import dependencies

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>BK-SpringCloud</artifactId>
        <groupId>org.example</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>alibaba-user</artifactId>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.example</groupId>
            <artifactId>alibaba-common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
    </dependencies>

</project>

2 Create SpringBoot main class

@SpringBootApplication
public class UserApplication {
  public static void main(String[] args) {
      SpringApplication.run(UserApplication.class,args);
  }
}

3 Add the yml configuration file

spring:
  application:
    name: user-server
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/nacos?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: 123456

4. Register the user module to nacos as a microservice

Next, start to modify the code of the alibaba-user module and register it with the nacos service

1) Add nacos dependency in pom.xml

<!--nacos客户端-->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2) Add the @EnableDiscoveryClient annotation to the main class

@SpringBootApplication
@EnableDiscoveryClient
public class UserApplication {
  public static void main(String[] args) {
      SpringApplication.run(UserApplication.class,args);
  }
}

3) Add the address of nacos service in application.yml

spring:
  application:
    name: user-server
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/user?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: 123456
  cloud:
    nacos:
      discovery:
        username: nacos
        password: nacos
        server-addr: 192.168.177.129:8848

4) Start the service and observe whether there are registered user microservices in the nacos control panel

4. Realize service call based on Feign

1) What is Feign

Feign is a declarative web service client that makes calls between microservices easier. Feign encapsulates Ribbon and Hystrix internally, and has load balancing and service fault tolerance capabilities.

The main function of Feign is to call other microservices by creating interfaces and adding annotations. It uses the interface to call other microservices, and combines Ribbon and Hystrix to achieve load balancing and service fault tolerance, which greatly simplifies the complexity of remote calls.

The main benefits of using Feign are as follows:

  1. Hiding the complexity of service calls: Feign calls services in a declarative way by defining interfaces, which simplifies the process for developers to call services directly.

  2. With load balancing capability: Feign has a built-in Ribbon load balancing client, which can realize load balancing of service calls.

  3. Service fault-tolerant capability: Feign has a built-in Hystrix service fault-tolerant component, which can realize service fault-tolerant functions such as service degradation and service fusing during service invocation.

  4. Support multiple service calling methods: Feign has built-in HTTP, TCP and other service calling methods, which are highly scalable.

  5. With a request retry mechanism: within the specified retry time, retry calls to services to improve the stability of service calls.

  6. Support GZIP compression: When sending GET requests, it supports GZIP compression for requests and responses to improve network transmission efficiency.

  7. Support for logging: Feign supports using SLF4J for logging, which is convenient for debugging and tracking of service calls.

Main usage steps:

  1. Add Feign dependency

  2. Create a service interface and add the @FeignClient annotation

  3. Call the service directly using the interface

  4. Configure timeouts, retries, etc. for service calls

  5. Define the service downgrade Fallback class, and return the default downgrade value when the service is unavailable

2) What does load balancing mean?

Load Balancing is a computer technology that maximizes the utilization efficiency of computing resources by distributing workload to multiple computing resources.

In a distributed system, the deployment of multiple service instances can achieve high availability and scalability of services. Through the load balancer, the client's request can be distributed among the service instances to realize the balanced distribution and management of the load.

Test: Start two Users, (change the port, change the content in the controller method), and access the incompatible content through the interface.

3) Use of Feign (create order module order)

1. Create an order module and introduce dependencies

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>SpringCloudAlibaba</artifactId>
        <groupId>com.buba</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>order</artifactId>

    <properties>
        <maven.compiler.source>11</maven.compiler.source>
        <maven.compiler.target>11</maven.compiler.target>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.buba</groupId>
            <artifactId>common</artifactId>
            <version>1.0-SNAPSHOT</version>
        </dependency>
        <!--nacos客户端-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
    </dependencies>
</project>

2. Add annotations to the startup class

@SpringBootApplication
@EnableDiscoveryClient
public class OrderApp {
    public static void main( String[] args ) {
        SpringApplication.run(OrderApp.class, args);
    }
}

3.yml file configuration

spring:
  application:
    name: order-server
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/nacos?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
      driver-class-name: com.mysql.cj.jdbc.Driver
      username: root
      password: 123456
  cloud:
    nacos:
      discovery:
        username: nacos
        password: nacos
        server-addr: 192.168.177.129:8848
server:
  port: ${random.int[0000,9999]}

4. Write an OrderController

@RestController
@RequestMapping("order")
public class OrderController {
    @RequestMapping("/get1")
    public Integer get1(){
        return 111;
    }
}

5. Add Fegin dependencies to the pom file of the user module

<dependencies>
    <dependency>
        <groupId>com.buba</groupId>
        <artifactId>common</artifactId>
        <version>1.0-SNAPSHOT</version>
    </dependency>
    <!--nacos客户端-->
    <dependency>
        <groupId>com.alibaba.cloud</groupId>
        <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-loadbalancer</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-openfeign</artifactId>
    </dependency>
</dependencies>

6. Add Fegin annotations to the user module on the startup class

@SpringBootApplication
@EnableDiscoveryClient
@EnableFeignClients//开启Fegin
public class UserApp {
    public static void main( String[] args ) {
        SpringApplication.run(UserApp.class, args);
    }
}

7. Create a feign interface for the user module, and use Fegin to implement microservice calls

@FeignClient(value = "order-server",path = "/order")//声明调用的提供者的name
public interface OrderFeign {
    // 指定调用提供者的哪个方法
    // @FeignClient+@GetMapping 就是一个完整的请求路径 http://serviceproduct/product/{pid}
    @GetMapping("/get1")
    Integer get1();
}

8. The controller calls and starts verification (the user service calls the order service)

@RestController
@RequestMapping("user")
public class UserController {
    @Resource
    private OrderFeign orderFeign;
    @RequestMapping("/get1")
    public Integer get1(){
        return orderFeign.get1();
    }
}

Five, Nacos domain model division

1. Namespace division

NameSpace (the default NameSpace is "public" and NameSpace can perform resource isolation. For example, the services under the NameSpace in our dev environment cannot call the microservices under the NameSpace of prod)

(1) Create a namespace

dev development environment

test test environment

pre production environment

(2) Configure the microservice namespace

spring:
  application:
    name: order-server
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.177.129:8848
        namespace: 9f5444ba-f5a0-4745-99aa-e15e8cca08cd

2. Group division

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 192.168.177.129:8848
        group: group2

6. Log Configuration

1. Local log configuration

method one:

(1) Log level setting

Note: There is no @Configuration annotation on this class

public class FeginConfig {
    @Bean
    public Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
}

(2) Configure target feign

@FeignClient(value = "repository-server",path = "/repositoty",configuration = FeginConfig.class)
public interface RepositotyFeign {
    @GetMapping("/getNum/{goodId}")
    Integer getNum(@PathVariable("goodId") Integer goodId);
}

way two

feign:
  client:
    config:
      repository-server:
        loggerLevel: debug

2. Global log configuration

(1) Add configuration file

Note: There are @Configuration annotations on this class

@Configuration
public class FeginConfig {
    @Bean
    public Logger.Level feignLoggerLevel(){
        return Logger.Level.FULL;
    }
}

(2) Lower the log level of springboot

logging:
  level:
    com.buba.feign: debug

Seven, Nacos unified configuration management

1. Why do we need a configuration center

The configuration center is different from the traditional way of distributing configuration information to every corner of the system, and centralizes and unifies the management of configuration files in the system, without the need to manage individual servers one by one. What are the benefits of doing so?

(1) Through the configuration center, the configuration can be standardized and the format can be unified

(2) When the configuration information changes, the modification takes effect in real time, and the corresponding changes can be automatically sensed without restarting the server, and the new changes are uniformly sent to the corresponding programs to quickly respond to changes. For example, a certain function is only for users in a certain area, and a certain function is only available during the big promotion period. After using the configuration center, only relevant personnel need to dynamically adjust the parameters in the configuration center, and it can be basically real-time or quasi-real-time. Adjust the corresponding business.

(3) Problems can also be traced through the audit function

2. Commonly used configuration centers

There are three mainstream solutions for the configuration center in microservices: Nacos, Apollo, Config+Bus, but here we mainly introduce the usage of Nacos as the configuration center.

Several concepts of Nacos

Namespace (Namespace) Namespace can be used to isolate the configuration of different environments. Generally, an environment is divided into a namespace configuration group (Group) Configuration group is used to classify different services into the same group. Generally, the configuration of a project is divided into a set of configuration sets (Data ID) In ​​the system, a configuration file is usually a configuration set. The configuration of a general microservice is a configuration set

3. Use of Nacos Configuration Center

Using nacos as the configuration center is actually treating nacos as a server and each microservice as a client. We store the configuration files of each microservice on nacos, and then each microservice pulls the configuration from nacos. Can.

(1) properties format

1. Import dependencies

<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>

2. Create a new configuration in the configuration center + number

3. Modify the configuration file name

Modify application.yml in the project to bootstrap.yml

 

4. Add the configuration of the nacos config service address in the microservice

5. Test to obtain the configuration of the registration center

@RestController
@RequestMapping("user")
public class UserController {
    @Value("${author}")
    private String author;
    @RequestMapping("/get1")
    public String get1(){
        return author;
    }
}

6. You can move the configuration of the database to the configuration center, and modify the configuration of the data source in the project

spring.datasource.druid.url=jdbc:mysql://localhost:3306/nacos?useSSL=false&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
spring.datasource.druid.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.druid.username=root
spring.datasource.druid.password=123456

Of course, if the configuration center is configured, it will be deleted in the yml file.

7. New configuration class

@Configuration
public class DataSourceConfig {
    @Value("${spring.datasource.druid.username}")
    private String username;
    @Value("${spring.datasource.druid.password}")
    private String password;
    @Value("${spring.datasource.druid.url}")
    private String url;
    @Value("${spring.datasource.druid.driver-class-name}")
    private String driverClassName;
    @Bean
    public DataSource dataSource(){
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setUrl(url);
        druidDataSource.setUsername(username);
        druidDataSource.setPassword(password);
        druidDataSource.setDriverClassName(driverClassName);
        return druidDataSource;
    }
}

You can break the point to test whether to get the dataSource

(2) yaml format

1. Create a new configuration in the configuration center

2. Modify the project configuration file name to bootstrap.yml and modify the configuration file configuration

(3) profiles.active—granularity configuration

1. Create a configuration in the configuration center

Data ID: service name-profileN name. suffix name (order-server-mysql.yaml)

2. Engineering module configuration

spring:
  application:
    name: user-server
  cloud:
    nacos:
      discovery: # 服务注册与发现
        username: nacos
        password: nacos
        server-addr: 192.168.177.129:8848
      config: # 配置中心
        username: nacos
        password: nacos
        server-addr: 192.168.177.129:8848
        file-extension: yaml
        group: group1 # 分组
        namespace: 9f5444ba-f5a0-4745-99aa-e15e8cca08cd # 命名空间
  profiles:
    active: mysql # 粒度配置
server:
  port: ${random.int[1000,9999]}
feign:
  client:
    config:
      default: # 全局,如果单个服务,写服务名称即可(user-server)
        #建立连接所用的时间,适用于网络状况正常的情况下,两端连接所需要的时间
        connect-timeout: 5000
        #指建立连接后从服务端读取到可用资源所用的时间
        read-timeout: 5000

(4) Data Id configuration of custom extension (shared configuration)

When the number of our microservices increases, there will inevitably be the same configuration. At this time, we can extract the same configuration as a common configuration in the project, such as data source information in the cluster, log configuration information, and nacos This writing method of multiple configuration sets in one configuration center is supported.

Case presentation:

1. Create two new files in nacos with Data IDs redis.yaml and mysql.yaml.

2. Add some configuration content to the configuration file

redis.yaml

 mysql.yaml

 ** 3. Add the following nacos configuration to the Springboot project: **

The entire yml configuration:

spring:
  application:
    name: user-server
  cloud:
    nacos:
      discovery: # 服务注册与发现
        username: nacos
        password: nacos
        server-addr: 192.168.177.129:8848
      config: # 配置中心
        username: nacos
        password: nacos
        server-addr: 192.168.177.129:8848
        file-extension: yaml
        extension-configs[0]: # 多个 Data Id的配置
          data-id: redis.yaml
          group: DEFAULT_GROUP # 默认为DEFAULT_GROUP
          refresh: true # 是否动态刷新,默认为false
        extension-configs[1]:
          data-id: mysql.yaml
          group: DEFAULT_GROUP # 默认为DEFAULT_GROUP
          refresh: true # 是否动态刷新,默认为false
#        group: group1 # 分组
#        namespace: 9f5444ba-f5a0-4745-99aa-e15e8cca08cd # 命名空间
  profiles:
    active: mysql # 粒度配置

Tip 1: When multiple Data Ids are configured at the same time, their priority relationship is spring.cloud.nacos.config.ext-config[n].data-id where the larger the value of n, the higher the priority.

Tip 2: The value of spring.cloud.nacos.config.ext-config[n].data-id must have a file extension. The file extension can support both properties and yaml/yml. At this time, the configuration of spring.cloud.nacos.config.file-extension has no effect on the Data Id file extension of the custom extension configuration.

(5) Priority

Nacos Config currently provides four configuration capabilities to pull related configurations from Nacos

A: Support multiple shared Data Id configurations through spring.cloud.nacos.config.shared-configs[0].dataids

B: Support the configuration of multiple extended Data Ids through spring.cloud.nacos.config.extension-configs[0].data-id

C: application name user-server.yaml application configuration

D: application name + Profile user-server-dev.yaml granular configuration

# Priority: granular configuration > application configuration > extension-configs[n] configuration (the larger the n, the higher the priority) > shared-configs[n] configuration (the larger the n, the higher the priority) D > C > B > A

(6) Dynamic configuration refresh

Annotation method (recommended)

@RestController
@RefreshScope // 在需要动态读取配置的类上添加此注解就可以(动态配置刷新)
@RequestMapping("/nacos-config")
public class NacosConfigController {
    @Value("${config.appName}")
    private String appName;
    //2 注解方式
    @GetMapping("/test")
    public String nacosConfingTest() {
        return appName;
    }
}

Guess you like

Origin blog.csdn.net/Microhoo_/article/details/130999757