Compare commits
7 Commits
041b8c0218
...
71049d5251
Author | SHA1 | Date |
---|---|---|
|
71049d5251 | |
|
ccc68630f0 | |
|
44457c9971 | |
|
42f1c00231 | |
|
41f905af9e | |
|
b450d0172d | |
|
42d21d0947 |
|
@ -335,3 +335,246 @@ spring:
|
|||
activate:
|
||||
on-profile: test
|
||||
```
|
||||
|
||||
## OpenFeign 使用
|
||||
|
||||
### 基础配置
|
||||
|
||||
#### 依赖引入
|
||||
|
||||
```xml
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||
<version>${spring-cloud.version}</version>
|
||||
</dependency>
|
||||
```
|
||||
|
||||
#### 启用Feign客户端
|
||||
|
||||
```java
|
||||
@SpringBootApplication
|
||||
@EnableFeignClients(basePackages = "com.yourpackage.feign")
|
||||
public class OrderServiceApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(OrderServiceApplication.class, args);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
> [!NOTE]
|
||||
> `@EnableDiscoveryClient`注解,Spring Cloud最新版本已自动启用服务发现功能。
|
||||
|
||||
### Feign客户端使用
|
||||
|
||||
#### 服务间调用
|
||||
|
||||
**Feign客户端定义**:
|
||||
|
||||
```java
|
||||
@FeignClient(
|
||||
name = "service-product",
|
||||
path = "/api/product",
|
||||
configuration = ProductFeignConfig.class
|
||||
)
|
||||
public interface ProductFeignClient {
|
||||
|
||||
@GetMapping("/{id}")
|
||||
ResponseEntity<Product> getProductById(@PathVariable("id") Long productId);
|
||||
|
||||
@PostMapping
|
||||
ResponseEntity<Void> createProduct(@Valid @RequestBody Product product); // 添加@Valid注解支持参数校验
|
||||
}
|
||||
```
|
||||
|
||||
**服务调用示例优化**:
|
||||
|
||||
```java
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class OrderService {
|
||||
private final ProductFeignClient productFeignClient;
|
||||
|
||||
public Order createOrder(Long productId, Long userId) {
|
||||
Product product = productFeignClient.getProductById(productId)
|
||||
.orElseThrow(() -> new ProductNotFoundException(productId)); // 使用Optional简化判断
|
||||
|
||||
return Order.builder()
|
||||
.productId(product.getId())
|
||||
.userId(userId)
|
||||
// 其他订单属性
|
||||
.build();
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 第三方服务调用优化
|
||||
|
||||
```java
|
||||
@FeignClient(
|
||||
name = "bunny-client",
|
||||
url = "${external.bunny.api.url}",
|
||||
configuration = ExternalFeignConfig.class
|
||||
)
|
||||
public interface BunnyFeignClient {
|
||||
|
||||
@PostMapping("/login")
|
||||
ResponseEntity<AuthResponse> login(@Valid @RequestBody LoginDto loginDto); // 使用具体返回类型替代String
|
||||
}
|
||||
```
|
||||
|
||||
### 负载均衡对比
|
||||
|
||||
| 特性 | 客户端负载均衡 (OpenFeign) | 服务端负载均衡 (Nginx等) |
|
||||
| ------------ | ----------------------------------- | ------------------------ |
|
||||
| **实现位置** | 客户端实现 | 服务端实现 |
|
||||
| **依赖关系** | 需要服务注册中心 | 不依赖注册中心 |
|
||||
| **性能** | 直接调用,减少网络跳转 | 需要经过代理服务器 |
|
||||
| **灵活性** | 可定制负载均衡策略 | 配置相对固定 |
|
||||
| **服务发现** | 集成服务发现机制 | 需要手动维护服务列表 |
|
||||
| **适用场景** | 微服务内部调用 | 对外暴露API或跨系统调用 |
|
||||
| **容错能力** | 集成熔断机制(如Sentinel、Hystrix) | 依赖代理服务器容错配置 |
|
||||
|
||||
### 高级配置
|
||||
|
||||
#### 日志配置优化
|
||||
|
||||
**application.yml**:
|
||||
|
||||
```yaml
|
||||
logging:
|
||||
level:
|
||||
org.springframework.cloud.openfeign: DEBUG
|
||||
com.yourpackage.feign: DEBUG
|
||||
```
|
||||
|
||||
**Java配置**:
|
||||
|
||||
```java
|
||||
@Configuration
|
||||
public class FeignConfig {
|
||||
|
||||
@Bean
|
||||
Logger.Level feignLoggerLevel() {
|
||||
// 生产环境建议使用BASIC级别
|
||||
return Logger.Level.FULL;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
#### 超时与重试配置优化
|
||||
|
||||
**application.yml**:
|
||||
|
||||
```yaml
|
||||
spring:
|
||||
cloud:
|
||||
openfeign:
|
||||
client:
|
||||
config:
|
||||
default: # 全局默认配置
|
||||
connect-timeout: 2000
|
||||
read-timeout: 5000
|
||||
logger-level: basic
|
||||
retryable: false # 默认关闭重试,避免幂等问题
|
||||
|
||||
service-product: # 特定服务配置
|
||||
connect-timeout: 3000
|
||||
read-timeout: 10000
|
||||
retryable: true
|
||||
```
|
||||
|
||||
**重试机制配置**:
|
||||
|
||||
```java
|
||||
@Bean
|
||||
public Retryer feignRetryer() {
|
||||
// 重试间隔100ms,最大间隔1s,最大尝试次数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 {
|
||||
// 方法定义
|
||||
}
|
||||
```
|
||||
|
|
|
@ -0,0 +1,10 @@
|
|||
package cn.bunny.model.order.bean;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class LoginDto {
|
||||
String username;
|
||||
String password;
|
||||
String type;
|
||||
}
|
|
@ -70,11 +70,11 @@
|
|||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-loadbalancer</artifactId>
|
||||
<artifactId>spring-cloud-starter-openfeign</artifactId>
|
||||
</dependency>
|
||||
|
||||
<!-- knife4j -->
|
||||
|
|
|
@ -18,6 +18,9 @@
|
|||
</properties>
|
||||
|
||||
<dependencies>
|
||||
|
||||
<dependency>
|
||||
<groupId>com.alibaba.cloud</groupId>
|
||||
<artifactId>spring-cloud-starter-alibaba-sentinel</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
</project>
|
||||
|
|
|
@ -8,6 +8,7 @@ import org.springframework.boot.SpringApplication;
|
|||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
|
||||
import org.springframework.cloud.context.config.annotation.RefreshScope;
|
||||
import org.springframework.cloud.openfeign.EnableFeignClients;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
|
||||
import java.util.concurrent.Executor;
|
||||
|
@ -16,6 +17,7 @@ import java.util.concurrent.Executors;
|
|||
@SpringBootApplication
|
||||
@EnableDiscoveryClient
|
||||
@RefreshScope
|
||||
@EnableFeignClients
|
||||
public class OrderServiceApplication {
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(OrderServiceApplication.class, args);
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
package cn.bunny.service.config;
|
||||
|
||||
import feign.Logger;
|
||||
import feign.Retryer;
|
||||
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
@ -8,10 +10,26 @@ import org.springframework.web.client.RestTemplate;
|
|||
@Configuration
|
||||
public class OrderServiceConfig {
|
||||
|
||||
@Bean
|
||||
public Retryer feignRetryer() {
|
||||
// 重试间隔100ms,最大间隔1s,最大尝试次数3次
|
||||
// return new Retryer.Default();
|
||||
return new Retryer.Default(100, 1000, 3);
|
||||
}
|
||||
|
||||
@Bean
|
||||
@LoadBalanced
|
||||
public RestTemplate restTemplate() {
|
||||
return new RestTemplate();
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置日志全级
|
||||
*
|
||||
* @return Logger级别
|
||||
*/
|
||||
@Bean
|
||||
public Logger.Level loggerLevel() {
|
||||
return Logger.Level.FULL;
|
||||
}
|
||||
}
|
||||
|
|
|
@ -0,0 +1,14 @@
|
|||
package cn.bunny.service.feign;
|
||||
|
||||
import cn.bunny.model.order.bean.LoginDto;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
|
||||
@FeignClient(value = "bunny-client", url = "http://bunny-web.site/api/user")
|
||||
public interface BunnyFeignClient {
|
||||
|
||||
@PostMapping("login")
|
||||
String login(@RequestBody LoginDto dtp);
|
||||
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package cn.bunny.service.feign;
|
||||
|
||||
import cn.bunny.model.product.bean.Product;
|
||||
import cn.bunny.service.feign.fallback.ProductFeignClientFallback;
|
||||
import org.springframework.cloud.openfeign.FeignClient;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
|
||||
// Feign 客户端
|
||||
@FeignClient(value = "service-product", path = "/api/product", fallback = ProductFeignClientFallback.class)
|
||||
public interface ProductFeignClient {
|
||||
|
||||
// 标注在 Controller 上是接受请求
|
||||
// 标注在 FeignClient 时发送请求
|
||||
@GetMapping("{id}")
|
||||
Product getProduct(@PathVariable("id") Long productId);
|
||||
|
||||
}
|
|
@ -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;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package cn.bunny.service.interceptor;
|
||||
|
||||
import feign.RequestInterceptor;
|
||||
import feign.RequestTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
@Component
|
||||
public class XTokenRequestInterceptor implements RequestInterceptor {
|
||||
|
||||
@Override
|
||||
public void apply(RequestTemplate requestTemplate) {
|
||||
requestTemplate.header("X-Token", UUID.randomUUID().toString());
|
||||
}
|
||||
|
||||
}
|
|
@ -2,6 +2,7 @@ package cn.bunny.service.service.impl;
|
|||
|
||||
import cn.bunny.model.order.bean.Order;
|
||||
import cn.bunny.model.product.bean.Product;
|
||||
import cn.bunny.service.feign.ProductFeignClient;
|
||||
import cn.bunny.service.service.OrderService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
|
@ -22,6 +23,7 @@ public class OrderServiceImpl implements OrderService {
|
|||
private final DiscoveryClient discoveryClient;
|
||||
private final RestTemplate restTemplate;
|
||||
private final LoadBalancerClient loadBalancerClient;
|
||||
private final ProductFeignClient productFeignClient;
|
||||
|
||||
/**
|
||||
* 创建订单信息
|
||||
|
@ -32,7 +34,8 @@ public class OrderServiceImpl implements OrderService {
|
|||
*/
|
||||
@Override
|
||||
public Order createOrder(Long productId, Long userId) {
|
||||
Product product = getProductFromRemoteWithLoadBalancerAnnotation(productId);
|
||||
// Product product = getProductFromRemoteWithLoadBalancerAnnotation(productId);
|
||||
Product product = productFeignClient.getProduct(productId);
|
||||
|
||||
Order order = new Order();
|
||||
order.setId(1L);
|
||||
|
|
|
@ -1,3 +0,0 @@
|
|||
server:
|
||||
port: 8000
|
||||
|
|
@ -0,0 +1,21 @@
|
|||
spring:
|
||||
cloud:
|
||||
openfeign:
|
||||
client:
|
||||
config:
|
||||
# 对所有配置
|
||||
default:
|
||||
logger-level: full
|
||||
connect-timeout: 1000
|
||||
read-timeout: 1000 # 最多等待对方 5s
|
||||
|
||||
# 对 service-product 单独设置
|
||||
service-product:
|
||||
logger-level: full
|
||||
connect-timeout: 3000
|
||||
read-timeout: 5000 # 最多等待对方 5s
|
||||
request-interceptors:
|
||||
- cn.bunny.service.interceptor.XTokenRequestInterceptor
|
||||
feign:
|
||||
sentinel:
|
||||
enabled: true
|
|
@ -5,7 +5,9 @@ spring:
|
|||
application:
|
||||
name: service-order
|
||||
profiles:
|
||||
active: prod
|
||||
active: dev
|
||||
include:
|
||||
- feign
|
||||
cloud:
|
||||
nacos:
|
||||
server-addr: 192.168.95.135:8848
|
||||
|
@ -15,6 +17,10 @@ spring:
|
|||
# namespace: prod # 所在的命名空间
|
||||
namespace: ${spring.profiles.active:dev} # 所在的命名空间,如果没有写 dev 为默认值
|
||||
|
||||
logging:
|
||||
level:
|
||||
cn.bunny.service.feign: debug
|
||||
|
||||
---
|
||||
spring:
|
||||
config:
|
||||
|
|
|
@ -1,69 +0,0 @@
|
|||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<contextName>logback</contextName>
|
||||
|
||||
<!-- 格式化 年-月-日 输出 -->
|
||||
<timestamp key="datetime" datePattern="yyyy-MM-dd"/>
|
||||
|
||||
<!--编码-->
|
||||
<property name="ENCODING" value="UTF-8"/>
|
||||
|
||||
<!-- 控制台日志 -->
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<!-- 临界值过滤器 -->
|
||||
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
|
||||
<level>INFO</level>
|
||||
</filter>
|
||||
<encoder>
|
||||
<pattern>%cyan([%thread %d{yyyy-MM-dd HH:mm:ss}]) %yellow(%-5level) %green(%logger{100}).%boldRed(%method)-%boldMagenta(%line)-%blue(%msg%n)
|
||||
</pattern>
|
||||
<charset>${ENCODING}</charset>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- 文件日志 -->
|
||||
<appender name="FILE" class="ch.qos.logback.core.FileAppender">
|
||||
<file>logs/${datetime}/financial-server.log</file>
|
||||
<append>true</append>
|
||||
<encoder>
|
||||
<pattern>%date{yyyy-MM-dd HH:mm:ss} [%-5level] %thread %file:%line %logger %msg%n</pattern>
|
||||
<charset>${ENCODING}</charset>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- 让SpringBoot内部日志ERROR级别 减少日志输出 -->
|
||||
<logger name="org.springframework" level="ERROR" additivity="false">
|
||||
<appender-ref ref="STOUT"/>
|
||||
</logger>
|
||||
|
||||
<!-- 让mybatis整合包日志ERROR 减少日志输出 -->
|
||||
<logger name="org.mybatis" level="ERROR" additivity="false">
|
||||
<appender-ref ref="STOUT"/>
|
||||
</logger>
|
||||
|
||||
<!-- 让ibatis 日志ERROR 减少日志输出 -->
|
||||
<logger name="org.apache.ibatis" level="ERROR" additivity="false">
|
||||
<appender-ref ref="STOUT"/>
|
||||
</logger>
|
||||
|
||||
<!-- 让 tomcat包打印日志 日志ERROR 减少日志输出 -->
|
||||
<logger name="org.apache" level="ERROR" additivity="false">
|
||||
<appender-ref ref="STOUT"/>
|
||||
</logger>
|
||||
|
||||
<!-- 我们自己开发的程序为DEBUG -->
|
||||
<logger name="cn.bunny" level="DEBUG" additivity="false">
|
||||
<appender-ref ref="STOUT"/>
|
||||
</logger>
|
||||
|
||||
<logger name="com.baomidou" level="ERROR" additivity="false">
|
||||
<appender-ref ref="STOUT"/>
|
||||
</logger>
|
||||
|
||||
<!-- 根日志记录器:INFO级别 -->
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE"/>
|
||||
<appender-ref ref="FILE"/>
|
||||
</root>
|
||||
|
||||
</configuration>
|
|
@ -0,0 +1,25 @@
|
|||
package cn.bunny.service.feign;
|
||||
|
||||
import cn.bunny.model.order.bean.LoginDto;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
|
||||
@SpringBootTest
|
||||
public class BunnyFeignClientTest {
|
||||
|
||||
@Autowired
|
||||
private BunnyFeignClient bunnyFeignClient;
|
||||
|
||||
@Test
|
||||
void test() {
|
||||
LoginDto loginDto = new LoginDto();
|
||||
loginDto.setUsername("bunny");
|
||||
loginDto.setPassword("admin123");
|
||||
loginDto.setType("default");
|
||||
String login = bunnyFeignClient.login(loginDto);
|
||||
|
||||
System.out.println(login);
|
||||
}
|
||||
|
||||
}
|
|
@ -3,6 +3,7 @@ package cn.bunny.service.controller;
|
|||
import cn.bunny.model.product.bean.Product;
|
||||
import cn.bunny.service.service.ProductService;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
|
@ -18,7 +19,14 @@ public class ProductController {
|
|||
|
||||
@Operation(summary = "根据id查询商品")
|
||||
@GetMapping("{id}")
|
||||
public Product getProduct(@PathVariable("id") Long productId) {
|
||||
public Product getProduct(@PathVariable("id") Long productId, HttpServletRequest request) {
|
||||
// try {
|
||||
// TimeUnit.SECONDS.sleep(6);
|
||||
// } catch (InterruptedException e) {
|
||||
// throw new RuntimeException(e);
|
||||
// }
|
||||
|
||||
System.out.println("request-X-Token: " + request.getHeader("X-Token"));
|
||||
return productService.getProductById(productId);
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue