search
HomeJavajavaTutorialHow SpringBoot integrates Nacos to implement registration center and configuration center

SpringBoot integrates Nacos

Introducing Maven dependencies

First of all, we still have to introduce Maven dependencies

<!--注册中心的依赖-->
<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-discovery-spring-boot-starter</artifactId>
    <version>0.2.3</version>
</dependency>
<!-- 配置中心的依赖 -->
<dependency>
    <groupId>com.alibaba.boot</groupId>
    <artifactId>nacos-config-spring-boot-starter</artifactId>
    <version>0.2.3</version>
</dependency>

There is one thing to note here: the registration center and the configuration center The dependent version should be selected according to the SpringBoot version. Version 0.2.x.RELEASE corresponds to Spring Boot 2.x version, and version 0.1.x.RELEASE corresponds to Spring Boot 1.x version. The SpringBoot version I am using here is 2.2.4.RELEASE, so I chose the 0.2.3 version of the registration center and configuration center.

Add configuration

The next step is to add relevant configuration in application.yml????

server:
port: 80
servlet:
context-path: /
spring:
application:
name: NacosDemo
nacos:
config:
server-addr: 127.0.0.1:8848
discovery:
server-addr: 127.0.0.1:8848

Sample code

First we need to add two Nacos annotations to the project startup class? ???

import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@EnableNacosDiscovery //注册中心注解 使用nacos
@NacosPropertySource(dataId = "product_config",autoRefreshed = true) //配置中心注解:autoRefreshed 代表自动刷新注解
public class NacosdemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(NacosdemoApplication.class, args);
    }
}

Next we need to add another Nacos configuration file???

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import javax.annotation.PostConstruct;
/**
 * @program: NacosDemo
 * @description: NacosConfig
 **/
@Configuration
public class NacosConfig {
    @Value("${server.port}")
    private int serverPort;
    @Value("${spring.application.name}")
    private String applicationName;
    @NacosInjected
    private NamingService namingService;
    @PostConstruct
    public void registerInstance() throws NacosException {
        namingService.registerInstance(applicationName, "127.0.0.1", serverPort);
    }
}

Finally we write a Controller class that simulates obtaining configuration parameters????

import com.alibaba.nacos.api.config.annotation.NacosValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * ConfigController 配置控制器
 * @description: ConfigController
 **/
@RestController
@RequestMapping("/test")
public class ConfigController {
    @NacosValue(value = "${productName}",autoRefreshed = true)
    private  String productName;
    @RequestMapping("/productName")
    public String getProductName(){
        return productName;
    }
}

The code has been prepared here. Since we have a Controller that obtains configuration parameters, we must define a configuration parameter to be obtained. We start Nacos, log in to its backend page, find the configuration list in the configuration management on the left, and create a new configuration under the configuration list.

How SpringBoot integrates Nacos to implement registration center and configuration center

How SpringBoot integrates Nacos to implement registration center and configuration center

##❗❗❗Be sure to note ❗❗❗ here: the Data ID value filled in when adding parameters on the Nacos management page It must be consistent with the dataId value in the @NacosPropertySource annotation on the startup class; and when defining the configuration content, the configuration name must be consistent with the name defined in the Controller. No matter which of the two names does not match, an error that the configuration cannot be found will be reported when starting the project.

At this point, the code and configuration have been prepared. Let's start the project to see the specific effects... After the project is started, we find the service list under service management on the left side of the Nacos management page and open the service You can see in the list that our project was successfully registered into Nacos.

How SpringBoot integrates Nacos to implement registration center and configuration center

Next, we visit http://localhost/test/productName in the browser, and we can see that our new configuration has been successfully taken out. If the configuration needs to be changed at this time, we only need to modify the corresponding configuration in the background of Nacos, and then refresh the page to see that the configuration has been dynamically updated

How SpringBoot integrates Nacos to implement registration center and configuration center

How SpringBoot integrates Nacos to implement registration center and configuration center

The above is the detailed content of How SpringBoot integrates Nacos to implement registration center and configuration center. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:亿速云. If there is any infringement, please contact admin@php.cn delete
How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?How do I use Maven or Gradle for advanced Java project management, build automation, and dependency resolution?Mar 17, 2025 pm 05:46 PM

The article discusses using Maven and Gradle for Java project management, build automation, and dependency resolution, comparing their approaches and optimization strategies.

How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?How do I create and use custom Java libraries (JAR files) with proper versioning and dependency management?Mar 17, 2025 pm 05:45 PM

The article discusses creating and using custom Java libraries (JAR files) with proper versioning and dependency management, using tools like Maven and Gradle.

How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?How do I implement multi-level caching in Java applications using libraries like Caffeine or Guava Cache?Mar 17, 2025 pm 05:44 PM

The article discusses implementing multi-level caching in Java using Caffeine and Guava Cache to enhance application performance. It covers setup, integration, and performance benefits, along with configuration and eviction policy management best pra

How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?How can I use JPA (Java Persistence API) for object-relational mapping with advanced features like caching and lazy loading?Mar 17, 2025 pm 05:43 PM

The article discusses using JPA for object-relational mapping with advanced features like caching and lazy loading. It covers setup, entity mapping, and best practices for optimizing performance while highlighting potential pitfalls.[159 characters]

How does Java's classloading mechanism work, including different classloaders and their delegation models?How does Java's classloading mechanism work, including different classloaders and their delegation models?Mar 17, 2025 pm 05:35 PM

Java's classloading involves loading, linking, and initializing classes using a hierarchical system with Bootstrap, Extension, and Application classloaders. The parent delegation model ensures core classes are loaded first, affecting custom class loa

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment