当前位置:网站首页>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
边栏推荐
- Leetcode(215)——数组中的第K个最大元素
- Convert datetime string to datetime - C in the original time zone
- 1. Getting started with QT
- [go basics] 1 - go go
- 线性代数1.1
- Div hidden in IE 67 shows blank problem IE 8 is normal
- ES6 summary
- 2022 electrician (intermediate) examination question bank and electrician (intermediate) examination questions and analysis
- ZABBIX monitoring system deployment
- Activiti常見操作數據錶關系
猜你喜欢

墨者学院-phpMyAdmin后台文件包含分析溯源

Fault analysis | MySQL: unique key constraint failure

墨者学院-PHPMailer远程命令执行漏洞溯源

L1-027 rental (20 points)

ctfshow web255 web 256 web257
![[go basics] 2 - go basic sentences](/img/b1/961615b439d75679a3bb40a60f208d.png)
[go basics] 2 - go basic sentences
![Sports [running 01] a programmer's half horse challenge: preparation before running + adjustment during running + recovery after running (experience sharing)](/img/c8/39c394ca66348044834eb54c68c2a7.png)
Sports [running 01] a programmer's half horse challenge: preparation before running + adjustment during running + recovery after running (experience sharing)

Chrome is set to pure black

Famous blackmail software stops operation and releases decryption keys. Most hospital IOT devices have security vulnerabilities | global network security hotspot on February 14

Comprendre la méthode de détection des valeurs aberrantes des données
随机推荐
DM database password policy and login restriction settings
谷歌官方回应:我们没有放弃TensorFlow,未来与JAX并肩发展
L1-026 I love gplt (5 points)
[gurobi] establishment of simple model
Difference between static method and non static method (advantages / disadvantages)
SQL注入测试工具之Sqli-labs下载安装重置数据库报错解决办法之一(#0{main}thrown in D:\Software\phpstudy_pro\WWW\sqli-labs-……)
Ecole bio rushes to the scientific innovation board: the annual revenue is 330million. Honghui fund and Temasek are shareholders
@Role of requestparam annotation
Moher college phpMyAdmin background file contains analysis traceability
【Go基础】2 - Go基本语句
Comprendre la méthode de détection des valeurs aberrantes des données
[CV] Wu Enda machine learning course notes | Chapter 9
Using the rate package for data mining
Leetcode 23. Merge K ascending linked lists
弈柯莱生物冲刺科创板:年营收3.3亿 弘晖基金与淡马锡是股东
NewH3C——ACL
【性能測試】一文讀懂Jmeter
L1-024 the day after tomorrow (5 points)
Azure ad domain service (II) configure azure file share disk sharing for machines in the domain service
C # implements a queue in which everything can be sorted