Spring Cloud笔记-OpenFeign服务接口调用(九)

1.概述

Feign是一个声明式Web Service客户端,使用Feign能让编写Web Service客户端更加简单。

使用方法:定义一个服务接口,在上面添加注解。Feign还支持可插拔式的编码器和解码器。Spring Cloud对Feign进行了封装,使其支持Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用实现负载均衡。

之前,使用Ribbon+RestTemplate的时候,利用RestTemplate对Http请求的封装处理,形成了一套模板化的调用方法。但是在实际开发中,对于服务依赖的调用可能不止一处,往往一个接口被多处调用,通常,针对每个微服务自行封装一些客户端类来包装这些依赖服务的调用。所以,Feign在此基础上做了进一步封装,由它来帮助我们定义和实现依赖服务接口的定义。在Feign的实现下,我们只需要创建一个接口并使用注解的方式来配置它,类比于Mybatis中,Dao接口使用@Mapper注解一样,现在微服务接口上面使用一个Feign有关的注解,即可完成对服务提供方的接口绑定,简化了使用Spring Cloud Ribbon时,自动封装服务调用客户端的开发工作。

Feign集成了Ribbon,利用Ribbon维护服务列表信息,通过轮询方式实现客户端负载均衡,与Ribbon不同的是,通过Feign只需要定义服务绑定接口,以声明式的方法,优雅而简单的实现服务调用。

Feign和OpenFeign的对比
FeignOpenFeign

Feign是Spring Cloud组件中轻量级的RESTful风格的HTTP服务客户端。Feign内置了Ribbon,用来做客户端负载均衡,调用服务注册中心服务。Feign使用方法:使用Feign的注解定义接口,调用这个接口,就可以调用服务注册中心的服务。

OpenFeign是Spring Cloud在Feign基础上支持了SpringMVC的注解,如@RequestMapping等。OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用服务。

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-feign</artifactId>
</dependency>

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>

2.OpenFeign使用步骤

新建cloud-consumer-feign-order80模块,修改pom.xml,这里加入了spring-cloud-starter-openfeign组件。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>cloud2020</artifactId>
        <groupId>com.atguigu.springcloud</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>
    <artifactId>cloud-consumer-feign-order80</artifactId>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <dependency>
            <groupId>com.atguigu.springcloud</groupId>
            <artifactId>cloud-api-commons</artifactId>
            <version>${project.version}</version>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-actuator</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <scope>runtime</scope>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <optional>true</optional>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
    </dependencies>
</project>

添加application.yml。

server:
  port: 80
# 这里只把feign做客户端用,不注册进eureka
eureka:
  client:
    register-with-eureka: false # 表示是否将自己注册进EurekaServer默认为true
    service-url:
      # defaultZone: http://localhost:7001/eureka
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/

添加主启动类和@EnableFeignClients注解。

package com.atguigu.springcloud;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.openfeign.EnableFeignClients;

@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeignMain80.class, args);
    }
}

编写业务类,添加PaymentFeignService.java接口和OrderFeignController.java控制器。

package com.atguigu.springcloud.service;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

// value的值表示要访问哪个服务,也就是注册进Eureka的服务名称
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
    // 找到要调用的接口,把它的方法名及注解复制过来
    @GetMapping("/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}
package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentFeignService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
public class OrderFeignController {
    @Resource
    private PaymentFeignService paymentFeignService;

    @GetMapping("/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        return paymentFeignService.getPaymentById(id);
    }
}

我们访问cloud-consumer-feign-order80的/consumer/payment/get/id地址,因为我们在cloud-consumer-feign-order80中添加了@FeignClient注解的接口,Feign会根据@FeignClient上的value值,找到具体的服务,向它发送/payment/get/id的请求,从而实现远程调用。在使用感受上,好像是调用了cloud-consumer-feign-order80项目内部的一个业务一样,无需关心实现,也不用写RestTemplate了。

启动Eureka集群7001和7002,服务提供者8001和8001,服务消费者OrderFeignMain80。浏览器访问http://localhost/consumer/payment/get/1,一切正常,可以查询到数据,并且不断在8001和8002之间切换。

3.OpenFeign超时控制

为了测试超时控制,我们在服务提供者的模块,即8001和8002中,添加一个controller方法,方法体内Thread.sleep(3000);停留3秒钟返回。

@GetMapping("/payment/feign/timeout")
public String paymentFeignTimeout() throws InterruptedException {
    Thread.sleep(3000);
    return serverPort;
}

为了让cloud-consumer-feign-order80能调用到这个接口,需要将接口定义写在PaymentFeignService.java接口中。在OrderFeignController.java中加入映射地址,用于浏览器访问。

@GetMapping("/consumer/payment/feign/timeout")
public String paymentFeignTimeout() throws InterruptedException {
    return paymentFeignService.paymentFeignTimeout();
}

通过浏览器直接访问http://localhost:8001/payment/feign/timeout,等待3秒钟后,可以看到结果,通过浏览器访问http://localhost/consumer/payment/feign/timeout,发现页面报错了,提示Read time out。

因为,Feign默认连接超时为1秒,默认读取资源超时是1秒。如果需要修改超时时间,需要在yml里添加配置。

# 设置feign客户端超时时间,OpenFeign默认支持Ribbon
ribbon:
  ReadTimeout: 5000 # 建立连接后,读取资源所用时间
  ConnectTimeout: 5000 # 建立连接所用时间

Feign还支持请求级别的超时设置,参考地址:https://github.com/OpenFeign/feign/pull/970

如果我希望对某个请求单独设置超时时间,可以在Controller层传进去一个Request.Options的对象,在对象中分别指定两个时间,即可生效。它不影响你在yml里的配置,对于该请求,传参的方式会覆盖yml里的配置,其他请求继续按照yml里的配置进行超时设置。导包时候,注意Request是feign下的Request。

// service接口
@GetMapping("/payment/feign/timeout")
public String paymentFeignTimeout(Request.Options options) throws InterruptedException;

// controller控制器
@GetMapping("/consumer/payment/feign/timeout")
public String paymentFeignTimeout() throws InterruptedException {
    Request.Options options = new Request.Options(1000, 1000);
    return paymentFeignService.paymentFeignTimeout(options);
}

4.OpenFeign日志打印功能

Feign提供了日志打印功能,我们可以通过配置来调整日志级别,从而查看Feign中Http请求细节,对Feign接口调用进行监控。

日志级别:

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

需要添加一个日志配置类。

package com.atguigu.springcloud.config;

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FeignConfig {
    @Bean
    Logger.Level level() {
        return Logger.Level.FULL;
    }
}

在yml里指定监控哪个请求接口和监控级别。

logging:
  level:
    # 指定监控哪个接口,以及监控的级别
    com.atguigu.springcloud.service.PaymentFeignService: debug

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值