当前位置:网站首页>06_ Service call feign
06_ Service call feign
2022-07-19 15:13:00 【Book opens autumn maple】
introduction
We used RestTemplate Realization REST API call , The code looks like this :
@GetMapping("/buy/{id}")
public Product order() {
Product product = restTemplate.getForObject("http://shop-service- product/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 . Then how to solve ? We take this question into the study of this chapter .
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 over a .
- 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 .
2. be based on Feign Service call for
2.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.2 Startup class add Feign Support for
adopt @EnableFeignClients Annotations to open Spring Cloud Feign Support functions of
@SpringBootApplication
@EnableFeignClients// Turn on feign function
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}2.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
@FeignClient(name = "shop-service-product")
public interface ProductFeginClient {
@RequestMapping("/shop-service-product/product/{id}")
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 .
2.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);
}
}2.5 Run the test
3. Feign and Ribbon contact
Ribbon It's based on HTTP and TCP client Load balancing tools . It can Configure... On the client side
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 parties Just do it , You don't need to build it yourself http request . Then it's like calling the method call of your own project , And I don't feel it's calling the remote party Law , It makes it very easy to write the client
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 For global configuration . It can also be done through service name .ribbon.xx To configure the specified service :
Start two shop_service_product , Retesting can reveal the use of Ribbon The polling strategy is used for load balancing
5. Feign Configuration of
from Spring Cloud Edgware Start ,Feign Support the use of custom attributes Feign. For a named Feign Client( For example Feign Client For the name of the feignName ),Feign The following configuration items are supported :
feign:
client:
config:
feignName: ## Definition FeginClient The name of
connectTimeout: 5000 # amount to Request.Options
readTimeout: 5000 # amount to Request.Options
loggerLevel: full # To configure Feign Log level of , It's equivalent to Logger
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
6. Request compression
Spring Cloud Feign Support for requests and responses GZIP Compress , To reduce the performance loss in the communication process . Through the following parameters You can turn on the compression function of request and response :
feign:
compression:
request:
enabled: true # Turn on request compression
response:
enabled: true # Turn on response compression meanwhile , We can also request the data type , And the lower limit of the size to trigger compression :
feign:
compression:
request:
enabled: true # Turn on request compression
mime-types: text/html,application/xml,application/json # Set compressed data type
min-request-size: 2048 # Set the lower size limit for triggering compression notes : Data type above 、 The lower limit of compression size is the default value .
7. 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:
shop-service-product:
loggerLevel: FULL
logging:
level:
com.suke.order.fegin.ProductFeginClient: debuglogging.level.xx : debug : Feign Log will only be used for log level debug In response
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 the quaternion According to the .

边栏推荐
- ICML2022 | 几何多模态对比表示学习
- Leetcode 1296. 划分数组为连续数字的集合(提供一种思路)
- A - Play on Words
- B树
- 模块1 作业
- Codeforces Round #807 (Div. 2) E. Mark and Professor Koro 二进制/线段树
- Cross domain and CORS
- 揭开服务网格~Istio Service Mesh神秘的面纱
- 3U VPX cooling conduction high performance srio/ Ethernet data exchange board
- [XSS range 10-14] insert when you see parameters: find hidden parameters and various attributes
猜你喜欢

Google Earth Engine——无人机影像进行分类处理

Wechat applet 8 cloud function

08_服务熔断Hystrix

Leetcode 1275. 找出井字棋的获胜者

A - Trees on the level(树的层序遍历)

BigScience 开源 Bloom 的自然语言处理模型

MMRotate从零开始训练自己的数据集

PCIe Cameralink signal generator (Cameralink image analog source)

UCAS. Deep learning Final examination questions and brief thinking analysis

SBOM (software bill of materials)
随机推荐
微信小程序8-云函数
模块1 作业
P1004 [noip2000 improvement group] grid access
csrf防护机制
买股票开户应该选哪个证券公司?什么证券公司是更安全的
5-21 interceptor
Li Hongyi machine learning 2022.07.15 -- error
UVA - 12096 The SetStack Computer
Leetcode 1275. 找出井字棋的获胜者
Google Earth Engine——无人机影像进行分类处理
Maximum heap and heap sort and priority queue
Achieve the effect of software login account by authorizing wechat ~ ~ unfinished
长安链学习研究-存储分析wal机制
A - Play on Words
天勤第九章课后习题代码
Unix ls
07_服务注册与发现总结
[XSS range 10-14] insert when you see parameters: find hidden parameters and various attributes
马走斜日(回溯法)
Icml2022 | geometric multimodal comparative representation learning