当前位置:网站首页>Service call feign of "micro service"
Service call feign of "micro service"
2022-07-04 08:51:00 【Bulst】
List of articles
One 、feign summary
We used RestTemplate Realization REST API call , The code looks like this :
@GetMapping("/buy/{id}")
public Product order() {
Product product = restTemplate.getForObject("http://shop-serviceproduct/product/1", Product.class);
return product; }
From the code , We use concatenated strings to construct URL Of , The URL There is only one parameter . however , In reality ,URL It often contains multiple parameters . At this time, if we still construct in this way URL, Then it will be very painful .
1.1 Feign brief introduction
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 .
1.2 be based on Feign Service call for
(1) Introduce dependencies
In serving consumers shop_service_order add to Fegin rely on
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
(2) Startup class add Feign Support for
@SpringBootApplication(scanBasePackages="cn.itcast.order")
@EntityScan("cn.itcast.entity")
@EnableFeignClients
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
adopt @EnableFeignClients Annotations to open Spring Cloud Feign Support functions of
(3) Start class activation FeignClient
Create a Feign Interface , This interface is in Feign The core interface for invoking microservices in
In serving consumers shop_service_order Add one ProductFeginClient Interface
// Specify the name of the micro service to be called
@FeignClient(name="shop-service-product")
public interface ProductFeginClient {
// The requested path of the call
@RequestMapping(value = "/product/{id}",method = RequestMethod.GET)
public Product findById(@PathVariable("id") Long id);
}
- When defining the binding of each parameter ,@PathVariable、@RequestParam、@RequestHeader And so on, you can specify the parameter belongs to
sex , 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 shop-service-product Service resolved to registry .
(4) Configure the calling interface of the request provider
modify OrderController , add to ProductFeginClient Automatic injection , And in order Method used in ProductFeginClient Complete the microservice call
@RestController
@RequestMapping("/order")
public class OrderController {
@Autowired
private ProductFeginClient productFeginClient;
@GetMapping("/buy/{id}")
public Product order(@PathVariable Long id) {
return productFeginClient.findById(id);
}
}
(5) The test results
A successful call ~ No screenshots , The computer is too laggy.
1.3 Feign and Ribbon The connection of
Ribbon It's based on HTTP and TCP client Load balancing tools . It can On the client side To configure
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 . Then it's like calling the method call of your own project , It doesn't feel like a remote method call , It makes it very easy to write the client
1.4 Load balancing
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 , We can configure it as we did in the last lesson Ribbon, Can pass ribbon.xx Come on in
Row global configuration . It can also be done through service name .ribbon.xx To configure the specified service :
feign:
client:
config:
## Definition FeginClient The name of
service-product:
# amount to Request.Options
connect-timeout: 5000
# amount to Request.Options
readTimeout: 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
Start two shop_service_product , Retesting can reveal the use of Ribbon The polling strategy is used for load balancing .
Two 、Feign Advanced
2.1Feign Configuration of
from SpringCloudEdgware Start ,Feign Support the use of custom attributes Feign. For a named Feign Client( For example FeignClient For the name of the feignName),Feign The following configuration items are supported :
feign:
client:
config:
service-product:
# amount to Request.Options
connect-timeout: 5000
# amount to Request.Options
readTimeout: 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:FeginClient The name of
- connectTimeout: The timeout for establishing a link readTimeout: Read timeout duration
- loggerLevel:Fegin Log level of
- errorDecoder:Feign Error decoder for
- retryer: Configuration retry
- requestInterceptors: Add a request interceptor decode404: Configuration fusing is not handled 404 abnormal
2.2 Request compression
SpringCloudFeign Support for requests and responses GZIP Compress , To reduce the performance loss in the communication process . The compression function of request and response can be turned on through the following parameters :
feign:
compression:
request:
# Turn on request compression
enabled: true
response:
# Turn on response compression
enabled: true
meanwhile , We can also request the data type , And the lower limit of the size to trigger compression :
feign:
compression:
request:
# Turn on request compression
enabled: true
# Set compressed data type
mime-types: text/html,application/xml,application/json
# Set the lower size limit for triggering compression
min-request-size: 2048
notes : Data type above 、 The lower limit of compression size is the default value .
2.3 The level of logging
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 . If you want to use attribute configuration to achieve logging effect , Just in application.yml Add the following to :
feign:
client:
config:
service-product:
# amount to Request.Options
connect-timeout: 5000
# amount to Request.Options
readTimeout: 5000
# To configure Feign Log level of , It's equivalent to Logger
loggerLevel: full
logging:
level:
# Feign Log will only be used for log level debug In response
cn.itcast.order.fegin.ProductFeginClient: debug
feign.client.config.shop-service-product.loggerLevel: To configure Feign Log 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 .
边栏推荐
- 地平线 旭日X3 PI (一)首次开机细节
- DM8 command line installation and database creation
- Codeforces Global Round 21(A-E)
- What sparks can applet container technology collide with IOT
- Research Report on research and investment prospects of China's testing machine industry (2022 Edition)
- ArcGIS应用(二十二)Arcmap加载激光雷达las格式数据
- snipaste 方便的截图软件,可以复制在屏幕上
- Getting started with microservices: gateway gateway
- Awk from getting started to digging in (9) circular statement
- awk从入门到入土(6)正则匹配
猜你喜欢

MySQL relearn 1-centos install mysql5.7

Awk from entry to earth (12) awk can also write scripts to replace the shell
![Private collection project practice sharing [Yugong series] February 2022 U3D full stack class 007 - production and setting skybox resources](/img/f9/6c97697896cd1bd0f1d62542959f29.jpg)
Private collection project practice sharing [Yugong series] February 2022 U3D full stack class 007 - production and setting skybox resources

DM8 uses different databases to archive and recover after multiple failures
![C language - Introduction - Foundation - syntax - [operators, type conversion] (6)](/img/3f/4d8f4c77d9fde5dd3f53ef890ecfa8.png)
C language - Introduction - Foundation - syntax - [operators, type conversion] (6)

【无标题】转发最小二乘法

小程序容器技术与物联网 IoT 可以碰撞出什么样的火花

保姆级JDEC增删改查练习

What if I forget the router password

How to solve the problem that computers often flash
随机推荐
@Role of requestparam annotation
awk从入门到入土(6)正则匹配
HMS core helps baby bus show high-quality children's digital content to global developers
C语言-入门-基础-语法-[变量,常亮,作用域](五)
Cancel ctrl+alt+delete when starting up
std::is_ union,std::is_ class,std::integral_ constant
Educational Codeforces Round 115 (Rated for Div. 2)
DM8 command line installation and database creation
Awk from getting started to digging in (11) detailed explanation of awk getline function
[BSP video tutorial] stm32h7 video tutorial phase 5: MDK topic, system introduction to MDK debugging, AC5, AC6 compilers, RTE development environment and the role of various configuration items (2022-
How to re enable local connection when the network of laptop is disabled
What if I forget the router password
Codeforces Round #793 (Div. 2)(A-D)
Awk from getting started to digging in (4) user defined variables
上周热点回顾(6.27-7.3)
Getting started with microservices: gateway gateway
DM8 tablespace backup and recovery
Snipaste convenient screenshot software, which can be copied on the screen
Developers really review CSDN question and answer function, and there are many improvements~
学习Nuxt.js