当前位置:网站首页>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 .
边栏推荐
- Research Report on research and investment prospects of China's testing machine industry (2022 Edition)
- C#,数值计算(Numerical Recipes in C#),线性代数方程的求解,Gauss-Jordan消去法,源代码
- Horizon sunrise X3 PI (I) first boot details
- @Role of pathvariable annotation
- What exactly is DAAS data as a service? Don't be misled by other DAAS concepts
- Flutter 集成 amap_flutter_location
- Leetcode topic [array] -136- numbers that appear only once
- 上周热点回顾(6.27-7.3)
- DM8 uses different databases to archive and recover after multiple failures
- Awk from entry to earth (12) awk can also write scripts to replace the shell
猜你喜欢

How to choose solid state hard disk and mechanical hard disk in computer

保姆级JDEC增删改查练习

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

How can we make a monthly income of more than 10000? We media people with low income come and have a look

DM8 uses different databases to archive and recover after multiple failures

Fault analysis | MySQL: unique key constraint failure

How college students choose suitable computers

转:优秀的管理者,关注的不是错误,而是优势

FOC control

Sequence model
随机推荐
awk从入门到入土(14)awk输出重定向
Redis sentinel mechanism
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)
Three paradigms of database design
AcWing 244. Enigmatic cow (tree array + binary search)
2022 electrician (intermediate) examination question bank and electrician (intermediate) examination questions and analysis
Relationship and operation of random events
微服務入門:Gateway網關
How can we make a monthly income of more than 10000? We media people with low income come and have a look
The upper layer route cannot Ping the lower layer route
Webapi interview question summary 01
C语言-入门-基础-语法-[标识符,关键字,分号,空格,注释,输入和输出](三)
Awk from entry to earth (18) GAW K line manual
Codeforces Round #750 (Div. 2)(A,B,C,D,F1)
CLion-控制台输出中文乱码
DM8 database recovery based on point in time
Codeforces Round #803 (Div. 2)(A-D)
Learn nuxt js
DM database password policy and login restriction settings
Talk about single case mode