SpringBoot integrates Nacos to dynamically read configuration files and service discovery

1. Integrate Nacos

1) Configure the pom file

        <!--nacos-config 版本号和springboot对应-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>
        <!--nacos-discovery 版本号和springboot对应-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
            <version>2.1.0.RELEASE</version>
        </dependency>
        <!--nacos-web 需要此依赖,不然服务列表里面服务注册不成功-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

2) Modify the configuration file

nacos reads the bootstrap.xml file by default

spring:
  application:
    name: test-server-tcp
  profiles:
    active: dev
  cloud:
    nacos:
      discovery:
        namespace: ${spring.profiles.active}
        server-addr: 192.168.0.1:8848
      config:
        namespace: ${spring.profiles.active}
        server-addr: 192.168.0.1:8848
        ext-config:
          - data-id: test-server-tcp.yml
            group: ${spring.profiles.active}
            refresh: true

3) Configure on the nacos management interface

    1. Create a new namespace

   2. Create a new configuration file

 

 

Second, the configuration of dynamic reading changes

Add the annotation @RefreshScope to the class that needs to reference the configuration

Sample code:

@RefreshScope
@RestController
@RequestMapping(value="/config")
public class NacosConfig {

    @Value(value = "${nacos.test-name}")
    private String testName;
    @Value(value = "${nacos.test-port}")
    private String testPort;

    @GetMapping(value = "/get")
    public String getConfig(){
        return "name: "+ testName +";" + "port: "+ testPort +";";
    }

}

You can verify whether the dynamic configuration takes effect through the http url

3. After the dynamic configuration changes, the timing task does not execute

Problem: There are scheduled tasks in the program. If the configuration read by the scheduled tasks changes dynamically, the scheduled tasks will not be executed.

Reason: The lazy loading method for the scheduled task to read the configuration file

Solution: Implement an interface in the class where the scheduled task is located

ApplicationListener<RefreshScopeRefreshedEvent> and implement its method, just empty method

 

PS: All classes that use timed tasks in the program must implement the above interface.

Guess you like

Origin blog.csdn.net/mawei7510/article/details/126585547