当前位置:网站首页>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 .
边栏推荐
- ArcGIS应用(二十二)Arcmap加载激光雷达las格式数据
- Three paradigms of database design
- What should I do if there is a problem with the graphics card screen on the computer
- DM8 database recovery based on point in time
- Codeforces Round #803 (Div. 2)(A-D)
- Codeforces Round #793 (Div. 2)(A-D)
- L1 regularization and L2 regularization
- MySQL relearn 1-centos install mysql5.7
- [attack and defense world | WP] cat
- Live in a dream, only do things you don't say
猜你喜欢
C language - Introduction - Foundation - syntax - [variable, constant light, scope] (V)
埃氏筛+欧拉筛+区间筛
snipaste 方便的截图软件,可以复制在屏幕上
Industry depression has the advantages of industry depression
[error record] no matching function for call to 'cacheflush' cacheflush();)
MySQL relearn 1-centos install mysql5.7
到底什么才是DaaS数据即服务?别再被其他DaaS概念给误导了
go-zero微服务实战系列(九、极致优化秒杀性能)
Educational Codeforces Round 115 (Rated for Div. 2)
Four essential material websites for we media people to help you easily create popular models
随机推荐
Comparison between sentinel and hystrix
Call Baidu map to display the current position
微服務入門:Gateway網關
Famous blackmail software stops operation and releases decryption keys. Most hospital IOT devices have security vulnerabilities | global network security hotspot on February 14
Research Report on the current market situation and development prospects of calcium sulfate whiskers in China (2022 Edition)
Manjaro install wechat
How to pass custom object via intent in kotlin
广和通高性能4G/5G无线模组解决方案全面推动高效、低碳智能电网
Mouse over to change the transparency of web page image
FRP intranet penetration, reverse proxy
Industry depression has the advantages of industry depression
The basic syntax of mermaid in typera
09 softmax regression + loss function
Openfeign service interface call
Research Report on research and investment prospects of China's testing machine industry (2022 Edition)
How to re enable local connection when the network of laptop is disabled
What sparks can applet container technology collide with IOT
How college students choose suitable computers
Codeforces Round #793 (Div. 2)(A-D)
awk从入门到入土(14)awk输出重定向