Spring Cloud integrates nacos

Spring Cloud is a distributed microservice framework that provides a series of tools and components for building distributed systems. Nacos is a registration center and configuration center open sourced by Alibaba. It also provides functions such as call chain tracking, dynamic configuration, service discovery, and traffic management.

When using Spring Cloud to build microservice applications, we need to integrate Nacos. The following are the integration steps:

  1. add dependencies

Add the following dependencies to the pom.xml file:

<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
   <groupId>org.springframework.cloud</groupId>
   <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
  1. Configure Nacos

Add the following configuration in the configuration file application.yml:

spring:
  application:
    name: service-name   # 服务名称
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848   # Nacos 地址
      config:
        server-addr: 127.0.0.1:8848   # Nacos 地址
        namespace: dev  # 命名空间,默认为 public
  1. registration service

Use the @EnableDiscoveryClient annotation to enable service registration and discovery:

@SpringBootApplication
@EnableDiscoveryClient
public class UserServiceApplication {
    
    

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

}
  1. get configuration

Use @NacosValue annotation to get configuration:

@Service
public class UserService {
    
    

    @NacosValue(value = "${user.name}", autoRefreshed = true)
    private String name;

    public String getName() {
    
    
        return name;
    }

}

The above are the steps for Spring Cloud to integrate Nacos. Through these steps, we can easily realize the registration, discovery and configuration management of microservices.

Guess you like

Origin blog.csdn.net/m0_37924754/article/details/131280814