SpringCloud_OpenFeign服务接口调用

概述

Feign是一个声明式WebService客户端。使用Feign能让编写一个WebService客户端更加简单。使用方法是定义一个服务接口然后在上面添加注解。支持可插拔式的编码器和解码器。SpringCloud对Feign进行了封装,使其支持SpringMVC标准注解和HTTPMessageConverters。Feign可以与Eureka和Ribbon组合使用支持负载均衡。

使用步骤

  1. pom
 <!--openfeign-->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  1. yaml
server:
  port: 80

eureka:
  client:
    register-with-eureka: false
    fetch-registry: true
    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服务
@Component
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService
{
	/**
	*此接口对应provider服务中方法
	*/
    @GetMapping(value = "/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}
  1. 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);
    }
}

超时控制

OpenFeign默认等待1秒钟,超过后报错。但有时候服务端处理需要超过1s,为了避免报错。需要设置Feign客户端的超时控制。

#设置feign客户端超时时间(OpenFeign默认支持ribbon)
ribbon:
#指的是建立连接所用的时间,适用于网络状况正常的情况下,两端连接所用的时间
  ReadTimeout: 5000
#指的是建立连接后从服务器读取到可用资源所用的时间
  ConnectTimeout: 5000

日志打印

对Feign接口调用情况进行监控和输出

日志级别

  • NONE:默认,不显示任何日志
  • BASIC:仅记录请求方法、URL、响应状态码和执行时间
  • HEADERS:除了BASIC包含的内容,还包含请求和响应的头信息
  • FULL:除了HEADERS包含的内容,还包含请求和响应的正文及元数据

配置

@Configuration
public class FeignConfig
{
    @Bean
    Logger.Level feignLoggerLevel()
    {
        return Logger.Level.FULL;
    }
}
logging:
  level:
    # feign日志以什么级别监控哪个接口
    com.atguigu.springcloud.service.PaymentFeignService: debug

参考Demo

https://github.com/zzyybs/atguigu_spirngcloud2020

发布了417 篇原创文章 · 获赞 45 · 访问量 6万+

猜你喜欢

转载自blog.csdn.net/Chill_Lyn/article/details/105422058