SpringCloud~~~【OpenFeign】

SpringCloud~~~【OpenFeign】

Feign是一个声明式的web服务客户端,让编写Web服务客户端变得非常容易,只需要创建一个接口并在接口上添加注解即可。

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-yCj3zRs0-1607913648886)(en-resource://database/2257:1)]

使用步骤

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-okBRjT2D-1607913648889)(en-resource://database/2265:1)]

  1. 新建服务
  2. POM
<!--openfeign-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  1. YML
server:
  port: 80

eureka:
  client:
    register-with-eureka: false
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
  1. 主启动类
@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain80 {
     public static void main(String[] args) {
         SpringApplication.run(OrderFeignMain80.class,args);
     }
}
  1. 业务类
    业务逻辑接口 + @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);
    }
}
  1. 测试
    [外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值