SpringCloud(四)OpenFeign服务接口调用

写在前面:

  • 你好,欢迎你的阅读!
  • 我热爱技术,热爱分享,热爱生活, 我始终相信:技术是开源的,知识是共享的!
  • 博客里面的内容大部分均为原创,是自己日常的学习记录和总结,便于自己在后面的时间里回顾,当然也是希望可以分享自己的知识。目前的内容几乎是基础知识和技术入门,如果你觉得还可以的话不妨关注一下,我们共同进步!
  • 除了分享博客之外,也喜欢看书,写一点日常杂文和心情分享,如果你感兴趣,也可以关注关注!
  • 微信公众号:傲骄鹿先生

说明:

1、专栏涉及到的源码已经同步至 https://github.com/SetAlone/springcloud2020(持续更新)

2、springcloud系列博文内容为学习《尚硅谷2020最新版SpringCloud(H版&alibaba)框架开发教程》的记录,此系列课程是目前看来个人觉得非常不错的资源,在此可以与大家进行分享。

3、个人收集到了课程源码和所需的脑图、笔记等资源,如需要私信我即可。查找资源不易,希望可以给个点赞和关注

1、概述

1.1 什么是OpenFeign

官网地址:https://cloud.spring.io/spring-cloud-static/Hoxton.SR1/reference/htmlsingle/#spring-cloud-openfeign

Feign是一个声明性web服务客户端。它使编写web服务客户端变得更容易。使用Feign创建一个接口并对其进行注释。它有可插入的注释支持,包括外部注释和JAX-RS注释。Feign还支持可插入的编码器和解码器。Spring Cloud增加了对Spring MVC注释的支持,以及对使用Spring Web中默认使用的httpMessageConverter的支持。

Spring Cloud集成了Ribbon和Eureka以及Spring Cloud LoadBalancer,在使用Feign时提供了一个负载均衡的http客户端

他的使用方式是:定义一个服务接口,然后在上面添加注释;

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

github地址:https://github.com/spring-cloud/spring-cloud-openfeign

1.2 OpenFeign能干嘛

OpenFeign是集成了Feign的,Feign旨在使编写Java Http客户端变得更加容易;

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

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

1.3 OpenFeign和Feign的区别

OpenFeignFeign
OpenFeign是SpringCloud在Feign的基础上支持了SpringMVC的注解,如@RequestMapping等。OpenFeign的@FeignClient可以解析SpringMVC的@RequestMapping注解下的接口,并通过动态代理的方式产生实现类,实现类中做负载均衡并调用其他服务。Feign是SpringCloud组件中的一个轻量级RESTful的Http服务客户端,Feign内置了Ribbon,用来做客户端负载均衡,去调用服务注册中心的服务。Feign的使用方式是:使用Feign的注解定义接口,调用这个接口,就可以调用服务注册中心的服务。

 

 

 

 

2、OpenFeign的使用

微服务调用接口+@FeignClient,OpenFeign是在客户端使用的

2.1 创建cloud-consumer-openfeign-order80

2.2 改pom

<?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>
    <description>订单消费者之feign</description>

    <dependencies>
        <!--openfeign-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-openfeign</artifactId>
        </dependency>
        <!--eureka client-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-server</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.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>

 2.3 写yml

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

2.4 主启动

package com.atguigu.springcloud;

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


@SpringBootApplication
@EnableEurekaClient
@EnableFeignClients //开启OpenFeign的支持
public class OrderFeignMain80 {
    public static void main(String[] args) {
        SpringApplication.run(OrderFeignMain80.class, args);
    }
}
 
 

2.5 业务代码

2.5.1 @FeignClient修饰业务逻辑接口

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.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * OpenFeign的业务逻辑接口类,里面的方法和8001的paymentController的方法以及路径都是一样的
 */
@Component
@FeignClient(name = "CLOUD-PAYMENT-SERVICE") //指定要从哪个服务调用
public interface PaymentOpenFeignService {

    @PostMapping(value = "payment/create")
    public CommonResult create(@RequestBody Payment payment);

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

    @GetMapping(value = "/payment/lb")
    public String getPaymentLB();

}

2.5.2 controller编写

package com.atguigu.springcloud.controller;

import com.atguigu.springcloud.entities.CommonResult;
import com.atguigu.springcloud.entities.Payment;
import com.atguigu.springcloud.service.PaymentOpenFeignService;
import lombok.extern.slf4j.Slf4j;
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
@Slf4j
public class OrderOpenFeignController {

    @Resource
    PaymentOpenFeignService paymentOpenFeignService;

    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id) {
        System.out.println("===OpenFeign80服务被调用了,会去调用8001和8002的集群服务");
        return paymentOpenFeignService.get(id);
    }

}

2.6 测试

启动Eureka7001和7002,然后启动payment8001和8002,最后启动新创建的这个order80服务:

Feign自带负载均衡配置项,所以我们访问:http://localhost/consumer/payment/get/31 可以看到也是8001和8002交替出现,轮询的负载均衡机制已经得到了实现了。

3、OpenFeign超时控制

3.1 超时设置,故意设置超时演示出错情况

3.1.1 payment8001和payment8002的controller添加方法

在cloud-provider-payment8001和cloud-provider-payment8002的PaymentController中添加如下方法:

@GetMapping(value = "/payment/feign/timeout")
public String paymentFeignTimeout() {
    try {
        // 暂停3秒钟
        TimeUnit.SECONDS.sleep(3);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    return serverPort;
}

3.1.2 order80的OpenFeign接口添加方法

在cloud-consumer-openfeign-order80的PaymentOpenFeignService添加方法:

//模拟feign超时
@GetMapping(value = "/payment/feign/timeout")
String paymentFeignTimeout();

3.1.3 order80的controller添加方法

在cloud-consumer-openfeign-order80的OrderOpenFeignController添加方法:

@GetMapping(value = "/consumer/payment/feign/timeout")
public String paymentFeignTimeout() {
    // openfeign-ribbon, 客户端一般默认等待1秒钟
    return paymentOpenFeignService.paymentFeignTimeout();
}

3.2 测试

启动服务之后,浏览器访问:http://localhost/consumer/payment/feign/timeout ,会看到报错:

在这里插入图片描述

OpenFeign默认等待1秒钟,超过后报错而我们的8001和8002是延迟了3秒。导致客户端不想等待了,直接返回报错,为了避免这样的情况,有时候我们需要设置Feign客户端的超时时间。

3.3 设置Feign客户端的超时时间

修改cloud-consumer-openfeign-order80的application.yml,添加超时设置:

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

设置的超时时间的 5000,就是5秒。

3.4 重新测试

浏览器访问:http://localhost/consumer/payment/feign/timeout 在等待了3秒之后,成功了返回了,不会报错。

4、OpenFeign日志打印功能

4.1 概述

Feign提供了日志打印功能,我们可以通过配置来调整日志级别,从而了解Feign中Http的请求细节,说白了就是对Feign接口的调用情况进行监控和输出。

有以下日志级别:

  • NONE:默认的,不显示任何日志

  • BASIC:仅记录请求方法,URL,响应状态码以及响应时间

  • HEADERS:除了BASIC中定义的信息之外,还有请求和响应的头信息

  • FULL:除了HEADERS中定义的信息之外,还有请求和响应的正文和元数据

4.2 配置日志Bean

在cloud-consumer-openfeign-order80中新建一个配置类:OpenFeignConfig:

package com.atguigu.springcloud.config;

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

@Configuration
public class OpenFeignConfig {

    /**
     * feignClient配置日志级别
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        // 请求和响应的头信息,请求和响应的正文及元数据,注意Logger是feign.Logger
        return Logger.Level.FULL;
    }
}

4.3 yml中添加配置

在cloud-consumer-openfeign-order80的application.yml中,设置feign日志以什么级别监控哪个接口,logging是顶格写的。

logging:
  level:
    # 配置 feign日志以什么级别监控哪个接口
    com.atguigu.springcloud.service.PaymentOpenFeignService: debug

4.4 测试

启动之后,浏览器访问:http://localhost/consumer/payment/feign/timeout

看到控制台的打印信息:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

傲骄鹿先生

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值