Spring Cloud Hoxton.SR9版本(五)OpenFeign

1.什么是OpenFeign

    feign是一个声明式WebService客户端。使用Feign能让编写Web Service客户端更加简单。他的使用方法是定义一个服务接口然后在上面添加注解。Feign也支持可拔插式的编码器和解码器。SpringCloud对Feign进行了封装,使其支持了Spring MVC标准注解和HttpMessageConverters。Feign可以与Eureka和Ribbon组合使用以支持负载均衡。

2.Feign和OpenFeign的区别

区别
Feign OpenFeign

Feign是springcloud组件中的一个轻量级RESTFul的HTTP客户端,Feign内置了Ribbon,用来做客户端的负载均衡

去调用服务注册中心的服务。Feign的使用方式是:用Feign的注解定义接口,调用这个接口,就可以调用服务注册

中心的服务。

OpenFeign是springcloud在Feign的基础上支持了Spring MVC的注解,如@RequestMapping等等,OpenFeign的@FeignClient

可以解析Spring MVC的@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>

 

3.新建项目cloud-feign-consumer-8004

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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>2.3.5.RELEASE</version>
		<relativePath/> <!-- lookup parent from repository -->
	</parent>
	<groupId>com.yinuo</groupId>
	<artifactId>cloud-feign-consumer-8004</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<name>cloud-feign-consumer-8004</name>
	<description>Demo project for Spring Boot</description>

	<properties>
		<java.version>1.8</java.version>
		<spring-cloud.version>Hoxton.SR9</spring-cloud.version>
	</properties>

	<dependencies>
		<!--devtools热部署-->
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-devtools</artifactId>
			<optional>true</optional>
		</dependency>

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

	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework.cloud</groupId>
				<artifactId>spring-cloud-dependencies</artifactId>
				<version>${spring-cloud.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>

	<repositories>
		<repository>
			<id>spring-milestones</id>
			<name>Spring Milestones</name>
			<url>https://repo.spring.io/milestone</url>
		</repository>
	</repositories>

</project>

yml文件

server:
  port: 8004
spring:
  application:
    name: feign-consumer
  devtools:
    restart:
      enabled: true #开启热部署
eureka:
  client:
    fetchRegistry: true #是否从eurekaServer中抓取已有的注册信息,默认为ture,单节点无所谓,集群必须为ture才能配合ribbon使用负载均衡
    register-with-eureka: true #注册进eurekaServer
    service-url:
      defaultZone: http://eureka-8091:8091/eureka/,http://eureka-8092:8092/eureka/
  instance:
    instance-id: consumer-8004
    prefer-ip-address: true #显示IP地址



 

4.启动类增加@EnableFeignClients注解

package com.yinuo.consumer8004;

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

@SpringBootApplication
@EnableFeignClients
@EnableDiscoveryClient
public class CloudFeignConsumer8004Application {

	public static void main(String[] args) {
		SpringApplication.run(CloudFeignConsumer8004Application.class, args);
	}

}

5.编写feign调用的接口

package com.yinuo.consumer8004.service;

import org.springframework.cloud.openfeign.FeignClient;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

@Component
@FeignClient(value = "cloud-payment")//要调取的服务名
public interface FeignService {

    @RequestMapping("/get")//这是8001和8002的TestController里的get接口
    public String get();
}

 6.编写FeignTestController

package com.yinuo.consumer8004.controller;

import com.yinuo.consumer8004.service.FeignService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class FeignTestController {

    @Autowired
    private FeignService service;

    @GetMapping("consumer/get")
    public String get(){
        return service.get();
    }


}

 7.访问http://localhost:8004/consumer/get,可以看到访问成功,刷新两次可以看到已经是负载均衡了。

Spring Cloud Hoxton.SR9版本(五)OpenFeign

Spring Cloud Hoxton.SR9版本(五)OpenFeign

8.OpenFeign的超时设置。OpenFeign的默认超时时间是1秒钟,超过后会报错。8001和8002新增超时测试接口

package com.yinuo.payment8002.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@RestController
public class TestController {

    @Value("${server.port}")
    private String serverPort;

    @RequestMapping("/get")
    public String get(){
        return "I am from "+serverPort;
    }


    //测试OpenFeign超时接口
    @RequestMapping("/timeOut")
    public String timeOut(){
        try {
            TimeUnit.SECONDS.sleep(3);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return serverPort;
    }
}

 

9. cloud-feign-consumer-8004的FeignService增加超时接口调用

 @RequestMapping("/timeOut")
    public String timeOut();

 10.FeignTestController增加测试超时接口

 @RequestMapping("consumer/timeOut")
    public String timeOut(){
        return service.timeOut();
    }

11.访问http://localhost:8004/consumer/timeOut,会出现报错timeOut

Spring Cloud Hoxton.SR9版本(五)OpenFeign

12.yml配置,控制OpenFeign的超时时间

ribbon:
  ReadTimeout: 5000 #单位毫秒
  ConnecTimeout: 5000

 13.测试

Spring Cloud Hoxton.SR9版本(五)OpenFeign

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

       Feign的日志级别:

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

               BASIC:仅记录请求方法、URL、响应状态码及执行时间

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

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

15.8004项目创建FeignLogConfig配置类

package com.yinuo.consumer8004.config;

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

@Configuration
public class FeignLogConfig {

    @Bean
    Logger.Level feignLogLever(){
        return Logger.Level.FULL;
    }
}

16.8004项目配置yml,增加日志配置

logging:
  level:
    #监听日志的包名
    com.yinuo.consumer8004.service: debug

17.访问http://localhost:8004/consumer/get,查看后台日志

Spring Cloud Hoxton.SR9版本(五)OpenFeign

上一篇:Ribbon、Feign和OpenFeign的区别


下一篇:SpringCloud OpenFeign服务调用客户端介绍及配置使用