OpenFeign
1. 简单使用
1.1 引入POM (消费端)
<!-- https://mvnrepository.com/artifact/org.springframework.cloud/spring-cloud-starter-openfeign -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
<version>4.0.2</version>
</dependency>
1.2 配置yaml(仅引入OpenFeign)
#这里没有集成注册中心,只需配置服务名即可,
server:
port: 80
spring:
application:
#服务名称
name: order-server
1.3 服务调用
1.3.1 服务提供端(接口)
@RequestMapping("payment")
@RestController
public class PaymentController {
@Autowired
PaymentService paymentService;
@GetMapping("hello")
public CommonResult hello(Payment payment)
{
return paymentService.create(payment);
}
}
1.3.2 服务消费端
- 添加主启动类注解
@SpringBootApplication
//开启feign
@EnableFeignClients
public class Order80Application {
public static void main(String[] args) {
SpringApplication.run(Order80Application.class,args);
}
}
- 声明接口服务
//value-微服务名称, url-服务地址(继承注册中心后,不再需要)
@FeignClient(value ="payment-server", url = "http://127.0.0.1:8001/")
public interface PaymentFeignService {
/**
* 这里的@GetMapping地址,与服务提供端匹配
*/
@GetMapping("payment/hello")
public CommonResult create(@SpringQueryMap Payment Payment);
}
2. 超时控制
yaml 配置
#OpenFeign配置
feign:
client:
config:
#默认超时配置,针对所有服务
default:
#读-超时时间 2s
read-timeout: 2000
#连接-超时时间 2s
connect-timeout: 2000
#服务名称,针对单个服务
PAYMENT-SERVER:
#读-超时时间 3s
read-timeout: 3000
#连接-超时时间 3s
connect-timeout: 3000
3. 日志增强
3.1 日志级别
- NONE: 默认,不显示任何日志;
- BASIC: 仅记录请求方法、URL、响应状态码及执行时间;
- HEADERS: 在basic基础上,增加请求和响应的头信息;
- FULL: 在headers基础上,增加请求和响应的正文及元数据。
3.2 配置日志
3.2.1 注入Bean
@Configuration
public class FeignConfig
{
@Bean
Logger.Level feignLoggerLevel()
{
return Logger.Level.FULL;
}
}
3.2.2 配置yaml 文件
logging:
level:
#举例, 接口: 日志级别
com.xxx.service.xxxService: debug