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

你可能感兴趣的:(java)