概述和版本说明
xml
<spring.boot.version>3.2.0</spring.boot.version>
<spring.cloud.version>2023.0.0</spring.cloud.version>
<spring.cloud.alibaba.version>2022.0.0.0</spring.cloud.alibaba.version>
注册中心,配置中心及动态刷新广播通知
Spring Cloud Alibaba 参考文档 (spring-cloud-alibaba-group.github.io)
下载安装使用
Release 2.2.3 (May 25th, 2023) · alibaba/nacos (github.com)
shell
D:\tool\nacos-server-2.2.3\nacos\bin>startup.cmd -m standalone
服务注册中心
provider
xml
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
yaml
server:
port: 9001
spring:
application:
name: nacos-pay-provider
cloud:
nacos:
discovery:
server-addr: localhost:8848 # nacos地址
java
@SpringBootApplication
@EnableDiscoveryClient
public class Main9001 {
public static void main(String[] args) {
SpringApplication.run(Main9001.class, args);
}
}
java
@RestController
public class PayAlibabaController {
@Value("${server.port}")
private String serverPort;
@GetMapping("/pay/nacos/{id}")
public String getPayInfo(@PathVariable("id") Integer id) {
return "nacos registry serverPost: " + serverPort + ", id: " + id;
}
}
consumer
需要额外添加 load-balance 依赖
yaml
server:
port: 9000
spring:
application:
name: nacos-order-consume
cloud:
nacos:
discovery:
server-addr: localhost:8848 # nacos地址
service-url:
nacos-user-service: http://nacos-pay-provider
配置 RestTemplate
java
@RestController
public class OrderController {
@Resource
private RestTemplate restTemplate;
@Value("${service-url.nacos-user-service}")
private String serverURL;
@GetMapping("/order/pay/nacos/{id}")
public String paymentInfo(@PathVariable("id") Integer id) {
return restTemplate.getForObject(serverURL + "/pay/nacos/" + id, String.class);
}
}
-DServer.port=9002
GET http://localhost:9000/order/pay/nacos/112 测试负载均衡 端口 9001 9002 交替出现
服务配置中心和动态刷新
xml
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
也是需要 bootstrap
yaml
spring:
application:
name: nacos-config-client
cloud:
nacos:
discovery:
server-addr: localhost:8848
config:
server-addr: localhost:8848
file-extension: yaml
java
@RestController
@RefreshScope // 支持动态刷新功能
public class NacosConfigClientController {
@Value("${config.info}")
private String configInfo;
@GetMapping("/config/info")
public String getConfigInfo() {
return configInfo;
}
}
nacos 中配置匹配规则
nacos-config-client-dev.yaml
测试接口和动态刷新
ps: nacos 历史配置回滚功能
Nacos数据模型 Namespace-Group-DataId三元组
解决多项目多环境配置问题
DataId 方案
使用默认 Namespace 默认 Group
不同 DataId,使用服务名+环境名来区分
Group 方案
通过Group实现环境区分,默认 Namespace
新建 group PROD_GROUP 的配置
Namespace 环境区分
新建命名空间 Prod_Namespace,不填写id,会自动生成