1
头图

If you want to know more Nacos tutorials, welcome to star "On Nacos" open source project. Based on the introduction, principle, source code, and practical introduction of Nacos 2.x, it helps developers to quickly get started with Nacos.

This article introduces how to use Nacos in Spring Boot projects. Nacos is mainly divided into two parts, configuration center and service registration and discovery. To use Nacos in a Spring Boot project, you must first ensure that a Nacos service is started. For details, you can refer to [Getting Started with Nacos Quickly] to build a stand-alone Nacos service.

The source code of the Nacos package starter can refer to the [nacos-spring-boot-project] project, and interested friends can view the source code.

For the detailed code example of this article, click [nacos-spring-boot] to view

Configuration Center

Create configuration

Open the console http://127.0.0.1:8848/nacos , enter the configuration management-configuration list, click the + sign to create a new configuration, and create a data source configuration example here: nacos-datasource.yaml

 spring:
    datasource:
     name: datasource
     url: jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=UTF-8&characterSetResults=UTF-8&zeroDateTimeBehavior=convertToNull&useDynamicCharsetInfo=false&useSSL=false
     username: root
     password: root
     driverClassName: com.mysql.jdbc.Driver

https://tva1.sinaimg.cn/large/e6c9d24ely1h3kow3r2tkj21680u0wgu.jpg

add dependencies

After the configuration is created, you can view it in the console configuration management - configuration list. Next, I will demonstrate how to get the configuration information in Nacos in the Spring Boot project.

The following dependencies need to be added to the project:

 <!--配置中心 starter-->
<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-config-spring-boot-starter</artifactId>
    <version>${latest.version}</version>
</dependency>

Then add some configuration of nacos to the application.properties file in the project:

 nacos.config.server-addr=127.0.0.1:8848
nacos.config.group=DEFAULT_GROUP
nacos.config.namespace=
nacos.config.username=nacos
nacos.config.password=nacos

get configuration

Bind to class get

The configuration in nacos-datasource.yaml can be bound to the NacosDataSourceConfig class through the @NacosConfigurationProperties annotation. This allows NacosDataSourceConfig to be injected where it is to be used via @Resource or @Autowired .

 @NacosConfigurationProperties(prefix = "spring.datasource", dataId = "nacos-datasource.yaml", autoRefreshed = true)
@Component
@Data
public class NacosDataSourceConfig {
    
    private String name;
    
    private String url;
    
    private String username;
    
    private String password;
    
    private String driverClassName;
}

Create a Controller and write an interface to get configuration information:

 /**
 * @author lixiaoshuang
 */
@RestController
@RequestMapping(path = "springboot/nacos/config")
public class NacosConfigController {
    
    @Resource
    private NacosDataSourceConfig nacosDataSourceConfig;
    
    @GetMapping(path = "get")
    private Map<String, String> getNacosDataSource() {
        Map<String, String> result = new HashMap<>();
        result.put("name", nacosDataSourceConfig.getName());
        result.put("url", nacosDataSourceConfig.getUrl());
        result.put("username", nacosDataSourceConfig.getUsername());
        result.put("password", nacosDataSourceConfig.getPassword());
        result.put("driverClassName", nacosDataSourceConfig.getDriverClassName());
        return result;
    }
}

Then start the service and visit http://localhost:8080/springboot/nacos/config/binding/class/get to get the corresponding configuration information:

https://tva1.sinaimg.cn/large/e6c9d24ely1h3koknj05gj21zm0hujv1.jpg

@NacosValue+@NacosPropertySource annotation acquisition

Create a configuration in properties format and use @NacosValue + @NacosPropertySource annotation to obtain configuration information under the demo. Or open the configuration management-configuration list and click the + sign to create a new configuration: nacos-datasource.properties

 name=datasource
url=jdbc:mysql://127.0.0.1:3306/nacos?characterEncoding=UTF-8&characterSetResults=UTF-8&zeroDateTimeBehavior=convertToNull&useDynamicCharsetInfo=false&useSSL=false
username=root
password=root
driverClassName=com.mysql.jdbc.Driver

https://tva1.sinaimg.cn/large/e6c9d24ely1h3kounqdmsj216m0u0wgp.jpg

Obtain the configuration of the specified dataId through the @NacosValue + @NacosPropertySource annotation

 /**
 * @author lixiaoshuang
 */
@RestController
@RequestMapping(path = "springboot/nacos/config")
@NacosPropertySource(dataId = "nacos-datasource.properties", autoRefreshed = true, before = SYSTEM_PROPERTIES_PROPERTY_SOURCE_NAME, after = SYSTEM_ENVIRONMENT_PROPERTY_SOURCE_NAME)
public class AnnotationGetController {
    
    @NacosValue(value = "${name:}", autoRefreshed = true)
    private String name;
    
    @NacosValue(value = "${url:}", autoRefreshed = true)
    private String url;
    
    @NacosValue(value = "${username:}", autoRefreshed = true)
    private String username;
    
    @NacosValue(value = "${password:}", autoRefreshed = true)
    private String password;
    
    @NacosValue(value = "${driverClassName:}", autoRefreshed = true)
    private String driverClassName;
    
    @GetMapping(path = "annotation/get")
    private Map<String, String> getNacosDataSource2() {
        Map<String, String> result = new HashMap<>();
        result.put("name", name);
        result.put("url", url);
        result.put("username", username);
        result.put("password", password);
        result.put("driverClassName", driverClassName);
        return result;
    }
}

Visit http://localhost:8080/springboot/nacos/config/annotation/get to get the configuration information of nacos-datasource.properties :

https://tva1.sinaimg.cn/large/e6c9d24ely1h3koyy2gw9j21z00gu77r.jpg

Configure monitoring

Spring Boot can also be used to monitor configuration changes through @NacosConfigListener annotations, and create a hello-nacos.text configuration:

https://tva1.sinaimg.cn/large/e6c9d24ely1h3kpuvham9j219k0u0dhh.jpg

 /**
 * @author lixiaoshuang
 */
@Component
public class ConfigListener {
    
    /**
     * 基于注解监听配置
     *
     * @param newContent
     * @throws Exception
     */
    @NacosConfigListener(dataId = "hello-nacos.text", timeout = 500)
    public void onChange(String newContent) {
        System.out.println("配置变更为 : \n" + newContent);
    }
    
}

Then modify the configuration content of hello-nacos.text to "hello nacos config", and the onChange() method will be called back in the code

https://tva1.sinaimg.cn/large/e6c9d24ely1h3kpz4de68j210q0gomy4.jpg

Service Registration & Discovery

service registration

Add the following dependencies to the project:

 <!--注册中心 starter-->
<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-discovery-spring-boot-starter</artifactId>
    <version>${latest.version}</version>
</dependency>

Then add some configuration of nacos to the application.properties file in the project:

 nacos.discovery.server-addr=127.0.0.1:8848
nacos.discovery.auto-register=true
nacos.discovery.register.clusterName=SPRINGBOOT
nacos.discovery.username=nacos
nacos.discovery.password=nacos

When the configuration is added and automatic registration is turned on, and the following log is seen after starting the service, it means that the service registration is successful.

 Finished auto register service : SPRING_BOOT_SERVICE, ip : 192.168.1.8, port : 8222

https://tva1.sinaimg.cn/large/e6c9d24ely1h3kx59muggj22l30u04dq.jpg

service discovery

You can use the NacosNamingService provided by Nacos to get an instance of the service. You can inject NacosNamingService into the place where it needs to be used through the @NacosInjected annotation.

 /**
 * @author lixiaoshuang
 */
@RestController
@RequestMapping(path = "springboot/nacos/discovery")
public class NacosDiscoveryController {
    
    @NacosInjected
    private NacosNamingService nacosNamingService;
    
    @RequestMapping(path = "get")
    public List<Instance> getInfo(@RequestParam("serviceName") String serviceName) throws NacosException {
        return nacosNamingService.getAllInstances(serviceName);
    }
}

Get the instance information of the SPRING_BOOT_SERVICE service by calling http://localhost:8222/springboot/nacos/discovery/get?serviceName=SPRING_BOOT_SERVICE .

https://tva1.sinaimg.cn/large/e6c9d24ely1h3kxi7wg4nj21rq0r2aed.jpg


晓双
76 声望15 粉丝

🏅Alibaba Nacos & Apache EventMesh Committer