SpringCloud~~~【OpenFeign】
Feign是一个声明式的web服务客户端,让编写Web服务客户端变得非常容易,只需要创建一个接口并在接口上添加注解即可。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yCj3zRs0-1607913648886)(en-resource://database/2257:1)]
使用步骤
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-okBRjT2D-1607913648889)(en-resource://database/2265:1)]
- 新建服务
- POM
<!--openfeign-->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- YML
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
- 主启动类
@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderFeignMain80.class,args);
}
}
- 业务类
业务逻辑接口 + @FeignClient配置调用provider服务
新建PaymentFeignService接口并新增注解@FeignClient
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping(value = "/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout();
}
控制层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);
}
}
- 测试
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gczSnFcs-1607913648894)(en-resource://database/2260:1)]
OpenFeign超时控制
OpenFeign默认等待1秒钟
需在yml中配置超时时间
#设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
#指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
ReadTimeout: 5000
#指的是建立连接后从服务器读取到可用资源所用的时间
ConnectTimeout: 5000
OpenFeign日志增强
日志Bean:
@Configuration
public class FeignConfig
{
@Bean
Logger.Level feignLoggerLevel()
{
return Logger.Level.FULL;
}
}
yml配置:
logging:
level:
# feign日志以什么级别监控哪个接口
com.maple.springcloud.service.PaymentFeignService: debug