SpringCloud06-OpenFeign

SpringCloud06-OpenFeign

1.OpenFeign

  1. Ribbon+RestTemplate远程调用的缺点:服务之间的调用往往不止一处,一个接口会被多次调用,而Ribbon+RestTemplate没有形成统一的调用代码。
  2. Feign通过为服务绑定接口且以声明式的方式,优雅而简单的实现了服务调用。
  3. Feign的调用和Mybatis的实现机制相似,都是通过动态代理生成最终的调用方法。所以使用Feign进行远程调用,就像是在调用本地的接口一样。
  4. OpenFeign是SpringCloud社区对Feign的扩展,扩展了SpringMVC的注解的使用,如引入常用的@RequesMapping、@GetMapping等注解。
  5. OpenFeign源码地址。https://github.com/spring-cloud/spring-cloud-openfeign
  6. OpenFeign官网地址。https://docs.spring.io/spring-cloud-openfeign/docs/current/reference/html/

2.创建微服务cloud-eureka-consumer-open-feign-order80

  1. pom.xml
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
  1. yml
# 当前版本OpenFeign没有集成Ribbon,但是还有超时控制的功能,需要使用Feign进行配置。
feign:
  client:
    config:
      default:
        # 官方配置
        # 服务端处理请求的时间
        connectTimeout: 5000
        # 从建立连接到响应的时间
        readTimeout: 5000
  1. Main
@EnableEurekaClient
@EnableFeignClients
@SpringBootApplication
public class CloudEurekaConsumerOpenFeignOrder80Main {

    public static void main(String[] args) {
        SpringApplication.run(CloudEurekaConsumerOpenFeignOrder80Main.class, args);
    }
}
  1. controller
@RestController
public class PaymentController {

    @Resource
    private IPaymentService paymentService;


    @GetMapping(value = "/consumer/payment/get/{id}")
    CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        return paymentService.getPaymentById(id);
    }
}
  1. service,Feign远程调用接口。
/**
 * Feign远程调用接口。
 * 接口的请求方式和参数和远程controller保持一致。
 */
@FeignClient(value = "CLOUD-PROVIDER-PAYMENT")
public interface IPaymentService {

    @GetMapping(value = "/payment/get/{id}")
    CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);

    @GetMapping("/payment/get/outer")
    CommonResult<String> toBaiDu();

    @GetMapping(value = "/payment/time/out")
    String timeOut();
}

3.OpenFeign打印调用日志

  1. config配置。
@Configuration
public class OpenFeignConfig {

    @Bean
    public Logger.Level log() {
        return Logger.Level.FULL;
    }
}
  1. yml
logging:
  level:
    com.my.springcloud.service.IPaymentService: debug
  1. 日志级别。
    1. ONE,默认的,不显示任何日志。
    2. BASIC,仅记录请求方法、URL、响应状态码及执行时间。
    3. HEADERS,除了BASIC中定义的信息之外,还有请求和响应的头信息。
    4. FULL,除了HEADERS中定义的信息之外,还有请求和响应的正文及元数据。

4.OpenFeign负载均衡

  1. 当前版本的OpenFeign没有集成Ribbon,如何进行负载均衡?带更新......
posted @ 2021-10-07 19:54  行稳致远方  阅读(21)  评论(0)    收藏  举报