preface

As Eureka stops updating, two components of SpringCloud Eureka and SpringCloud Config are required if both registry and configuration center are implemented. SpringCloud Bus message Bus sends message notification (Kafka, RabbitMQ, etc.) to each service to dynamically update the configuration. If not, you have to restart each microservice instance. Nacos can register and configure the center, as well as dynamically update the configuration.

Versions.

Nacos Server: 1.3.2

SpringBoot: 2.3.0. RELEASE

SpringCloud: Hoxton.SR5

SpringCloud Alibaba: 2.2.1. RELEASE

The project of actual combat

1. Youlai-auth adds nacos-config dependency

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

2. The project configuration file bootstrap.yml specifies the nacOS configuration file name

spring: application: name: youlai-auth cloud: nacos: discovery: server-addr: http://localhost:8848 config: Prefix: ${spring.application. Name} # rsa: publicKey: 123456Copy the code

Note that bootstrap.yml is used instead of application.yml to avoid applicaton.yml being loaded after nacOS configuration and overwritten

SpringBoot reads configuration files in the following order: Yml > Bootstrap. yaml> Bootstrap. properties> NacOS Configuration > Application. yml> Application. yaml> Application. properties

3. Add interface to read configuration information and add @refreshScope annotation to dynamically refresh configuration

@RefreshScope @RestController @RequestMapping("/oauth") public class AuthController { @Value("${rsa.publicKey}") public String publicKey; @GetMapping("/publicKey") public Result getPublicKey(){ return Result.success(this.publicKey); }}Copy the code

4. Open the NacOS administrative console to add the configuration

DATA-ID :  ${prefix}-${spring.profiles.active}.${file-extension} 
Copy the code

A). The default spring prefix. Application. The value of the name, but can be by spring configuration items. The cloud. Nacos. Config. The prefix to configure b) file - the extension default properties, For example, I used here is yaml, then change the spring. The cloud. Nacos. Config. The file - the extension = yaml c). The default DEFAULT_GROUP Group, But can be by spring configuration items. Cloud. Nacos. Config. Group to configurationCopy the code

5. Read the configuration information for the first time after the service is started

6. Request the interface to obtain the configuration information again

You can see that the configuration information obtained through the interface for the second time is changed, and the configuration information is dynamically refreshed

conclusion

So far youlai – auth module integration nacos configuration center finished, if compared with eureka integration SpringCloud Config is convenient, complete code address at https://github.com/hxrui/youlai/tree/nacos. To be continued…