文章目录
前言
大致开始学习OnFeign
一、OpenFeign
Feign是一个声明式的Web服务客户端,让编写Web服务客户端变得非常容易,只需要创建一个接口并在接口上添加主键即可
二、使用步骤
1.引入库
代码如下(示例):
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
2.application.yml
server:
port: 80
spring:
application:
name: cloud-consumer-order
eureka:
instance:
instance-id: order80
prefer-ip-address: true
client:
register-with-eureka: false
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka
3.主启动类
@SpringBootApplication
@EnableFeignClients
public class OrderOpenFeignMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderOpenFeignMain80.class, args);
}
}
4.PaymentFeignService
@Component
//注册在Eureka上的服务名称(需要调用的服务模块的服务名:spring.application.name)
@FeignClient(value = "cloud-payment-service")
public interface PaymentFeignService {
//服务中暴露的控制器接口(需要调用的服务模块的控制器里的各种存在@RequestMapping的方法)
@GetMapping(value = "/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}
5.controller
@RestController
@Slf4j
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping(value = "/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id")Long id){
return paymentFeignService.getPaymentById(id);
}
}
三、超时控制
feign:
client:
config:
default:
#指的是建立连接后从服务器读取到可用资源所用的时间
readTimeout: 5000
#指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
connectTimeout: 5000
#ribbon:
# ConnectTimeout: 5000
# ReadTimeout: 5000
四、日志打印
对Feign接口的调用情况进行监控和输出
NONE:默认,不显示任何日志
BASIC:仅记录请求方法、URL、响应状态码及执行时间
HEADERS:除了BASIC中定义的信息之外,还有请求和响应的头信息
FULL:除了HEADERS中定义的信息之外,还有请求和响应的正文及元数据
1.FeignConfig
import feign.Logger;
@Configuration
public class FeignConfig {
@Bean
Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
2.application.yml
logging:
level:
#feign日志以什么级别监控哪个接口
com.sakanal.springcloud.service.PaymentFeignService: debug