当前位置:网站首页>Microservice - remote invocation (feign component)
Microservice - remote invocation (feign component)
2022-07-25 05:26:00 【Java world from scratch】
List of articles
1. Feign brief introduction
a RestTemplate comparison ,Feign Provide more elegant sending Http Requested function .
public Order queryOrderById(Long orderId) {
// 1. According to the order id Query order
Order order = orderMapper.findById(orderId);
//2. According to the user id Query user information
String url = "http://userserivce/user/" + order.getUserId(); // Will change , Without elegance .
// The remote invocation
User user = restTemplate.getForObject(url,User.class).var;
return order;
}
2. Use Feign Instead of RestTemplate
- Introduce dependency coordinates
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
- Open the annotation
@SpringCloudApplication
@EnableFeignClients // Turn on OpenFeign annotation
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
- Create an interface 、 Declare the path of the remote call
@FeignClient("userservice") //service id
public interface UserClient {
@GetMapping("/user/{id}")
User findById(@PathVariable("id") Long id);
}
- Use FeignClient The method defined in replaces RestTemplate
User user = userClient.findById(order.getUserId());
3. Feign To configure
| type | effect | explain |
|---|---|---|
| feign.Logger.Level | Modify log level | Contains four different levels :NONE、BASIC、HEADERS、FULL |
| feign.codec.Decoder | The parser that responds to the result | http Analyze the result of remote call , For example, parsing json String is java object |
| feign.codec.Encoder | Request parameter encoding | Encode the request parameters , Easy to pass http Request to send |
| feign. Contract | Supported annotation formats | The default is SpringMVC Annotations |
| feign. Retryer | Failure retry mechanism | Retry mechanism for request failure , The default is No , However, it will be used Ribbon Retry |
In general , The default value can meet our use , If you want to customize , Just create a custom @Bean Override default Bean that will do .
There are four levels of logs :
- NONE: No log information is recorded , This is the default .
- BASIC: Record only the requested method ,URL And the response status code and execution time
- HEADERS: stay BASIC On the basis of , Additionally, the request and response header information is recorded
- FULL: Record details of all requests and responses , Including header information 、 Request body 、 Metadata .
Mode one : The configuration file
Modify based on the configuration file feign Log level of :
feign:
client:
config:
userservice: # Configuration for a microservice
loggerLevel: FULL # The level of logging
feign:
client:
config:
default: # Here we use default Global configuration , If you write the service name , It is the configuration for a micro service
loggerLevel: FULL # The level of logging
4. Feign Use optimization
Feign Bottom layer initiation http request , Rely on other frameworks . Its underlying client implementation includes :
URLConnection: Default implementation , Connection pooling is not supported
Apache HttpClient : Support connection pool
OKHttp: Support connection pool
So improve Feign The main means of performance is to use Connection pool Instead of default URLConnection.
Use Apache HttpClient
- Introduce dependencies
<!--Apache HttpClient Dependence -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
- Configure connection pool
feign:
client:
config:
userservice: # Configuration for a microservice
loggerLevel: BASIC # The level of logging
httpclient: # Configure connection pool
enabled: true # Turn on feign Yes HttpClient Support for
max-connections: 200 # Maximum number of connections
max-connections-per-route: 50 # Maximum number of connections per path
take Feign The interface is drawn into a module
- Create a new module , Special preservation Feign Interface , Introduce dependencies
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
</dependencies>

2. Open annotation when using , Add scan path
@SpringCloudApplication
@EnableFeignClients(basePackages = {
"cn.xin.feign.clients"})
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
}
边栏推荐
- Oracle split branches
- Odoo14 | about the abnormal display of statusbar keyword after use and Its Solutions
- Game 302 of leetcode
- Airserver 7.3.0 Chinese version mobile device wireless transmission computer screen tool
- STL notes (IV): String
- ZTE's first 5g mobile phone, axon 10 pro, was launched in the first half of this year
- ThreadLocal
- 2022-07-24:以下go语言代码输出什么?A:[]int{};B:[]int(nil);C:panic;D:编译错误。 package main import ( “fmt“ ) f
- Execution process of NPM run XX
- Shenzhen on call test, subject 4 on call test, subject 3 theory, second theory on call test instructions
猜你喜欢

In depth understanding of pre post + +, -- and negative modulus

项目管理工具——项目开发者工具

Realsense D435i 深度图优化_高精度模式

Array programming problem of CSDN programming challenge

Thesis reading | which is the best multilingual pre training technology for machine translation? See the latest progress!

Panda3D keyboard moving scene

LeetCode 15:三数之和

AirServer 7.3.0中文版手机设备无线传送电脑屏幕工具
![2022-07-24: what is the output of the following go language code? A:[]int{}; B:[]int(nil); C:panic; D: Compilation error. package main import ( “fmt“ ) f](/img/bf/e38a8fd813f88a83f61a1abfa3b95d.png)
2022-07-24: what is the output of the following go language code? A:[]int{}; B:[]int(nil); C:panic; D: Compilation error. package main import ( “fmt“ ) f

Game 302 of leetcode
随机推荐
微服务 - Hystrix 熔断器
Event cycle mechanism browser nodejs async await execution sequence promise execution sequence interview questions
After Oracle user a deletes a table under user B's name, can user B recover the deleted table through the recycle bin?
Which side of Nacos has the SQL script of this column?
rhcsa暑假第三天
Matter's Unified Smart Home connection standard enables local automatic interaction between smart devices
DOM processing in ahooks
Sword finger offer special shock edition day 9
剑指offer专项突击版第9天
Delivery practice of private PAAS platform based on cloud native
Solve the problem that uni app applet obtains routes and route parameters
使用getifaddrs获取本机网口IP地址
VIM search and replacement and the use of regular expressions
批量下载视频小技巧
1310_ Implementation analysis of a printf
Game 302 of leetcode
Tips for downloading videos in batches
基环树入门
What should testers do if they encounter a bug that is difficult to reproduce?
VPP不能加载UP状态接口