✨ 远程调用-Feign拦截器
This commit is contained in:
parent
ccc68630f0
commit
71049d5251
|
@ -336,7 +336,7 @@ spring:
|
||||||
on-profile: test
|
on-profile: test
|
||||||
```
|
```
|
||||||
|
|
||||||
## OpenFeign
|
## OpenFeign 使用
|
||||||
|
|
||||||
### 基础配置
|
### 基础配置
|
||||||
|
|
||||||
|
@ -354,7 +354,6 @@ spring:
|
||||||
|
|
||||||
```java
|
```java
|
||||||
@SpringBootApplication
|
@SpringBootApplication
|
||||||
@EnableDiscoveryClient
|
|
||||||
@EnableFeignClients(basePackages = "com.yourpackage.feign")
|
@EnableFeignClients(basePackages = "com.yourpackage.feign")
|
||||||
public class OrderServiceApplication {
|
public class OrderServiceApplication {
|
||||||
public static void main(String[] args) {
|
public static void main(String[] args) {
|
||||||
|
@ -363,6 +362,9 @@ public class OrderServiceApplication {
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
> [!NOTE]
|
||||||
|
> `@EnableDiscoveryClient`注解,Spring Cloud最新版本已自动启用服务发现功能。
|
||||||
|
|
||||||
### Feign客户端使用
|
### Feign客户端使用
|
||||||
|
|
||||||
#### 服务间调用
|
#### 服务间调用
|
||||||
|
@ -371,7 +373,7 @@ public class OrderServiceApplication {
|
||||||
|
|
||||||
```java
|
```java
|
||||||
@FeignClient(
|
@FeignClient(
|
||||||
value = "service-product",
|
name = "service-product",
|
||||||
path = "/api/product",
|
path = "/api/product",
|
||||||
configuration = ProductFeignConfig.class
|
configuration = ProductFeignConfig.class
|
||||||
)
|
)
|
||||||
|
@ -381,86 +383,61 @@ public interface ProductFeignClient {
|
||||||
ResponseEntity<Product> getProductById(@PathVariable("id") Long productId);
|
ResponseEntity<Product> getProductById(@PathVariable("id") Long productId);
|
||||||
|
|
||||||
@PostMapping
|
@PostMapping
|
||||||
ResponseEntity<Void> createProduct(@RequestBody Product product);
|
ResponseEntity<Void> createProduct(@Valid @RequestBody Product product); // 添加@Valid注解支持参数校验
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
**服务调用示例**:
|
**服务调用示例优化**:
|
||||||
|
|
||||||
```java
|
```java
|
||||||
@Service
|
@Service
|
||||||
@RequiredArgsConstructor
|
@RequiredArgsConstructor
|
||||||
public class OrderService {
|
public class OrderService {
|
||||||
|
|
||||||
private final ProductFeignClient productFeignClient;
|
private final ProductFeignClient productFeignClient;
|
||||||
|
|
||||||
public Order createOrder(Long productId, Long userId) {
|
public Order createOrder(Long productId, Long userId) {
|
||||||
// 使用Feign客户端调用远程服务
|
Product product = productFeignClient.getProductById(productId)
|
||||||
ResponseEntity<Product> response = productFeignClient.getProductById(productId);
|
.orElseThrow(() -> new ProductNotFoundException(productId)); // 使用Optional简化判断
|
||||||
|
|
||||||
if (!response.getStatusCode().is2xxSuccessful()) {
|
return Order.builder()
|
||||||
throw new RuntimeException("商品服务调用失败");
|
.productId(product.getId())
|
||||||
}
|
.userId(userId)
|
||||||
|
// 其他订单属性
|
||||||
Product product = response.getBody();
|
.build();
|
||||||
Order order = new Order();
|
|
||||||
// 订单业务逻辑处理...
|
|
||||||
return order;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 第三方服务调用
|
#### 第三方服务调用优化
|
||||||
|
|
||||||
```java
|
```java
|
||||||
@FeignClient(
|
@FeignClient(
|
||||||
name = "bunny-client",
|
name = "bunny-client",
|
||||||
url = "${external.bunny.api.url}",
|
url = "${external.bunny.api.url}",
|
||||||
configuration = ExternalFeignConfig.class
|
configuration = ExternalFeignConfig.class
|
||||||
)
|
)
|
||||||
public interface BunnyFeignClient {
|
public interface BunnyFeignClient {
|
||||||
|
|
||||||
@PostMapping("/login")
|
@PostMapping("/login")
|
||||||
ResponseEntity<String> login(@RequestBody LoginDto loginDto);
|
ResponseEntity<AuthResponse> login(@Valid @RequestBody LoginDto loginDto); // 使用具体返回类型替代String
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
**测试用例**:
|
|
||||||
|
|
||||||
```java
|
|
||||||
@SpringBootTest
|
|
||||||
public class BunnyFeignClientTest {
|
|
||||||
|
|
||||||
@Autowired
|
|
||||||
private BunnyFeignClient bunnyFeignClient;
|
|
||||||
|
|
||||||
@Test
|
|
||||||
void testLogin() {
|
|
||||||
LoginDto loginDto = new LoginDto("bunny", "admin123", "default");
|
|
||||||
ResponseEntity<String> response = bunnyFeignClient.login(loginDto);
|
|
||||||
|
|
||||||
assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK);
|
|
||||||
System.out.println("登录响应: " + response.getBody());
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
### 负载均衡对比
|
### 负载均衡对比
|
||||||
|
|
||||||
#### 客户端负载均衡 vs 服务端负载均衡
|
| 特性 | 客户端负载均衡 (OpenFeign) | 服务端负载均衡 (Nginx等) |
|
||||||
|
| ------------ | ----------------------------------- | ------------------------ |
|
||||||
| 特性 | 客户端负载均衡 (OpenFeign) | 服务端负载均衡 (Nginx等) |
|
| **实现位置** | 客户端实现 | 服务端实现 |
|
||||||
| ------------ | -------------------------- | ------------------------ |
|
| **依赖关系** | 需要服务注册中心 | 不依赖注册中心 |
|
||||||
| **实现位置** | 客户端实现 | 服务端实现 |
|
| **性能** | 直接调用,减少网络跳转 | 需要经过代理服务器 |
|
||||||
| **依赖关系** | 需要服务注册中心 | 不依赖注册中心 |
|
| **灵活性** | 可定制负载均衡策略 | 配置相对固定 |
|
||||||
| **性能** | 直接调用,减少网络跳转 | 需要经过代理服务器 |
|
| **服务发现** | 集成服务发现机制 | 需要手动维护服务列表 |
|
||||||
| **灵活性** | 可定制负载均衡策略 | 配置相对固定 |
|
| **适用场景** | 微服务内部调用 | 对外暴露API或跨系统调用 |
|
||||||
| **服务发现** | 集成服务发现机制 | 需要手动维护服务列表 |
|
| **容错能力** | 集成熔断机制(如Sentinel、Hystrix) | 依赖代理服务器容错配置 |
|
||||||
| **适用场景** | 微服务内部调用 | 对外暴露API或跨系统调用 |
|
|
||||||
|
|
||||||
### 高级配置
|
### 高级配置
|
||||||
|
|
||||||
#### 日志配置
|
#### 日志配置优化
|
||||||
|
|
||||||
**application.yml**:
|
**application.yml**:
|
||||||
|
|
||||||
|
@ -474,18 +451,20 @@ logging:
|
||||||
**Java配置**:
|
**Java配置**:
|
||||||
|
|
||||||
```java
|
```java
|
||||||
|
@Configuration
|
||||||
public class FeignConfig {
|
public class FeignConfig {
|
||||||
|
|
||||||
@Bean
|
@Bean
|
||||||
Logger.Level feignLoggerLevel() {
|
Logger.Level feignLoggerLevel() {
|
||||||
return Logger.Level.FULL; // NONE, BASIC, HEADERS, FULL
|
// 生产环境建议使用BASIC级别
|
||||||
|
return Logger.Level.FULL;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
#### 超时与重试配置
|
#### 超时与重试配置优化
|
||||||
|
|
||||||
**application-feign.yml**:
|
**application.yml**:
|
||||||
|
|
||||||
```yaml
|
```yaml
|
||||||
spring:
|
spring:
|
||||||
|
@ -497,10 +476,12 @@ spring:
|
||||||
connect-timeout: 2000
|
connect-timeout: 2000
|
||||||
read-timeout: 5000
|
read-timeout: 5000
|
||||||
logger-level: basic
|
logger-level: basic
|
||||||
|
retryable: false # 默认关闭重试,避免幂等问题
|
||||||
|
|
||||||
service-product: # 特定服务配置
|
service-product: # 特定服务配置
|
||||||
connect-timeout: 3000
|
connect-timeout: 3000
|
||||||
read-timeout: 10000
|
read-timeout: 10000
|
||||||
|
retryable: true
|
||||||
```
|
```
|
||||||
|
|
||||||
**重试机制配置**:
|
**重试机制配置**:
|
||||||
|
@ -512,3 +493,88 @@ public Retryer feignRetryer() {
|
||||||
return new Retryer.Default(100, 1000, 3);
|
return new Retryer.Default(100, 1000, 3);
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
### Feign拦截器优化
|
||||||
|
|
||||||
|
#### 最佳实践
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Component
|
||||||
|
@RequiredArgsConstructor
|
||||||
|
public class AuthRequestInterceptor implements RequestInterceptor {
|
||||||
|
private final AuthService authService;
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public void apply(RequestTemplate template) {
|
||||||
|
template.header("Authorization", "Bearer " + authService.getCurrentToken());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**配置方式**:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
spring:
|
||||||
|
cloud:
|
||||||
|
openfeign:
|
||||||
|
client:
|
||||||
|
config:
|
||||||
|
default:
|
||||||
|
request-interceptors:
|
||||||
|
- com.yourpackage.feign.interceptor.AuthRequestInterceptor
|
||||||
|
- com.yourpackage.feign.interceptor.LoggingInterceptor
|
||||||
|
```
|
||||||
|
|
||||||
|
### 熔断降级配置优化
|
||||||
|
|
||||||
|
#### 整合Sentinel
|
||||||
|
|
||||||
|
```xml
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
||||||
|
<version>${sentinel.version}</version>
|
||||||
|
</dependency>
|
||||||
|
```
|
||||||
|
|
||||||
|
**配置**:
|
||||||
|
|
||||||
|
```yaml
|
||||||
|
feign:
|
||||||
|
sentinel:
|
||||||
|
enabled: true
|
||||||
|
# 降级策略配置
|
||||||
|
fallback:
|
||||||
|
enabled: true
|
||||||
|
# 默认降级类路径
|
||||||
|
default: com.yourpackage.feign.fallback.DefaultFallback
|
||||||
|
```
|
||||||
|
|
||||||
|
**降级实现优化**:
|
||||||
|
|
||||||
|
```java
|
||||||
|
@Slf4j
|
||||||
|
@Component
|
||||||
|
public class ProductFeignClientFallback implements ProductFeignClient {
|
||||||
|
|
||||||
|
@Override
|
||||||
|
public ResponseEntity<Product> getProductById(Long productId) {
|
||||||
|
log.warn("Product服务降级,productId: {}", productId);
|
||||||
|
return ResponseEntity.ok(Product.getDefaultProduct(productId));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
**FeignClient使用**:
|
||||||
|
|
||||||
|
```java
|
||||||
|
@FeignClient(
|
||||||
|
name = "service-product",
|
||||||
|
path = "/api/product",
|
||||||
|
fallback = ProductFeignClientFallback.class,
|
||||||
|
fallbackFactory = ProductFeignClientFallbackFactory.class // 可选,用于获取异常信息
|
||||||
|
)
|
||||||
|
public interface ProductFeignClient {
|
||||||
|
// 方法定义
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
|
@ -18,6 +18,9 @@
|
||||||
</properties>
|
</properties>
|
||||||
|
|
||||||
<dependencies>
|
<dependencies>
|
||||||
|
<dependency>
|
||||||
|
<groupId>com.alibaba.cloud</groupId>
|
||||||
|
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
||||||
|
</dependency>
|
||||||
</dependencies>
|
</dependencies>
|
||||||
</project>
|
</project>
|
||||||
|
|
|
@ -1,12 +1,13 @@
|
||||||
package cn.bunny.service.feign;
|
package cn.bunny.service.feign;
|
||||||
|
|
||||||
import cn.bunny.model.product.bean.Product;
|
import cn.bunny.model.product.bean.Product;
|
||||||
|
import cn.bunny.service.feign.fallback.ProductFeignClientFallback;
|
||||||
import org.springframework.cloud.openfeign.FeignClient;
|
import org.springframework.cloud.openfeign.FeignClient;
|
||||||
import org.springframework.web.bind.annotation.GetMapping;
|
import org.springframework.web.bind.annotation.GetMapping;
|
||||||
import org.springframework.web.bind.annotation.PathVariable;
|
import org.springframework.web.bind.annotation.PathVariable;
|
||||||
|
|
||||||
// Feign 客户端
|
// Feign 客户端
|
||||||
@FeignClient(value = "service-product", path = "/api/product")
|
@FeignClient(value = "service-product", path = "/api/product", fallback = ProductFeignClientFallback.class)
|
||||||
public interface ProductFeignClient {
|
public interface ProductFeignClient {
|
||||||
|
|
||||||
// 标注在 Controller 上是接受请求
|
// 标注在 Controller 上是接受请求
|
||||||
|
|
|
@ -0,0 +1,22 @@
|
||||||
|
package cn.bunny.service.feign.fallback;
|
||||||
|
|
||||||
|
import cn.bunny.model.product.bean.Product;
|
||||||
|
import cn.bunny.service.feign.ProductFeignClient;
|
||||||
|
import org.springframework.stereotype.Component;
|
||||||
|
|
||||||
|
import java.math.BigDecimal;
|
||||||
|
|
||||||
|
@Component
|
||||||
|
public class ProductFeignClientFallback implements ProductFeignClient {
|
||||||
|
@Override
|
||||||
|
public Product getProduct(Long productId) {
|
||||||
|
System.out.println("ProductFeignClientFallback 兜底回调...");
|
||||||
|
|
||||||
|
Product product = new Product();
|
||||||
|
product.setId(productId);
|
||||||
|
product.setPrice(new BigDecimal("1000"));
|
||||||
|
product.setProductName("兜底数据");
|
||||||
|
product.setNum(99);
|
||||||
|
return product;
|
||||||
|
}
|
||||||
|
}
|
|
@ -15,4 +15,7 @@ spring:
|
||||||
connect-timeout: 3000
|
connect-timeout: 3000
|
||||||
read-timeout: 5000 # 最多等待对方 5s
|
read-timeout: 5000 # 最多等待对方 5s
|
||||||
request-interceptors:
|
request-interceptors:
|
||||||
- cn.bunny.service.interceptor.XTokenRequestInterceptor
|
- cn.bunny.service.interceptor.XTokenRequestInterceptor
|
||||||
|
feign:
|
||||||
|
sentinel:
|
||||||
|
enabled: true
|
Loading…
Reference in New Issue