OpenFeign的简单介绍和快速使用

一、OpenFeign是什么?

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

二、OpenFeign的快速使用

(1)新建消费者maven项目cloud-consumer-feign-order80,并引入下面相关依赖

<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-client</artifactId>
        </dependency>
        <!--web-->
        <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>
 </dependencies>
    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Hoxton.SR10</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
    <!--在本地仓库找不到就到官网去找-->
    <repositories>
        <repository>
            <id>spring-milestones</id>
            <name>Spring Milestones</name>
            <url>https://repo.spring.io/libs-milestone</url>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
        </repository>
    </repositories>

(2)在配置文件添加下面信息

server.port=80

eureka.client.register-with-eureka=false
eureka.client.service-url.defaultZone=http://eureka7001:7001/eureka/,http://eureka7002:7002/eureka/

(3)主启动添加@EnableFeignClients

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);
    }
}

(4)创建业务类(逻辑层)
新建PaymentFeignService接口并新增注解@FeignClien
业务逻辑接口+@FeignClient配置调用provider服务

import com.lun.springcloud.entities.CommonResult;
import com.lun.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;

@Component//value为提供者应用名称
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService
{
    //==============注意这个路径是提供者的控制层的基准路径+方法上的路径
    //============同时注意@PathVariable形式的参数,则要用value=""标明对应的参数,否则会抛出IllegalStateException异常
    //=========同理在使用@RequestParam传递参数的时候,也要使用value属性指定名称,否则也会报错。

    @GetMapping(value = "/payment/get/{id}")//对应提供者方法路径
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);

}

(5)控制层Controller

import com.lun.springcloud.entities.CommonResult;
import com.lun.springcloud.entities.Payment;
import com.lun.springcloud.service.PaymentFeignService;
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 OrderFeignController
{
    @Resource
    private PaymentFeignService paymentFeignService;

    @GetMapping(value = "/consumer/payment/get/{id}")
    public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id)
    {   //调用逻辑层
        return paymentFeignService.getPaymentById(id);
    }
}

(6)测试
先启动2个eureka集群7001/7002
再启动2个微服务8001/8002
启动OpenFeign启动
http://localhost/consumer/payment/get/1
Feign自带负载均衡配置项

三、OpenFeign超时控制

(1)在消费者工程添加下面方法

@GetMapping(value = "/consumer/payment/feign/timeout")
    public String paymentFeignTimeout()
    {
        // OpenFeign客户端一般默认等待1秒钟
        return paymentFeignService.getPaymentById(id);
    }
}

(2)在提供者工程方法添加下面代码

Thread.sleep(3000);

(3)测试:
多次刷新http://localhost/consumer/payment/feign/timeout
将会跳出错误Spring Boot默认错误页面,主要异常:feign.RetryableException:Read timed out executing GET http://CLOUD-PAYMENT-SERVCE/payment/feign/timeout
OpenFeign默认等待1秒钟,超过后报错
可以在消费者工程配置文件里开启OpenFeign客户端超时控制

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

四、OpenFeign日志增强

(1)日志打印功能
就是对Feign接口的调用情况进行监控和输出
(2)日志级别

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

(3)在消费者工程配置日志bean

import feign.Logger;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class FeignConfig
{
    @Bean
    Logger.Level feignLoggerLevel()
    {
        return Logger.Level.FULL;
    }
}

(4)在消费者工程配置文件里需要开启日志的Feign客户端

# feign日志以什么级别监控哪个接口
#com.lun.springcloud.service.PaymentFeignService就是要进行监控的业务层的接口类全名
logging.level.com.lun.springcloud.service.PaymentFeignService=debug
Spring Cloud是一个为开发者提供了快速构建分布式系统的工具集,其中非常重要的一部分就是OpenFeignOpenFeign是一个声明式、模板化的HTTP客户端,它可以让开发者更加方便的调用HTTP接口。下面我们来详细了解一下Spring Cloud整合OpenFeign使用方式。 首先,我们需要在pom.xml文件中添加依赖,如下所示: ``` <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> <version>{版本号}</version> </dependency> ``` 然后,我们需要在启动类上添加@EnableFeignClients注解,表示开启Feign客户端自动配置。同时,我们还需要通过@FeignClient注解来定义接口。例如: ``` @FeignClient(name = "user-service") public interface UserFeignClient { @GetMapping("/user/findById") User findById(@RequestParam("id") Long id); } ``` 在上面的代码中,@FeignClient注解中的name属性表示调用的服务名,而接口中的findById方法就是定义的远程调用的接口。其中,@RequestParam注解表示使用@RequestParam方式传参。 最后,我们在业务代码中使用定义的接口即可。例如: ``` @RestController public class UserController { @Autowired private UserFeignClient userFeignClient; @GetMapping("/findUser") public User findUser(Long id) { return userFeignClient.findById(id); } } ``` 通过以上步骤,我们就可以方便地使用OpenFeign来调用HTTP接口,实现微服务之间的远程调用。整合OpenFeign有很多细节需要注意,例如如何处理调用异常、如何配置重试等等。但总体来说,Spring Cloud整合OpenFeign使用起来非常简单,是我们构建分布式系统的重要利器之一。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值