当前位置:网站首页>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 .
边栏推荐
- C语言-入门-基础-语法-数据类型(四)
- How to send pictures to the server in the form of file stream through the upload control of antd
- 转:优秀的管理者,关注的不是错误,而是优势
- Three paradigms of database design
- Awk from entry to earth (8) array
- 老掉牙的 synchronized 锁优化,一次给你讲清楚!
- go-zero微服务实战系列(九、极致优化秒杀性能)
- C#,数值计算(Numerical Recipes in C#),线性代数方程的求解,Gauss-Jordan消去法,源代码
- 上周热点回顾(6.27-7.3)
- ctfshow web255 web 256 web257
猜你喜欢
C language - Introduction - Foundation - syntax - [operators, type conversion] (6)
[CV] Wu Enda machine learning course notes | Chapter 9
DM database password policy and login restriction settings
Langage C - démarrer - base - syntaxe - [opérateur, conversion de type] (vi)
Horizon sunrise X3 PI (I) first boot details
Educational Codeforces Round 119 (Rated for Div. 2)
DM8 database recovery based on point in time
C语言-入门-基础-语法-[运算符,类型转换](六)
How to choose solid state hard disk and mechanical hard disk in computer
Codeforces Round #750 (Div. 2)(A,B,C,D,F1)
随机推荐
Educational Codeforces Round 119 (Rated for Div. 2)
How can we make a monthly income of more than 10000? We media people with low income come and have a look
[untitled] 2022 polymerization process analysis and polymerization process simulation examination
@Role of pathvariable annotation
Openfeign service interface call
Flutter 集成 amap_flutter_location
snipaste 方便的截图软件,可以复制在屏幕上
Comparison between sentinel and hystrix
Codeforces Round #793 (Div. 2)(A-D)
How to solve the problem of computer jam and slow down
Awk from entry to earth (15) awk executes external commands
Three paradigms of database design
如何通过antd的upload控件,将图片以文件流的形式发送给服务器
What sparks can applet container technology collide with IOT
DM8 uses different databases to archive and recover after multiple failures
awk从入门到入土(5)简单条件匹配
Talk about single case mode
Research Report on research and investment prospects of China's testing machine industry (2022 Edition)
Snipaste convenient screenshot software, which can be copied on the screen
ctfshow web255 web 256 web257