当前位置:网站首页>[microservice] microservice learning note 3: use feign to replace resttemplate to complete remote call
[microservice] microservice learning note 3: use feign to replace resttemplate to complete remote call
2022-07-19 15:00:00 【Driver Zhao Si】
Personal profile :
Personal home page : Driver Zhao Si
Direction of study :JAVA The backend development
The best time to plant a tree is ten years ago , The second is now !
The articles :SpringBoot Project integration wechat payment
🧡 If you like it, please pay a little attention , Your support is my biggest motivation .
Preface :
1. Based on Springboot The single project introduction of has been completed , As for the realization of other functions in the project, I'm not going to introduce them here , Because the knowledge involved is not difficult , And they are all simple CRUD operation , If you are interested, you can send me a private message. I'll see if I want to write a few articles to introduce .
2. Complete the previous stage of learning , I put myself into the study of microservices , The tutorials used are B The microservice tutorial of dark horse on the website . Because my memory is not very good , So for the study of new things, I prefer to take notes to enhance understanding , Here I will summarize the key contents of my notes and post them to “ Micro service learning ” In the notes column . I'm Zhao Si , A programmer with pursuit , I hope you can support me a lot , It would be better if you could give me some attention .
List of articles
One :🧸 Problem introduction
The previous introduction can be used RestTemplate To make a remote call , See the following code
// 2. utilize RestTemplate launch Http request , Query the user
//2.1 url route
String url = "http://userServer/user/" + order.getUserId();
//2.2 send out http request , Implement remote call
User user = restTemplate.getForObject(url,User.class);
But this method is also in the form of hard coding , There are two obvious problems , First, the readability of the code is very poor , Inconsistent programming experience ; Second, the parameters are complex URL Difficult to maintain .
Now Feign And that's what happened ,Feign It's a declarative one http client ( Official website address ), Its function is to help us achieve http Request to send , Solve the two problems mentioned above .
Two :🧸Feign Introduction configuration of
At the service provider's pom The file import Feign Client dependency
<!--feign Client dependency --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>Add comments to the startup class of the service consumer to start Feign The function of
@SpringBootApplication @EnableFeignClients // Turn on Feign function public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } /** * establish RestTemplate And injection Spring Containers */ @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }Write in service consumers Feign client
package cn.itcast.order.client; import cn.itcast.user.pojo.User; import org.springframework.cloud.openfeign.FeignClient; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; @FeignClient("userServer") public interface UserClient { @GetMapping("/user/{id}") User findById(@PathVariable("id") Long id); }Call in the service consumer Feign The client makes remote calls
/** * feign * @param orderId * @return */ public Order queryOrderById(Long orderId) { // 1. Query order Order order = orderMapper.findById(orderId); // 2. utilize Feign launch Http request , Query the user User user = userClient.findById(order.getUserId()); // 3. encapsulation user To Order order.setUser(user); // 4. return return order; }
3、 ... and :🧸 Customize Feign The level of logging
1. Mode one : Configuration file mode
Global effect
feign: client: config: default: # Fill in here default Global configuration , If you fill in the service name , It is to configure a specific micro service logger-level: basic # The level of loggingPartial effect
feign: client: config: userServer: # Fill in here default Global configuration , If you fill in the service name , It is to configure a specific micro service logger-level: basic # The level of logging
2. Mode two :java Code mode
Let me declare one Bean
package cn.itcast.order.config; import feign.Logger; import org.springframework.context.annotation.Bean; public class FeignClientConfig { @Bean public Logger.Level feignLogLevel() { return Logger.Level.BASIC; } }Global configuration
@MapperScan("cn.itcast.order.mapper") @SpringBootApplication @EnableFeignClients(defaultConfiguration = FeignClientProperties.FeignClientConfiguration.class) // Turn on Feign function public class OrderApplication { public static void main(String[] args) { SpringApplication.run(OrderApplication.class, args); } /** * establish RestTemplate And injection Spring Containers */ @Bean @LoadBalanced public RestTemplate restTemplate() { return new RestTemplate(); } }Local configuration
@FeignClient(value = "userServer", configuration = FeignClientProperties.FeignClientConfiguration.class) public interface UserClient { @GetMapping("/user/{id}") User findById(@PathVariable("id") Long id); }
Four :🧸Feign performance optimization
Feign The implementation of the underlying client mainly includes the following three :
- URLConnection: Default implementation , Connection pooling is not supported
- Apache HttpClient: Support connection pool
- OKHttp: Support connection pool
So optimize Feign The performance mainly includes :
- Use the connection pool instead of the default connection pool URLConnection
- The level of logging , Best use basic perhaps none
Use connection pooling for optimization
Introduce dependencies :
<!-- introduce HttpClient rely on --> <dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-httpclient</artifactId> </dependency>Configure connection pool :
feign: client: config: userServer: # Fill in here default Global configuration , If you fill in the service name , It is to configure a specific micro service logger-level: BASIC # The level of logging httpclient: enabled: true # Turn on feign Yes httpClient Support for max-connections: 200 # maximum connection max-connections-per-route: 50 # Maximum connections per path
5、 ... and :🧸 Best practice analysis
We noticed that , Service providers UserController Request interfaces and service consumers in UserClient The interface in is the same , See the code below
UserController
@GetMapping("/{orderId}")
public Order queryOrderByUserId(@PathVariable("orderId") Long orderId) {
// according to id Query the order and return
return orderService.queryOrderById(orderId);
}
UserClient
@FeignClient(value = "userServer")
public interface UserClient {
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}
Since the two are the same , So can we consider unifying this method? Who needs to call it directly when using it ? This can reduce a lot of code , The answer is yes , Through best practice ( Keep stepping on the pit and sum up ) There are two ways to solve the problem mentioned above , One is inheritance , The other is extraction .
1. Mode one : Inherit
Inheritance is for consumers FeignClient And provider's Controller Define a unified parent interface as a standard . Take the example above , We can package it into a API Interface , then UserClient Just inherit this API Interface ,UserController Just implement this interface , As shown in the figure below :
But there will be some problems in doing so ,Spring This is how it was introduced in : This is not recommended , Because doing so will cause tight coupling , And the method parameters are Spring MVC Is not acceptable , in other words Conroller The layer implements this API You should redefine the parameters when you interface .
2. Mode two : extract
Extraction is to FeignClient Extracted as a separate module , And the interface related POJO、 default Feign The configuration is put into this module , Available to all consumers , See the picture below :
Here is how to implement mode 2 :
Create a moudle, Name it feign-api, Then introduce the feign Of starter rely on

take order-service Writing in the UserClient、User、DefaultFeignConfig All copied to feign-api In the project

stay order-service Introduction in feign-api Dependence
<!-- introduce feign The unity of api--> <dependency> <groupId>cn.itcast.demo</groupId> <artifactId>feign-api</artifactId> <version>1.0</version> </dependency>modify order-service All related to the above three components in import part , Change to import feign-api In the package
package cn.itcast.order.service; import cn.itcast.feign.clients.UserClient; import cn.itcast.feign.pojo.User;Restart test

You can see the startup Order Error reported during service , The prompt message is that the instance object cannot be found , This is wrong ,UserClient It has been imported , It passed the compilation . It shows that this class does exist at this time , But this class cannot create objects , So in Spring The object cannot be found in the container . It turns out that when the method is not extracted, because the starting class scans its own package , It's also UserClient The bag where it is , So you can create objects , But after extraction UserClient Class in feign In bag ,OrderApplication This package was not scanned at startup , Therefore, the object cannot be created ,Spring This is not in the container Bean, Naturally, injection is unsuccessful .
There are two solutions , The first is to specify FeiginClient The bag where it is , namely :
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
@EnableFeignClients(basePackages = "cn.itcast.feign.clients") // Turn on Feign Function and specify scanning FeignClient The bag where it is
public class OrderApplication {
}
However, the above method is generally not recommended , Because the scanning range is relatively large , If client There are a lot of client, This method will put all client Take over , We can define which one we need more precisely client, Therefore, the following methods are recommended ( When multiple client You can add commas when you want to continue adding ):
@EnableFeignClients(clients = {
UserClient.class}) // Turn on Feign Function and specify scanning FeignClient Bytecode
public class OrderApplication {
}

You can see OrderApplication Start successfully
边栏推荐
- MySQL index (II)
- 兩種虛擬機的比較
- 2022 P gas cylinder filling examination practice questions simulated examination platform operation
- 暑期第三周总结
- ObjectARX -- implementation of custom circle
- 国科大.深度学习.期末复习知识点总结笔记
- 6U VPX high speed signal processing board based on ku115+mpsoc (xcku115 + zu9eg +dsp)
- 运行时加载 Objective-C
- The bill module of freeswitch
- Load Objective-C at runtime
猜你喜欢

PCIe Cameralink signal generator (Cameralink image analog source)

【MQTT从入门到提高系列 | 06】MQTT3.1.1之SUBSCRIBE订阅工作流

Sliding window maximum problem

Comparison of two virtual machines

csrf防护机制

DMA方式的特点

ICML2022 | 几何多模态对比表示学习
![[port 3000 is already in use, solution to the problem of 3000 port being occupied]](/img/6f/6c8fdbc6b0b2794433c97e77185111.png)
[port 3000 is already in use, solution to the problem of 3000 port being occupied]

Characteristics of DMA mode

1、DBMS基本概念
随机推荐
Use of token in ogg
数据填报、报表展示哪家强?亿信ABI给你答案
5-21 interceptor
[port 3000 is already in use, solution to the problem of 3000 port being occupied]
Alibaba microservice component Nacos registry
The first step of agile: turn "iteration" into "sprint" and start!
[mqtt from getting started to improving series | 06] subscribe subscription workflow of mqtt3.1.1
PCIe Cameralink signal generator (Cameralink image analog source)
抽象類與派生類
MySQL CPU使用率飙升,如何定位是被谁占用了
现场可程式化逻辑闸阵列 FPGA
Classification of blocks
An unforgettable day in 2022 summer camp
论文阅读 TEMPORAL GRAPH NETWORKS FOR DEEP LEARNING ON DYNAMIC GRAPHS
Field programmable logic gate array FPGA
Is it safe to buy funds in a securities account? I want to make a fixed investment in the fund
长安链学习研究-存储分析wal机制
Common built-in functions, iteratable objects, iterator objects, exception capture, purpose of exception capture, generator objects, modules, absolute and relative imports, package concepts, modules
现在网上办理基金开户,身份证信息安全吗?
009 execution sequence of SQL statement of interview questions