Compare commits
2 Commits
a76dd2227e
...
041b8c0218
Author | SHA1 | Date |
---|---|---|
|
041b8c0218 | |
|
6ee93a581c |
|
@ -1,4 +1,4 @@
|
|||
# 微服务文档
|
||||
# Nacos注册中心
|
||||
|
||||
## 注册中心
|
||||
|
||||
|
@ -18,25 +18,24 @@ public class DiscoveryTest {
|
|||
|
||||
@Test
|
||||
void discoveryClientTest() {
|
||||
// 使用Spring Cloud标准DiscoveryClient
|
||||
for (String service : discoveryClient.getServices()) {
|
||||
System.out.println("服务名称: " + service);
|
||||
System.out.println(service);
|
||||
|
||||
for (ServiceInstance instance : discoveryClient.getInstances(service)) {
|
||||
System.out.println("实例IP地址: " + instance.getHost());
|
||||
System.out.println("实例端口号: " + instance.getPort());
|
||||
System.out.println("IP地址:" + instance.getHost());
|
||||
System.out.println("端口号" + instance.getPort());
|
||||
}
|
||||
}
|
||||
|
||||
System.out.println("----------------------------------------------");
|
||||
|
||||
// 使用Nacos专用DiscoveryClient
|
||||
// 两个方式一样,DiscoveryClient 是 Spring自带的 NacosDiscoveryClient是 Nacos
|
||||
for (String service : nacosDiscoveryClient.getServices()) {
|
||||
System.out.println("服务名称: " + service);
|
||||
System.out.println(service);
|
||||
|
||||
for (ServiceInstance instance : nacosDiscoveryClient.getInstances(service)) {
|
||||
System.out.println("实例IP地址: " + instance.getHost());
|
||||
System.out.println("实例端口号: " + instance.getPort());
|
||||
System.out.println("IP地址:" + instance.getHost());
|
||||
System.out.println("端口号" + instance.getPort());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -45,11 +44,11 @@ public class DiscoveryTest {
|
|||
|
||||
### 远程调用
|
||||
|
||||
订单模块调用远程商品模块,使用Nacos作为注册中心,可以使用`RestTemplate`进行远程调用。`RestTemplate`是线程安全的,只需注册一次即可全局使用。
|
||||
订单模块调用远程商品模块,使用了nacos,可以使用`RestTemplate`,其中`RestTemplate`是线程安全的,只要注册一次全局都是可以使用。
|
||||
|
||||
**RestTemplate线程安全说明**
|
||||
**RestTemplate源码**
|
||||
|
||||
`RestTemplate`继承了`InterceptingHttpAccessor`,其中使用了单例模式保证线程安全:
|
||||
继承了`InterceptingHttpAccessor`,在`InterceptingHttpAccessor`中,使用了单例模式。
|
||||
|
||||
```java
|
||||
public ClientHttpRequestFactory getRequestFactory() {
|
||||
|
@ -60,6 +59,7 @@ public ClientHttpRequestFactory getRequestFactory() {
|
|||
factory = new InterceptingClientHttpRequestFactory(super.getRequestFactory(), interceptors);
|
||||
this.interceptingRequestFactory = factory;
|
||||
}
|
||||
|
||||
return factory;
|
||||
} else {
|
||||
return super.getRequestFactory();
|
||||
|
@ -69,9 +69,9 @@ public ClientHttpRequestFactory getRequestFactory() {
|
|||
|
||||
#### 实现远程调用
|
||||
|
||||
##### 基础调用方式
|
||||
##### 普通方式调用
|
||||
|
||||
1. 注册`RestTemplate` Bean:
|
||||
注册`RestTemplate`
|
||||
|
||||
```java
|
||||
@Bean
|
||||
|
@ -80,27 +80,26 @@ public RestTemplate restTemplate() {
|
|||
}
|
||||
```
|
||||
|
||||
2. 实现远程调用:
|
||||
如果我们的服务启动了多个,在下面代码中即使一个服务宕机也可以做到远程调用。
|
||||
|
||||
```java
|
||||
private Product getProductFromRemote(Long productId) {
|
||||
// 获取商品服务所有实例
|
||||
// 获取商品服务所有及其的 IP+port
|
||||
List<ServiceInstance> instances = discoveryClient.getInstances("service-product");
|
||||
if (instances.isEmpty()) {
|
||||
throw new RuntimeException("未找到可用的商品服务实例");
|
||||
}
|
||||
|
||||
ServiceInstance instance = instances.get(0);
|
||||
|
||||
// 远程URL
|
||||
String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/api/product/" + productId;
|
||||
|
||||
log.info("远程调用商品服务: {}", url);
|
||||
// 2. 远程发送请求
|
||||
log.info("远程调用:{}", url);
|
||||
return restTemplate.getForObject(url, Product.class);
|
||||
}
|
||||
```
|
||||
|
||||
##### 负载均衡调用
|
||||
|
||||
1. 注册`RestTemplate` Bean:
|
||||
注册`RestTemplate`
|
||||
|
||||
```java
|
||||
@Bean
|
||||
|
@ -109,32 +108,39 @@ public RestTemplate restTemplate() {
|
|||
}
|
||||
```
|
||||
|
||||
2. 使用`LoadBalancerClient`实现负载均衡:
|
||||
使用负载均衡`LoadBalancerClient`,通过负载均衡算法动态调用远程服务。
|
||||
|
||||
```java
|
||||
/**
|
||||
* 使用负载均衡调用远程商品服务
|
||||
* 远程调用商品模块 --- 负载均衡
|
||||
*
|
||||
* @param productId 商品ID
|
||||
* @return 商品信息
|
||||
* @param productId 商品id
|
||||
* @return 商品对象
|
||||
*/
|
||||
private Product getProductFromRemoteWithLoadBalancer(Long productId) {
|
||||
// 1. 获取商品服务所有及其的 IP+port
|
||||
ServiceInstance instance = loadBalancerClient.choose("service-product");
|
||||
|
||||
// 远程URL
|
||||
String url = "http://" + instance.getHost() + ":" + instance.getPort() + "/api/product/" + productId;
|
||||
|
||||
log.info("负载均衡远程调用商品服务: {}", url);
|
||||
// 2. 远程发送请求
|
||||
log.info("负载均衡远程调用:{}", url);
|
||||
return restTemplate.getForObject(url, Product.class);
|
||||
}
|
||||
```
|
||||
|
||||
##### 注解式负载均衡调用
|
||||
##### 负载均衡注解调用
|
||||
|
||||
> [!TIP]
|
||||
> 关于注册中心宕机的影响:
|
||||
> - 已调用过的服务:可以继续调用,因为客户端有缓存
|
||||
> - 未调用过的服务:首次调用会失败,因为需要从注册中心获取服务列表
|
||||
>
|
||||
> 如果远程注册中心宕机是否可以调用?
|
||||
>
|
||||
> 调用过:远程调用不在依赖注册中心,可以通过。
|
||||
>
|
||||
> 没调用过:第一次发起远程调用;不能通过。
|
||||
|
||||
1. 注册带负载均衡的`RestTemplate`:
|
||||
在`RestTemplate`上加上`@LoadBalanced`注解使用负载均衡。
|
||||
|
||||
```java
|
||||
@Bean
|
||||
|
@ -144,67 +150,85 @@ public RestTemplate restTemplate() {
|
|||
}
|
||||
```
|
||||
|
||||
2. 直接使用服务名进行调用:
|
||||
在实际的调用中并不需要再显式调用,将URL替换成服务名称即可。
|
||||
|
||||
```java
|
||||
/**
|
||||
* 使用注解式负载均衡调用远程商品服务
|
||||
* 远程调用商品模块 --- 负载均衡注解调用
|
||||
*
|
||||
* @param productId 商品ID
|
||||
* @return 商品信息
|
||||
* @param productId 商品id
|
||||
* @return 商品对象
|
||||
*/
|
||||
private Product getProductFromRemoteWithLoadBalancerAnnotation(Long productId) {
|
||||
// 远程URL,实现动态替换
|
||||
String url = "http://service-product/api/product/" + productId;
|
||||
log.info("负载均衡注解调用商品服务: {}", url);
|
||||
|
||||
// 远程发送请求
|
||||
log.info("负载均衡注解调用:{}", url);
|
||||
return restTemplate.getForObject(url, Product.class);
|
||||
}
|
||||
```
|
||||
|
||||
### 远程配置管理
|
||||
## 按需加载
|
||||
|
||||
#### 基础配置
|
||||
### 数据隔离架构
|
||||
|
||||
1. 添加依赖:
|
||||

|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
|
||||
</dependency>
|
||||
```
|
||||
### 命名空间管理
|
||||
|
||||
2. 在Nacos中配置:
|
||||
#### 创建命名空间
|
||||
|
||||
> [!TIP]
|
||||
> 预配置的命名空间示例可在项目 `samples/namespace-config` 目录下找到。
|
||||
|
||||
建议创建以下标准命名空间:
|
||||
|
||||
- `dev` - 开发环境
|
||||
- `test` - 测试环境
|
||||
- `prod` - 生产环境
|
||||
|
||||
**操作步骤**:
|
||||
|
||||
1. 进入Nacos控制台命名空间管理
|
||||
2. 点击"新建命名空间"
|
||||
3. 填写命名空间信息(ID和名称)
|
||||
|
||||

|
||||

|
||||
|
||||
#### 配置管理
|
||||
|
||||
**开发环境配置示例**:
|
||||
|
||||
1. 基础配置:
|
||||
|
||||
配置内容示例:
|
||||
```yaml
|
||||
order:
|
||||
timeout: 30min
|
||||
auto-confirm: true
|
||||
timeout: 1min
|
||||
auto-confirm: 1h
|
||||
```
|
||||
|
||||
3. 创建配置读取接口:
|
||||
2. 数据库配置:
|
||||
|
||||
```java
|
||||
@RestController
|
||||
@RequestMapping("/api/order")
|
||||
@RequiredArgsConstructor
|
||||
public class OrderController {
|
||||
|
||||
@Value("${order.timeout}")
|
||||
private String timeout;
|
||||
|
||||
@Value("${order.auto-confirm}")
|
||||
private String autoConfirm;
|
||||
|
||||
@Operation(summary = "读取配置")
|
||||
@GetMapping("config")
|
||||
public String config() {
|
||||
return "timeout: " + timeout + "\nautoConfirm: " + autoConfirm;
|
||||
}
|
||||
}
|
||||
```yaml
|
||||
order:
|
||||
db-url: jdbc:mysql://dev-db:3306/order_dev
|
||||
```
|
||||
|
||||
4. 应用配置:
|
||||

|
||||
|
||||
#### 命名空间克隆
|
||||
|
||||
通过克隆功能快速创建相似环境的命名空间:
|
||||
|
||||

|
||||
|
||||
### 动态环境配置
|
||||
|
||||
#### Spring Boot 配置方案
|
||||
|
||||
**基础配置**:
|
||||
|
||||
```yaml
|
||||
server:
|
||||
|
@ -214,150 +238,100 @@ spring:
|
|||
name: service-order
|
||||
profiles:
|
||||
active: dev
|
||||
config:
|
||||
import:
|
||||
- nacos:service-order.yml
|
||||
cloud:
|
||||
nacos:
|
||||
server-addr: 192.168.95.135:8848
|
||||
server-addr: ${NACOS_HOST:192.168.95.135}:8848
|
||||
config:
|
||||
import-check:
|
||||
enabled: false
|
||||
namespace: ${spring.profiles.active:dev} # 动态匹配当前profile
|
||||
group: DEFAULT_GROUP
|
||||
```
|
||||
|
||||
> [!CAUTION]
|
||||
> 注意事项:
|
||||
> - 不要在`server-addr`中使用变量引用如`${nacos.server-addr}`,这可能导致连接失败
|
||||
> - 对于不需要动态配置的模块,可以禁用配置检查
|
||||
**多环境配置加载**:
|
||||
|
||||
#### 动态刷新配置
|
||||
|
||||
1. 添加`@RefreshScope`注解:
|
||||
|
||||
```java
|
||||
@SpringBootApplication
|
||||
@EnableDiscoveryClient
|
||||
@RefreshScope
|
||||
public class ProductServiceApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(ProductServiceApplication.class, args);
|
||||
}
|
||||
}
|
||||
```yaml
|
||||
spring:
|
||||
config:
|
||||
import:
|
||||
- optional:nacos:service-order.yml
|
||||
- optional:nacos:common.yml?group=order
|
||||
- optional:nacos:database.yml?group=order
|
||||
```
|
||||
|
||||
#### 批量配置绑定
|
||||
> [!NOTE]
|
||||
> 使用`optional:`前缀可避免配置不存在时启动失败
|
||||
|
||||
> [!TIP]
|
||||
> 使用`@ConfigurationProperties`批量绑定配置:
|
||||
> - 无需`@RefreshScope`即可实现动态刷新
|
||||
> - 支持中划线命名自动转为驼峰命名
|
||||
### 配置读取实现
|
||||
|
||||
1. 创建配置类:
|
||||
**配置类**:
|
||||
|
||||
```java
|
||||
@Configuration
|
||||
@ConfigurationProperties(prefix = "order")
|
||||
@Getter
|
||||
@Setter
|
||||
public class OrderProperties {
|
||||
private String timeout;
|
||||
private String autoConfirm;
|
||||
// getters and setters
|
||||
private String dbUrl; // 自动映射db-url
|
||||
}
|
||||
```
|
||||
|
||||
2. 使用配置:
|
||||
**REST接口**:
|
||||
|
||||
```java
|
||||
@RestController
|
||||
@RequestMapping("/api/order")
|
||||
@RequiredArgsConstructor
|
||||
public class OrderController {
|
||||
|
||||
private final OrderProperties orderProperties;
|
||||
|
||||
@Operation(summary = "读取配置")
|
||||
@GetMapping("config")
|
||||
public String config() {
|
||||
return "timeout: " + orderProperties.getTimeout() +
|
||||
"\nautoConfirm: " + orderProperties.getAutoConfirm();
|
||||
@GetMapping("/config")
|
||||
public Map<String, String> getConfig() {
|
||||
return Map.of(
|
||||
"timeout", orderProperties.getTimeout(),
|
||||
"autoConfirm", orderProperties.getAutoConfirm(),
|
||||
"dbUrl", orderProperties.getDbUrl()
|
||||
);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 高级配置管理
|
||||
### 按需加载策略
|
||||
|
||||
1. 多环境配置:
|
||||
#### 多环境差异化配置
|
||||
|
||||
```yaml
|
||||
spring:
|
||||
profiles:
|
||||
active: @profileActive@
|
||||
config:
|
||||
import:
|
||||
- nacos:service-order-${spring.profiles.active}.yml
|
||||
```
|
||||
active: prod # 可通过启动参数覆盖
|
||||
|
||||
2. 共享配置:
|
||||
|
||||
```yaml
|
||||
---
|
||||
# 生产环境配置
|
||||
spring:
|
||||
config:
|
||||
import:
|
||||
- nacos:common-config.yml
|
||||
- nacos:service-order.yml
|
||||
- nacos:service-order-prod.yml
|
||||
- nacos:common-prod.yml?group=order
|
||||
activate:
|
||||
on-profile: prod
|
||||
|
||||
---
|
||||
# 开发环境配置
|
||||
spring:
|
||||
config:
|
||||
import:
|
||||
- nacos:service-order-dev.yml
|
||||
- nacos:database-dev.yml?group=order
|
||||
activate:
|
||||
on-profile: dev
|
||||
|
||||
---
|
||||
# 测试环境配置
|
||||
spring:
|
||||
config:
|
||||
import:
|
||||
- nacos:service-order-test.yml
|
||||
- nacos:database-test.yml?group=order
|
||||
activate:
|
||||
on-profile: test
|
||||
```
|
||||
|
||||
3. 命名空间和分组:
|
||||
|
||||
```yaml
|
||||
cloud:
|
||||
nacos:
|
||||
config:
|
||||
namespace: dev
|
||||
group: DEFAULT_GROUP
|
||||
```
|
||||
|
||||
4. 配置优先级:
|
||||
- 应用名-profile.yml (最高优先级)
|
||||
- 应用名.yml
|
||||
- 扩展配置
|
||||
- 共享配置 (最低优先级)
|
||||
|
||||
### 配置监听
|
||||
|
||||

|
||||
|
||||
#### 实现配置监听
|
||||
|
||||
1. 项目启动时注册监听器:
|
||||
|
||||
```java
|
||||
@SpringBootApplication
|
||||
@EnableDiscoveryClient
|
||||
public class OrderServiceApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(OrderServiceApplication.class, args);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public ApplicationRunner runner(NacosConfigManager nacosConfigManager) {
|
||||
return args -> {
|
||||
ConfigService configService = nacosConfigManager.getConfigService();
|
||||
configService.addListener("service-order.yml", "DEFAULT_GROUP", new Listener() {
|
||||
@Override
|
||||
public Executor getExecutor() {
|
||||
return Executors.newFixedThreadPool(10);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void receiveConfigInfo(String configInfo) {
|
||||
System.out.println("配置变更内容: " + configInfo);
|
||||
// 实现配置变更后的处理逻辑
|
||||
System.out.println("发送配置变更通知邮件...");
|
||||
}
|
||||
});
|
||||
System.out.println("订单服务启动完成,配置监听已注册");
|
||||
};
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
|
|
Binary file not shown.
After Width: | Height: | Size: 193 KiB |
Binary file not shown.
After Width: | Height: | Size: 36 KiB |
Binary file not shown.
After Width: | Height: | Size: 20 KiB |
Binary file not shown.
After Width: | Height: | Size: 16 KiB |
Binary file not shown.
After Width: | Height: | Size: 19 KiB |
Binary file not shown.
After Width: | Height: | Size: 50 KiB |
Binary file not shown.
|
@ -15,4 +15,6 @@ public class OrderProperties {
|
|||
// 中划线写法会自动映射为小驼峰
|
||||
private String autoConfirm;
|
||||
|
||||
private String dbUrl;
|
||||
|
||||
}
|
||||
|
|
|
@ -35,6 +35,8 @@ public class OrderController {
|
|||
public String config() {
|
||||
String timeout = orderProperties.getTimeout();
|
||||
String autoConfirm = orderProperties.getAutoConfirm();
|
||||
return "timeout:" + timeout + "\nautoConfirm:" + autoConfirm;
|
||||
String dbUrl = orderProperties.getDbUrl();
|
||||
|
||||
return "timeout:" + timeout + "\nautoConfirm:" + autoConfirm + "\norder.db-url" + dbUrl;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -1,16 +1,49 @@
|
|||
server:
|
||||
port: 8000
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: service-order
|
||||
profiles:
|
||||
active: dev
|
||||
config:
|
||||
import:
|
||||
- nacos:service-order.yml
|
||||
active: prod
|
||||
cloud:
|
||||
nacos:
|
||||
server-addr: 192.168.95.135:8848
|
||||
config:
|
||||
import-check:
|
||||
enabled: false
|
||||
enabled: false
|
||||
# namespace: prod # 所在的命名空间
|
||||
namespace: ${spring.profiles.active:dev} # 所在的命名空间,如果没有写 dev 为默认值
|
||||
|
||||
---
|
||||
spring:
|
||||
config:
|
||||
import:
|
||||
- nacos:service-order.yml
|
||||
- nacos:common.yml?group=order # 在nacos中配置了分组
|
||||
- nacos:database.yml?group=order # 在nacos中配置了分组
|
||||
activate:
|
||||
on-profile: prod
|
||||
---
|
||||
|
||||
---
|
||||
spring:
|
||||
config:
|
||||
import:
|
||||
- nacos:service-order.yml
|
||||
- nacos:common.yml?group=order # 在nacos中配置了分组
|
||||
- nacos:database.yml?group=order # 在nacos中配置了分组
|
||||
activate:
|
||||
on-profile: dev
|
||||
---
|
||||
|
||||
---
|
||||
spring:
|
||||
config:
|
||||
import:
|
||||
- nacos:service-order.yml
|
||||
- nacos:common.yml?group=order # 在nacos中配置了分组
|
||||
- nacos:database.yml?group=order # 在nacos中配置了分组
|
||||
activate:
|
||||
on-profile: test
|
||||
---
|
Loading…
Reference in New Issue