当前位置:网站首页>Openfeign service interface call
Openfeign service interface call
2022-07-04 08:16:00 【Meow xiansen likes fish】
One 、 summary
1.1 Feign Introduce
Feign yes Netflix Developed declarative , templated HTTP client , It's inspired by Retrofit,JAXRS-2.0 as well as WebSocket.
- Feign Can help us more convenient , Elegant call HTTP API.
- stay SpringCloud in , Use Feign It's simple —— Create an interface , And add some comments to the interface , The code is done .
- Feign Support multiple annotations , for example Feign Own notes or JAX-RS Annotations etc. .
- SpringCloud Yes Feign Enhanced , send Feign Support SpringMVC annotation , And integrated Ribbon and Eureka, So that Feign It is more convenient to use .
Official website :https://cloud.spring.io/spring-cloud-static/Hoxton.SR1/reference/htmlsingle/#spring-cloud-openfeign
GitHub:https://github.com/spring-cloud/spring-cloud-openfeign
1.2 Feign The role of
Feign Designed to make writing Java Http The client becomes easier .
In front of the use of Ribbon + RestTemplate when , utilize RestTemplate Yes Http Encapsulation processing of requests , It forms a set of template calling methods . But in actual development , Because there may be more than one call to the service , Often an interface is called in multiple places , So we usually encapsulate some client classes for each microservice to package the calls of these dependent services . therefore ,Feign On this basis, we make further encapsulation , It's up to him to help us define and implement the definition of the dependent service interface . stay Feign Under the realization of , We just need to create an interface and use annotations to configure it ( It used to be DAO Mark... On the interface @Mapper annotation , Now it's a microservice interface with a Feign Annotations can be ), You can complete the interface binding to the service provider , Simplified use SpringCloud Ribbon when , Development volume of auto encapsulation service calling client .
Feign Integrated Ribbon, utilize Ribbon Maintain the service list information of the service provider , And through polling to achieve the client load balancing . And with the Ribbon The difference is , adopt Feign Just define the service binding interface and use declarative methods , Elegant and simple implementation of service invocation .
1.3 Feign and OpenFeign The difference between
Feign | OpenFeign |
---|---|
Feign yes SpringCloud One of the lightweight components RESTful Of HTTP Service client .Feign Built in Ribbon, It is used for client load balancing , To call the service in the service registry .Feign Is used in the following way : Use Feign The annotation defines the interface , Call this interface , You can call the service in the service registry . | OpenFeign yes SpringCloud stay Feign Based on the support of SpringMVC Annotations @RequestMapping wait .OpenFeign Of @FeignClient Can be parsed SpringMVC Of @RequestMapping Interface under annotation , And through the way of dynamic proxy to produce the implementation class , Load balancing in the implementation class and calling other services . |
<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> |
Two 、 be based on OpenFeign Service call for
2.1 Introduce dependencies
<?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>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
<dependency>
<groupId>com.atguigu.springcloud</groupId>
<artifactId>cloud-api-commons</artifactId>
<version>1.0-SNAPSHOT</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.projectlombok</groupId>
<artifactId>lombok</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
</project>
2.2 To configure application.yml
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
2.3 Start the main class configuration , And add Feign Support for
@SpringBootApplication
@EnableFeignClients
public class OrderFeignMain80 {
public static void main(String[] args) {
SpringApplication.run(OrderFeignMain80.class, args);
}
}
adopt @EnableFeignClients
Annotations to open SpringCloud Feign Support functions of .
2.4 Start class activation FeignClient
Create a Feign Interface , This interface is in Feign The core interface for invoking microservices in .
In serving consumers cloud-consumer-feign-order80 Create a PaymentFeignService Interface and add comments @FeignClient
@Service
@FeignClient(name = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping(value = "/payment/get/{id}")
CommonResult<Payment> getPaymentById(@PathVariable("id") Long id);
}
- When defining the binding of each parameter ,@PathVariable、@RequestParam、@RequestHeader Parameter properties can be specified , stay Feign The binding parameter in must pass value Property to specify the specific parameter name , Otherwise, an exception will be thrown .
- @FeignClient Comments by name Specify the name of the micro service to be called , Used to create Ribbon Load balancer for . therefore Ribbon Will be able to CLOUD-PAYMENT-SERVICE Service resolved to registry .
2.5 Configure the calling interface of the request provider
@RestController
@Slf4j
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping("/consumer/payment/get/{id}")
public CommonResult<Payment> getPaymentById(@PathVariable("id") Long id){
return paymentFeignService.getPaymentById(id);
}
}
2.6 test
Start... First 2 individual eureka colony 7001/7002, Restart 2 Micro services 8001/8002, Finally start OpenFeign
visit http://localhost/consumer/payment/get/31
It can be seen that Feign Load balancing item with its own configuration .Feign Has been integrated in Ribbon Dependency and auto configuration , So we don't need to introduce additional dependencies , No need to register again RestTemplate object . in addition , If you want to modify Ribbon Configuration of , Can still pass ribbon.xx
For global configuration . It can also be done through service name .ribbon.xxx
To configure the specified service .
2.7 summary
3、 ... and 、Feign and Ribbon The connection of
Ribbon It's based on HTTP and TCP Load balancing tools for clients , It can be configured on the client side RibbonServerList( Server list ), Use HttpClient or RestTemplate simulation http request , The steps are rather tedious .
Feign Is in Ribbon Based on this, an improvement is made , It is more convenient to use HTTP client . Interface mode , Just create an interface , Then add comments on it , Define the methods of other services that need to be called as abstract methods , You don't need to build it yourself http request . When called, it is like calling the method of its own project , It doesn't feel like a remote method call , It makes it very easy to write the client .
Four 、 Timeout control
Feign When the client calls the server , The default waiting time for program execution is 1 Second , If timeout occurs, an error will be reported . But generally, the server processing may exceed 1 Second , To avoid that , We need to set Feign Timeout control of client .
4.1 When the demo is over
4.1.1 service provider 8001 and 8002 Add a pause program
Add the following code to 8001 and 8002 Of PaymentController Class :
@GetMapping("/payment/feign/timeout")
public String paymentFeignTimeOut(){
System.out.println("*****************paymentFeignTimeOut from serverPort:" + serverPort);
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e){
e.printStackTrace();
}
return serverPort;
}
4.1.2 Service consumer 80 Add timeout method
stay PaymentFeignService Add the following code to :
@Service
@FeignClient(value = "CLOUD-PAYMENT-SERVICE")
public interface PaymentFeignService {
@GetMapping(value = "/payment/feign/timeout")
String paymentFeignTimeOut();
}
stay OrderFeignController Add the following code to :
@RestController
@Slf4j
public class OrderFeignController {
@Resource
private PaymentFeignService paymentFeignService;
@GetMapping("/consumer/payment/feign/timeout")
public String paymentFeignTimeOut(){
return paymentFeignService.paymentFeignTimeOut();
}
}
4.1.3 test
visit http://localhost/consumer/payment/feign/timeout
4.2 Turn on timeout control
4.2.1 The first way
modify application.yml file , Add the following configuration
# Set up feign Client timeout (OpenFeign The default support ribbon )
ribbon:
# The time taken to establish a connection , It is suitable for normal network conditions , The time taken to connect the two ends
ReadTimeout: 5000
# It refers to the time taken to read the available resources from the server after the connection is established
ConnectTimeout: 5000
80 complete application.yml
server:
port: 80
eureka:
client:
register-with-eureka: false
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
# Set up feign Client timeout (OpenFeign The default support ribbon )
ribbon:
ReadTimeout: 5000 # The time taken to establish a connection , It is suitable for normal network conditions , The time taken to connect the two ends
ConnectionTimeout: 5000 # It refers to the time taken to read the available resources from the server after the connection is established
4.2.2 The second way :
modify application.yml file , Add the following configuration
feign:
client:
config:
CLOUD-PAYMENT-SERVICE:
readTimeout: 5000
connectTimeout: 5000
80 complete application.yml:
server:
port: 80
spring:
application:
name: cloud-feign-consumer
eureka:
client:
register-with-eureka: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
feign:
client:
config:
CLOUD-PAYMENT-SERVICE: # FeignClient The name of
readTimeout: 5000
connectTimeout: 5000
Restart after adding 80 To test :
4.3 Feign Other configurations for
from SpringCloud Edgware Start ,Feign Support the use of custom attributes Feign. For a named FeignClient( For example FeignClient For the name of the feignName),Feign The following configuration items are supported :
feign:
client:
config:
feignName: # Definition FeignClient The name of
readTimeout: 5000
connectTimeout: 5000
# To configure Feign Log level of , It's equivalent to Logger
loggerLevel: FULL
# Feign Error decoder for , It's equivalent to ErrorDecoder
errorDecoder: com.example.SimpleErrorDecoder
# Configuration retry , It's equivalent to Retryer
retryer: com.example.SimpleRetryer
# Configure interceptors , It's equivalent to RequestInterceptor
requestInterceptors:
- com.example.FooRequestInterceptor
- com.example.BarRequestInterceptor
decode404: false
- feignName:FeignClient The name of
- connectTimeout: The timeout for establishing a link
- readTimeout: Read timeout duration
- loggerLevel:Feign Log level of
- errorDecoder:Feign Error decoder for
- retryer: Configuration retry
- requestInterceptors: Add a request interceptor
- decode404: Configuration fusing is not handled 404 abnormal
4.4 Log printing function
In the development or operation phase, you often want to see Feign Logging of the request process , By default Feign Your log is not open . There are two ways to open : One is through configuration yml Mode on , The other is to enable through the configuration class .
4.4.1 To configure application.yml
If you want to use attribute configuration to achieve logging effect , Only need application.yml Add the following to :
feign:
client:
config:
CLOUD-PAYMENT-SERVICE: # Definition FeignClient The name of
# To configure Feign Log level of , It's equivalent to Logger
loggerLevel: FULL
logging:
level:
com.atguigu.springcloud.service.PaymentFeignService: debug
loggin.level.xx: debug
: feign At what level does the log monitor which interfacefeign.client.config.CLOUD_PAYMENT_SERVICE.loggerLevel
: To configure Feign Log level of .
Feign There are four logging levels :
- NONE【 Best performance , Suitable for production 】: Don't log anything ( The default value is )
- BASIC【 Applicable to production environment tracking problems 】: Only the request method is recorded 、URL、 Response status code and execution time
- HEADERS: Record BASIC Level based , Recording requests and responses header
- FULL【 It is more suitable for positioning problems in development and test environment 】: Recording requests and responses header、body And metadata .
complete application.yml
server:
port: 80
spring:
application:
name: cloud-feign-consumer
eureka:
client:
register-with-eureka: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
feign:
client:
config:
CLOUD-PAYMENT-SERVICE: # Definition FeignClient The name of
readTimeout: 5000
connectTimeout: 5000
# To configure Feign Log level of , It's equivalent to Logger
loggerLevel: FULL
logging:
level:
com.atguigu.springcloud.service.PaymentFeignService: debug
4.4.2 Configuration class
1、 Create configuration class
@Configuration
public class FeignConfig {
@Bean
public Logger.Level feignLoggerLevel(){
return Logger.Level.FULL;
}
}
2、yml The configuration file enables the logging function
logging:
level:
com.atguigu.springcloud.service.PaymentFeignService: debug
complete application.yml:
server:
port: 80
spring:
application:
name: cloud-feign-consumer
eureka:
client:
register-with-eureka: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/
# Set up feign Client timeout (OpenFeign The default support ribbon )
ribbon:
ReadTimeout: 5000 # The time taken to establish a connection , It is suitable for normal network conditions , The time taken to connect the two ends
ConnectionTimeout: 5000 # It refers to the time taken to read the available resources from the server after the connection is established
logging:
level:
com.atguigu.springcloud.service.PaymentFeignService: debug # feign At what level does the log monitor which interface
Start the test , visit http://localhost/consumer/payment/get/31
边栏推荐
- Set and modify the page address bar icon favicon ico
- 【Go基础】2 - Go基本语句
- How to get bytes containing null terminators from a string- c#
- 力扣今日题-1200. 最小绝对差
- DM8 database recovery based on point in time
- Cannot click button when method is running - C #
- Add log file to slim frame - PHP
- 1. Qt入门
- C#实现一个万物皆可排序的队列
- 一文了解数据异常值检测方法
猜你喜欢
Do you know about autorl in intensive learning? A summary of articles written by more than ten scholars including Oxford University and Google
The second session of the question swiping and punching activity -- solving the switching problem with recursion as the background (I)
Go h*ck yourself:online reconnaissance (online reconnaissance)
What does range mean in PHP
SQL注入测试工具之Sqli-labs下载安装重置数据库报错解决办法之一(#0{main}thrown in D:\Software\phpstudy_pro\WWW\sqli-labs-……)
Redis sentinel mechanism
墨者学院-phpMyAdmin后台文件包含分析溯源
JVM中堆概念
一文了解數據异常值檢測方法
弈柯莱生物冲刺科创板:年营收3.3亿 弘晖基金与淡马锡是股东
随机推荐
DM8 database recovery based on point in time
Leetcode 23. Merge K ascending linked lists
Leetcode(215)——数组中的第K个最大元素
Ecole bio rushes to the scientific innovation board: the annual revenue is 330million. Honghui fund and Temasek are shareholders
Preliminary study on temporal database incluxdb 2.2
Système de surveillance zabbix contenu de surveillance personnalisé
PCIE知识点-010:PCIE 热插拔资料从哪获取
DM8 uses different databases to archive and recover after multiple failures
How to use C language code to realize the addition and subtraction of complex numbers and output structure
[go basics] 1 - go go
Newh3c - routing protocol (RIP, OSPF)
Parallel shift does not provide any acceleration - C #
Activiti常見操作數據錶關系
运动【跑步 01】一个程序员的半马挑战:跑前准备+跑中调整+跑后恢复(经验分享)
Conversion of yolov5 XML dataset to VOC dataset
yolov5 xml数据集转换为VOC数据集
Devops Practice Guide - reading notes (long text alarm)
2022 gas examination registration and free gas examination questions
DM8 tablespace backup and recovery
Question 49: how to quickly determine the impact of IO latency on MySQL performance