当前位置:网站首页>Feign remote call and getaway gateway
Feign remote call and getaway gateway
2022-07-01 03:22:00 【Xiaobai wants to be a big cow】
Before we use RestTemplate When calling remotely , That's true :
There is a problem with it :
• Poor code readability , Inconsistent programming experience
• Complex parameters URL Difficult to maintain
Feign It's a declarative one http client , Official address :https://github.com/OpenFeign/feign
Its function is to help us achieve http Send request , Solve the problems mentioned above .
Feign: Send the request to the provider instead of the consumer , And accept the returned results
openfeign: SpringCloud Officially provided components
Feign Use steps
First step : Import dependence
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-openfeign</artifactId>
</dependency>
The second step : Add an annotation on the startup class to open Feign function
establish Feign The client of :
@FeignClient("userservice")
public interface UserFeignClient {
@GetMapping("/user/{id}")
User queryById(@PathVariable("id") Long id);
}
That is, the address of the representative is :http://userservice/user/id
in other words :@FeignClient("userservice")+GetMapping("/user/{id}") A link made up of the content inside
Then when we use it again, we can directly inject this class and call the methods of this layer to complete the remote call
Feign Custom configuration
Configuration file mode :
Modify based on the configuration file feign The log level can be for a single service :
If... Is configured in this project , So when we only have remote calls userservice Will promote this configuration .
feign:
client:
config:
userservice: # Configuration for a microservice
loggerLevel: FULL # The level of logging
Put that userservice If it is removed, the global configuration can be made according to the configuration , That is to say, if you configure , So when we call all of them remotely, this configuration will be triggered .
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
Use Java The code implements custom configuration
public class DefaultFeignConfiguration {
@Bean
public Logger.Level feignLogLevel(){
return Logger.Level.BASIC; // Log level is BASIC
}
}
If you want to Global effect , Put it in the... Of the startup class @EnableFeignClients In this note :
@MapperScan("cn.itcast.order.mapper")
@SpringBootApplication
// Enable global logging by configuring classes
@EnableFeignClients(defaultConfiguration = DefaultFeignConfiguration.class) // Turn on feign Client support
@EnableFeignClients // Turn on feign Client support
public class OrderApplication {
public static void main(String[] args) {
SpringApplication.run(OrderApplication.class, args);
}
//......
}
If it is Partial effect , Then put it in the corresponding @FeignClient In this note :
// Specify the service log configuration
@FeignClient(value = "userservice",configuration = DefaultFeignConfiguration.class)
@FeignClient(value = "userservice")
public interface UserFeignClient {
@GetMapping("/user/{id}")
User queryById(@PathVariable("id") Long id);
}
Feign Use optimization of :
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
In fact, it is Feign Remote call is still used RestTmplate, But by default URLConnection, Connection pooling is not supported , If we want to use connection pooling, we need to use HttpClient and OkHttp, These two support connection pooling
Feign Optimize the use steps
Introduce dependencies
<!--httpClient Dependence -->
<dependency>
<groupId>io.github.openfeign</groupId>
<artifactId>feign-httpclient</artifactId>
</dependency>
Configure connection pool
feign:
client:
config:
default: # default Global configuration
loggerLevel: BASIC # The level of logging ,BASIC Is the basic request and response information
httpclient:
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
Be careful : We are importing HttpClient The default will be directly replaced in the future , Even if it is not configured, it will be replaced , Personally, I think as long as I import HttpClient rely on bean Our factory has this example , that Feign You will find that this instance will be called first HttpClirnt, If neither of the two types with connectives has import dependency, then there is no instance ,Feign If no instance is found, the default
summary ,Feign The optimization of the :
Try to use the log level basic
2. Use HttpClient or OKHttp Instead of URLConnection
① introduce feign-httpClient rely on
② Profile on httpClient function , Set connection pool parameters
Feign Best practices
The so-called recent practice , Is the experience summarized in the process of use , The best way to use .
Careful observation shows that ,Feign Client and service provider controller The code is very similar :
Also is to feign Separate them separately to make one jar Package depends on importing our i In the project .
Gateway gateway
Gateway Gateway is the gatekeeper of our service , A unified portal for all microservices .
The gateway Core functional features :
Request routing
Access control
Current limiting
That is to say, all our clusters are called by the gateway , We just need to access the gateway , The gateway gives us load balancing , Visit for us
Access control : The gateway acts as a microservice portal , You need to verify whether the user is qualified to request , If not, intercept .
Routing and load balancing : All requests must go through first gateway, But the gateway doesn't handle business , But according to some rule , Forward the request to a micro service , This process is called routing . Of course, when there are multiple target services for routing , You also need to do load balancing .
Current limiting : When the request traffic is too high , In the gateway, the request is released at a speed acceptable to obscene microservices , Avoid excessive service pressure
getaway Gateway usage steps :
Introduce dependencies :
<!-- gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--nacos Service discovery depends on -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
Write routing rules :
server:
port: 10010 # Gateway port
spring:
application:
name: gateway # The service name
cloud:
nacos:
server-addr: localhost:80 # nacos Address
gateway:
routes: # Gateway routing configuration
- id: user-service # route id, Customize , As long as it's the only one
# uri: http://127.0.0.1:8081 # The destination address of the route http It's a fixed address
uri: lb://userservice # The destination address of the route lb It's load balancing , Followed by the service name
predicates: # Route assertion , That is, judge whether the request meets the conditions of routing rules
- Path=/user/** # This is matched according to the path , As long as /user/ Meet the requirements at the beginning
filters:
- AddRequestHeader=Truth, Itcast is freaking awesome! # Add the request header to the request, followed by the information , The tag of the request header is Truth The content is :Itcast is freaking awesome!
- id: order-service # route id, Customize , As long as it's the only one
# uri: http://127.0.0.1:8081 # The destination address of the route http It's a fixed address
uri: lb://orderservice # The destination address of the route lb It's load balancing , Followed by the service name
predicates: # Route assertion , That is, judge whether the request meets the conditions of routing rules There are many kinds of assertions , You can check it out
- Path= /** # This is matched according to the path , This is matching all
default-filters: # Default filter
# in other words , Like the one above id by user-service He has a designated request header , But their request is headed by key It's the same , Then use his own , But below order-service Is not specified , Then use the default
- AddRequestHeader=Truth, Itcast is freaking awesomedefault!
# ...
globalcors: # Global cross domain processing
add-to-simple-url-handler-mapping: true # solve options The request is blocked
corsConfigurations:
'[/**]':
allowedOrigins: # Allow cross domain requests for which websites
- "http://localhost:8090"
allowedMethods: # Allowed cross domain ajax Request method of
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # Header information allowed to be carried in the request
allowCredentials: true # Is it allowed to carry cookie
maxAge: 360000 # The validity period of this cross domain detection
There are two routes above :
One is
- Path=/user/**
The other one is
- Path= /**
When the second one is placed in the first position , Then no matter what we visit, there will be a problem , That is, the second path will be satisfied no matter what , At this time, you won't enter the first - Path=/user/**, Even with user Will also be blocked , If there is a common path, the sequence should be considered
The factory
The assertion rules we write in the configuration file are just strings , These strings will be Predicate Factory Read and process , The condition for changing to routing judgment
for example Path=/user/** Is to match according to the path , This rule is made by
org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory
Class toTo deal with the , Assertion factories like this are SpringCloudGateway There are more than a dozen
Routing filter
What is the function of the filter ?
① Process the routed request or response , For example, add request headers
② The filter configured under the route is only effective for the requests of the current route
defaultFilters What is the role of ?
① Filters in effect for all routes
Global filter
The gateway provides 31 Kind of , But the function of each filter is fixed . If we want to intercept the request , Doing your own business logic can't realize .
The global filter is also used to handle all requests and microservice responses entering the gateway , And GatewayFilter It does the same thing . The difference lies in GatewayFilter Defined by configuration , The processing logic is fixed ; and GlobalFilter You need to write your own code to implement your logic .
The definition is to implement GlobalFilter Interface .
Code implementation
@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 1. Get request parameters
MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
// 2. obtain authorization Parameters
String auth = params.getFirst("authorization");
// 3. check
if ("admin".equals(auth)) {
// release
return chain.filter(exchange);
}
// 4. Intercept
// 4.1. Blocking access , Set status code
exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
// 4.2. End processing
return exchange.getResponse().setComplete();
}
}
One of those order It is the execution sequence of our filter in the filter chain ,order The smaller the size, the higher the execution , If it is not specified, it is in the order of code from top to bottom
Filter execution order
The request to enter the gateway will encounter three types of filters : Filter for the current route 、DefaultFilter、GlobalFilter
After request routing , The current route filter and DefaultFilter、GlobalFilter, Merge into a filter chain ( aggregate ) in , After sorting, execute each filter in turn :
What are the sorting rules ?
Each filter must specify a int Type of order value ,order The smaller the value. , The higher the priority , The higher the order of execution .
GlobalFilter By implementing Ordered Interface , Or add @Order Note to specify order value , It's up to us to designate
Routing filters and defaultFilter Of order from Spring Appoint , The default is from... In the order of declaration 1 Increasing .
When the filter order When the value is the same , According to defaultFilter > Routing filter > GlobalFilter Sequential execution .
Cross-domain problem
In other words, if the content of a web page appears from two ports at the same time , So it's cross domain
agreement , domain name , If any one of the three ports is different, it is cross domain
Cross domain : Domain name inconsistency is cross domain , It mainly includes :
Domain name is different : www.taobao.com and www.taobao.org and www.jd.com and miaosha.jd.com
Domain name is the same , Different ports :localhost:8080 and localhost8081
Cross-domain problem : The browser prohibits cross domain communication between the initiator of the request and the server ajax request , The request is blocked by the browser
Solution :CORS, This should have been learned before , I won't repeat it here . If you don't know, you can check Cross-domain resource sharing CORS Detailed explanation - Ruan Yifeng's Weblog
Solving cross domain problems
stay gateway Service application.yml In file , Add the following configuration :
spring:
cloud:
gateway:
# ...
globalcors: # Global cross domain processing
add-to-simple-url-handler-mapping: true # solve options The request is blocked
corsConfigurations:
'[/**]':
allowedOrigins: # Allow cross domain requests for which websites
- "http://localhost:8090"
allowedMethods: # Allowed cross domain ajax Request method of
- "GET"
- "POST"
- "DELETE"
- "PUT"
- "OPTIONS"
allowedHeaders: "*" # Header information allowed to be carried in the request
allowCredentials: true # Is it allowed to carry cookie
maxAge: 360000 # The validity period of this cross domain detection
summary :
Nacos Components :
summary : alibaba One of the components provided
effect :
Nacos Registry Center
Nacos Configuration center
Be careful : nacos The registry and the configuration center have their own dependencies , Which leads which
install : install nacos, And start the
startup.cmd -m standalone
Nacos Registry Center :
Origin of the problem :
There is a hard coding problem when two microservices are called remotely
If you save the addresses of multiple microservices
How to monitor the health status of microservices
effect :
...
Content :
namespace:
group:
XxxService:
Disaster tolerance in other places :
Multiple instances of a service , Stored in different areas , Form different clusters
When microservices are invoked , Give priority to this cluster ( Nearby principle )
Use steps :
1. Import registry dependencies
2. To configure nacos The address of
When configuring a microservice cluster , You need to set priority to this cluster
Nacos Configuration center
Origin of the problem :
In a microservice cluster , Every micro service may have the same configuration , It's inconvenient to modify
effect :
Separate the configuration file from the microservice , Store in nacos in
When the microservice starts , from nacos Load the configuration file in , And use the configuration in the configuration file
Hot update of configuration file : 2 Kind of
Various writing methods in the configuration file :
service name - Environmental Science .yaml > service name .yaml > application.yaml
stay SpringBoot External and internal configuration ( The specified configuration is larger than the default configuration ) Greater than The internal configuration
Use steps :
0. stay nacos Write configuration files in
1. Import registry dependencies
2. To configure nacos
stay bootstrap.yml Configuration in file nacos Information about the configuration center
边栏推荐
- C#实现基于广度优先BFS求解无权图最短路径----完整程序展示
- Huawei operator level router configuration example | BGP VPLS and LDP VPLS interworking example
- C语言多线程编程入门学习笔记
- 咱就是说 随便整几千个表情包为我所用一下
- A few lines of transaction codes cost me 160000 yuan
- MySQL knowledge points
- Nacos
- [applet project development -- Jingdong Mall] classified navigation area of uni app
- [small program project development -- Jingdong Mall] the home page commodity floor of uni app
- shell脚本使用两个横杠接收外部参数
猜你喜欢
手把手带你了解一块电路板,从设计到制作(干货)
Completely solve the lost connection to MySQL server at 'reading initial communication packet
Multithreaded printing
8 pits of redis distributed lock
Latest interface automation interview questions
Redis分布式锁的8大坑
ctfshow爆破wp
岭回归和lasso回归
POI导出excel,按照父子节点进行分级显示
A few lines of transaction codes cost me 160000 yuan
随机推荐
C#实现图的深度优先遍历--非递归代码
Druid monitoring statistics source
调试定位导航遇到的问题总结
多元线性回归
[linear DP] shortest editing distance
Introduction to the core functions of webrtc -- an article to understand peerconnectionfactoryinterface rtcconfiguration peerconnectioninterface
EtherCAT简介
【EXSI】主机间传输文件
岭回归和lasso回归
【Qt】添加第三方库的知识补充
Introduction and basic knowledge of machine learning
POI导出excel,按照父子节点进行分级显示
JUC learning
So easy deploy program to server
Subnet division and subnet summary
监听器 Listener
Chapter 03_ User and authority management
手把手带你了解一块电路板,从设计到制作(干货)
leetcode 1818 绝对值,排序,二分法,最大值
Introduction and installation of Solr