Using Nacos with Spring Cloud Alibaba for Service Registration, Discovery, and Configuration
The guide shows how to download and start Nacos, configure Spring Cloud Alibaba projects for service registration and discovery, create provider and consumer services with load‑balanced RestTemplate or OpenFeign calls, and use Nacos as a dynamic configuration center with refresh‑scope support.
Service Registry and Configuration Center - Nacos
Nacos is a dynamic service discovery, configuration management, and service management platform that simplifies building cloud‑native applications. In Spring Cloud Alibaba, Nacos is used for service registration, discovery, and configuration.
Downloading and Starting Nacos
Download Nacos from the official site (https://nacos.io/zh-cn/), extract the archive, and run startup.cmd located in the bin directory. After startup, access http://localhost:8848/nacos with the default username and password nacos to open the management console.
Service Registration
Create a parent Maven project springcloud-alibaba with the following pom.xml:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.wwj</groupId>
<artifactId>springcloud-alibaba</artifactId>
<version>0.0.1-SNAPSHOT</version>
<modules>
<module>cloud-provider-payment8001</module>
</modules>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.3.7.RELEASE</version>
</parent>
</project>Then create the provider module cloud-provider-payment8001 with the following pom.xml (only the relevant part is shown):
<project ...>
<artifactId>cloud-provider-payment8001</artifactId>
<parent>
<groupId>com.wwj</groupId>
<artifactId>springcloud-alibaba</artifactId>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-nacos-discovery</artifactId>
</dependency>
</dependencies>
...
</project>Add the Nacos discovery configuration to application.yml:
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
service: cloud-provier-payment
server:
port: 8001Enable discovery in the main class:
@EnableDiscoveryClient
@SpringBootApplication
public class CloudProviderPayment8001Application {
public static void main(String[] args) {
SpringApplication.run(CloudProviderPayment8001Application.class, args);
}
}Implement a simple controller:
@RestController
public class PaymentController {
@Value("${server.port}")
private String port;
@GetMapping("/payment/nacos/{id}")
public String getPayment(@PathVariable("id") Integer id) {
return "nacos服务注册,端口号:" + port + "\t" + "id:" + id;
}
}Start the service and verify its registration in the Nacos console. Create a second instance (port 8002) by copying the code and changing the port.
Service Consumption
For a consumer service, add the Nacos dependency and the same discovery configuration (different service name, e.g., cloud-consumer-order).
Register a RestTemplate with load balancing:
@Configuration
public class MyApplicationConfig {
@Bean
@LoadBalanced
public RestTemplate restTemplate() {
return new RestTemplate();
}
}Use the provider URL to call the payment service:
@RestController
public class OrderController {
public static final String SERVER_URL = "http://cloud-provier-payment";
@Autowired
private RestTemplate restTemplate;
@GetMapping("/consumer/payment/nacos/{id}")
public String paymentInfo(@PathVariable("id") Integer id) {
String reqUrl = SERVER_URL + "/payment/nacos/" + id;
return restTemplate.getForObject(reqUrl, String.class);
}
}Test the consumer at http://localhost:9001/consumer/payment/nacos/1; Nacos will perform round‑robin load balancing between the two provider instances.
OpenFeign Integration
Add the OpenFeign starter dependency, then define a Feign client interface:
@FeignClient("cloud-provier-payment")
public interface PaymentService {
@GetMapping("/payment/nacos/{id}")
String getPayment(@PathVariable("id") Integer id);
}Enable Feign in the consumer application:
@EnableDiscoveryClient
@EnableFeignClients("com.wwj.cloudcomsumer.order.service")
@SpringBootApplication
public class CloudComsumerOrder9001Application {
public static void main(String[] args) {
SpringApplication.run(CloudComsumerOrder9001Application.class, args);
}
}Inject the client and call the remote method:
@RestController
public class OrderController {
@Autowired
private PaymentService paymentService;
@GetMapping("/consumer/payment/nacos/{id}")
public String paymentInfo(@PathVariable("id") Integer id) {
return paymentService.getPayment(id);
}
}Configuration Management with Nacos
To use Nacos as a configuration center, add the spring-cloud-alibaba-nacos-config dependency and create a bootstrap.yml with higher priority than local files:
spring:
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
service: cloud-config2001
config:
server-addr: 127.0.0.1:8848
file-extension: yaml
prefix: cloud-config2001
server:
port: 2001Define a controller that reads a dynamic property:
@RestController
@RefreshScope
public class ConfigController {
@Value("${config.msg}")
private String msg;
@GetMapping("/get/msg")
public String getMsg() {
return msg;
}
}In Nacos, create a configuration entry with Data ID cloud-config2001.yaml (or cloud-config2001-dev.yaml when a profile is active) and set the desired key config.msg. After publishing, the value is instantly reflected in the running application without a restart.
Nacos also supports groups and namespaces for environment isolation. Example group configuration:
spring:
cloud:
nacos:
config:
group: DEV_GROUP
namespace: d7e672f8-441e-449b-a143-1eca69122daaBy switching groups, namespaces, or active profiles, you can manage separate configurations for development, testing, and production environments.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Java Tech Enthusiast
Sharing computer programming language knowledge, focusing on Java fundamentals, data structures, related tools, Spring Cloud, IntelliJ IDEA... Book giveaways, red‑packet rewards and other perks await!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
