当前位置:网站首页>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 .
边栏推荐
- manjaro安装微信
- Sequence model
- 20220701 barbarat lemma proof
- Learn nuxt js
- Use Alibaba cloud NPM image acceleration
- How to re enable local connection when the network of laptop is disabled
- C#实现一个万物皆可排序的队列
- Awk from entry to earth (18) GAW K line manual
- DM database password policy and login restriction settings
- Technology sharing | MySQL parallel DDL
猜你喜欢

Snipaste convenient screenshot software, which can be copied on the screen

Ehrlich sieve + Euler sieve + interval sieve
![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

Question 49: how to quickly determine the impact of IO latency on MySQL performance

Educational Codeforces Round 119 (Rated for Div. 2)

High order phase difference such as smear caused by myopic surgery

Démarrage des microservices: passerelle

Relationship and operation of random events
![C language - Introduction - Foundation - syntax - [variable, constant light, scope] (V)](/img/dc/5c8077c10cdc7ad6e6f92dedfbe797.png)
C language - Introduction - Foundation - syntax - [variable, constant light, scope] (V)

L1 regularization and L2 regularization
随机推荐
awk从入门到入土(9)循环语句
Go zero micro service practical series (IX. ultimate optimization of seckill performance)
Codeforces Round #803 (Div. 2)(A-D)
C语言-入门-基础-语法-[变量,常亮,作用域](五)
Xcode 6 swift code completion does not work properly - Xcode 6 swift code completion not working
Codeforces Round #793 (Div. 2)(A-D)
@Role of pathvariable annotation
2022 examination questions for safety managers of metal and nonmetal mines (underground mines) and examination papers for safety managers of metal and nonmetal mines (underground mines)
C#,数值计算(Numerical Recipes in C#),线性代数方程的求解,Gauss-Jordan消去法,源代码
Internal learning
Industry depression has the advantages of industry depression
C, Numerical Recipes in C, solution of linear algebraic equations, Gauss Jordan elimination method, source code
Langage C - démarrer - base - syntaxe - [opérateur, conversion de type] (vi)
Flutter integrated amap_ flutter_ location
awk从入门到入土(8)数组
保姆级JDEC增删改查练习
How does Xiaobai buy a suitable notebook
How to send pictures to the server in the form of file stream through the upload control of antd
Awk from entry to earth (7) conditional statements
根据数字显示中文汉字