当前位置:网站首页>Getting started with microservices (resttemplate, Eureka, Nacos, feign, gateway)
Getting started with microservices (resttemplate, Eureka, Nacos, feign, gateway)
2022-07-05 21:52:00 【Hesitant demon king】
List of articles
1. The framework is introduced
1.1 Monomer architecture
Basic introduction : Develop all the functions of the business in one project , Deploy as a package .
advantage : Simple architecture 、 Low deployment cost
shortcoming : High coupling degree
1.2 Distributed architecture
Basic introduction : Split the system according to the business function , Each business module is developed as an independent project , It's called a service .
advantage : Reduce service coupling 、 It is conducive to service upgrading and expansion
shortcoming : The architecture is complex 、 Difficulty
Problems to be considered in distributed architecture :
- What is the granularity of service splitting ?
- How to maintain the service cluster address ?
- How to realize remote call between services ?
- How to perceive the health status of services ?
1.3 Microservice architecture
Basic introduction : Microservices are well architected services Distributed Architecture .
features :
- Single responsibility : Microservices have smaller granularity , Each service corresponds to a unique business capability , Single responsibility , Avoid duplicate business development
- Service oriented : Microservices expose business interfaces
- autonomous : Team independence 、 Technology independence 、 Data independence 、 Deploy independent
- Strong isolation : Isolate service calls 、 Fault tolerance 、 Downgrade , Avoid cascading problems .
advantage : Smaller split granularity 、 The service is more independent 、 Less coupling
shortcoming : The architecture is very complex , Operation and maintenance 、 monitor 、 Deployment is more difficult
2. Get to know microservices
2.1 SpringCloud
SpringCloud It is the most widely used microservice framework in China . Official website address :https://spring.io/projects/spring-cloud
SpringCloud It integrates various micro service functional components , And based on SpringBoot The automatic assembly of these components is realized , This provides a good out of the box experience
- Service registration found :Eureka、Nacos、Consul
- Unified configuration management :SpringCloudConfig、Nacos
- Service remote invocation :OpenFegin、Dubbo
- Unified gateway routing :SpringCloudGateway、zuul
- Service link monitoring :Zipkin、Sleuth
- technological process 、 Downgrade 、 Protect :Hystix、Sentinel
SpringCloud And SpringBoot Version compatibility relationship :
Realesase Train( Version sequence ) Boot Version 2020.0.x aka Ilford 2.4.x Hoxton 2.2.x, 2.3.x Greenwich 2.1.x Finchley 2.0.x Edgware 1.5.x Dalston 1.5.x
2.2 Precautions for micro service splitting
- Different microservices , Don't develop the same business repeatedly
- Microservice data independence , Do not access databases of other microservices
- Microservices can expose their business as interfaces , For other microservices to call
2.3 Remote invocation mode of microservice
2.3.1 Providers and consumers
- Service providers : In a business , Services invoked by other microservices .( Provide interfaces to other microservices )
- Serving consumers : In a business , Call the services of other microservices .( Call interfaces provided by other microservices )
- A service can be both a provider and a consumer .
2.3.2 RestTemplate
Basic introduction :
When we need to call a remote HTTP Interface , We often use RestTemplate This class , This class is Spring Framework provides a tool class . It provides common REST Template of request scheme , for example GET request 、POST request 、PUT request 、DELETE Request and some general request execution methods exchange as well as execute.
Common methods :
Method | describe |
---|---|
getForObject | adopt GET Request response results |
getForEntity | adopt GET The request for ResponseEntity object , Including status code 、 Response header and response data |
headForHeaders | With HEAD Request resource returns all response header information |
postForLocation | use POST Request to create resource , And return the response field in the response data Location The data of |
postForObject | adopt POST Request to create resource , Get response results |
put | adopt PUT Request to create or update resources |
patchForObject | adopt PATH Request to update resources , And get the response result |
delete | adopt DELETE Request to delete resources |
optionsForAllow | adopt ALLOW Request to get all the access allowed by the resource HTTP Method , It can be used to view which request methods a request supports |
exchange | More through the version of the request processing method , Accept one RequestEntity object , You can set the path 、 Request header 、 Request information, etc , The last one to return ResponseEntity Entity |
execute | The most common execution HTTP Request method , All of the above methods are based on execute Encapsulation , Can fully control the requested information , And get the response data through the callback interface |
Easy to use :
First of all, will RestTemplate Inject in the configuration class ( The startup class also belongs to the configuration class , It can be used directly in the startup class
@Bean
For injection )adopt RestTemplate Object's
getForObject(url, Class<T> responseType)
Method , I can get through get Method sends corresponding requests to other microservices to obtain data .
RestTamplate Problems with remote calls :
- How can service consumers get the address information of service providers ?
- If there are multiple service providers , How consumers choose ?
- How consumers know the health status of service providers ?
- Poor code readability , Inconsistent programming experience
- Complex parameters URL Difficult to maintain
3. Eureka Registry Center
3.1 Basic introduction
stay Eureka In the frame , There are two types of microservice roles :
EurekaServer( Server side , Registry Center ): Used to record service information , Conduct heartbeat monitoring
EurekaClient( client ): Including service providers and consumers
- Service providers can register their own information to EurekaServer in , And every 30s towards EurekaServer Send a heartbeat
- Service consumers can choose from EurekaServer Pull the list of services , And do load balancing based on the service list , Select a microservice and initiate a remote call
Before proceeding to the next step , You need to introduce spring-cloud-dependencies
rely on
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>Hoxton.SR10</version>
<type>pom</type>
<scope>import</scope>
</dependency>
3.2 build EurekaServer
Create project , introduce
spring-cloud-starter-netflix-eureka-server
eureka The server depends on<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-server</artifactId> </dependency>
Edit startup class , add to
@EnableEurekaServer
annotation@SpringBootApplication @EnableEurekaServer public class EurekaApplication { public static void main(String[] args) { SpringApplication.run(EurekaApplication.class, args); } }
add to application.yml file , Write the following configuration :
server: port: 10086 # Service port spring: application: name: eurekaserver # eureka Service name of eureka: client: service-url: # eureka Address information for defaultZone: http://127.0.0.1:10086/eureka
configured eureka You can access the address information of eureka The status of the registry
3.3 Service registration
Introduce in the service to be registered
spring-cloud-starter-netflix-eureka-server
eureka Client dependency<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency>
stay application.yml Write the following configuration in the file :
server: port: 8080 # Service port spring: application: name: aservice # Sign up to eureka Service name in eureka: client: service-url: # To configure eureka Address information for defaultZone: http://127.0.0.1:10086/eureka
configured eureka You can view the address information registered to eureka Examples in
The above is the deployment of an instance of a service , If you want to deploy multiple instances , To avoid port conflicts , You need to modify the port configuration
Right click the service to deploy multiple , Click on Copy Configuration…
Modify the name of the configuration , And in VM options Add
-Dserver.port= New port number
But modify the configured port numberAfter starting the project , stay eureka You can see the registration center of aservice The service registers two instances
3.4 Service pull ( Including load balancing )
modify RestTemplate Of url route , Use the service name instead of ip And port number
stay RestTemplate Sign up to Spring Add
@LoadBalanced
Load balancing annotationStart project , adopt bservice Service access aservice Methods in services
4. Ribbon Load balancing
4.1 Load balancing process
Access directly through the browser http://aservice/say/dog It's not accessible , because aservice Not right ip And port number , And add the annotation of load balancing @LoadBalanced Annotations can intercept this request , stay eureka-server Find aservice Corresponding ip And port number , Finally, the requested data is returned .
add @LoadBalanced You can intercept , So who handled the interception ?
The request will be called LoadBalancerInterceptor The load balancing interceptor is blocked , It can get the hostname in the interception request , That is aservice, And give it to RibbonLoadBalancerClient.RibbonLoadBalancerClient I will give the service name to DynamicServerListLoadBalancer.DynamicServerListLoadBalancer It will come to eureka-server Get the service list of the corresponding service in and give it to IRule.IRule One of the services will be selected from the list of services based on rules , take ip And port number are returned to RibbonLoadBalancerClient.RibbonLoadBalancerClient The request will be modified to the correct address and sent , Finally get the data .
4.2 Load balancing strategy
Ribbon The load balancing rule of is called IRule Defined by the interface , Each of its sub interfaces is a rule
Built in load balancing rule class | Rule description |
---|---|
RoundRobinRule | Simply poll the list of services to select the server . It is Ribbon Default load balancing rules . |
WeightedResponseTimeRule | Give each server a weight . The longer the server response time , The less weight this server has . This rule randomly selects servers , But the weight value will affect the choice of the server . |
RandomRule | Randomly select an available server . |
RetryRule | The choice logic of retry mechanism . |
ZoneAvoidanceRule | Select servers based on servers available in the region . Use Zone Classify servers , This Zone It can be understood as a computer room 、 One rack . And then on Zone Polling multiple services in . |
AvailabilityFilteringRule | 1. By default , This server if 3 Secondary connection failed , It will be set to “ A short circuit ” state . The short circuit condition will continue 30s, If the connection fails again , The short-circuit time will increase geometrically .2. Servers with too many concurrent , If the AvailabilityFilteringRule The rules , The client will ignore it . |
Modify the load balancing rule method :
Define a new... Directly in the configuration class or startup class IRule( After the definition , The service invokes other micro services using the following rules )
// Change the rule to random selection @Bean public IRule randomRule(){ return new RandomRule(); }
stay application.yml In file , Add a new configuration ( After the configuration , This service will configure rules for the specified services to be scheduled )
aservice: # The name of the service to be dispatched ribbon: # Load balancing rules , Change the name of the load balancing class to be used NFLoadBalancerRuleClassName: com.netflix.loadbalancer.RandomRule
4.3 Hunger is loaded
Ribbon The default is lazy loading , That is, the first visit will create LoadBalanceCilent, The request took a long time . Hunger loading will be created when the project starts , Reduce the time-consuming of the first visit , Enable hungry loading through the following configuration :
ribbon:
eager-load:
enabled: true # Turn on hunger loading
clients: # Specify the service name to load
- aservice # Assign to aservice The service starts hungry loading
5. Nacos Registry Center
5.1 install Nacos
Nacos It's Alibaba's product , Now it is SpringCloud One of the components in , Compared with Eureka More features .
Nacos The installation method is as follows :
download Nacos Installation package , And decompress it ( Download at :https://github.com/alibaba/nacos/tags)
start-up Nacos( Go in and unzip. OK bin Catalog , Execute the following commands through the console )
# Stand alone start Nacos startup.cmd -m standalone
Console The following address is Nacos The console address of ,Ctrl + The left mouse button can directly open
Sign in Nacos( The default account and password are nacos), After successful login, you will jump to the console page
5.2 Service registration
Add... To the parent project
spring-cloud-alilbaba
Management dependency of :<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-alibaba-dependencies</artifactId> <version>2.2.5.RELEASE</version> <type>pom</type> <scope>import</scope> </dependency>
Add nacos Client dependency for :
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>
To configure application.yml file
spring: application: name: aservice # service name cloud: nacos: server-addr: localhost:8848 # nacos Service address
After running the project , The specified service will be registered to nacos in . stay nacos You can see the specific information on the console .
adopt RestTemplate You can register to nacos Scheduling services on .
5.3 Nacos Service hierarchical storage model
A service can be divided into multiple clusters , Each cluster can include multiple instances .
Cross cluster invocation of services :
Select the local cluster service as much as possible for service invocation , Cross cluster call latency is high . When the local cluster is not accessible , Then visit other clusters .
How to configure the cluster :
When we do not configure the cluster ,Nacos The cluster in is displayed as DEFAULT, That means there is no cluster
Can be in application.yml Edit the following configuration in the file , Configure the cluster
spring:
cloud:
nacos:
discovery:
cluster-name: CS # Cluster name
stay aservice The cluster name is set in the service CS Post start aservice Of 8080 example . And then modify it aservice The cluster name of is HZ And start the aservice Of 8082 example ,Nacos The cluster in will display the following results :
5.4 According to cluster load balancing
The above has been modified aservice Configuration of services , take aservice The two instances of are configured in two clusters respectively . But will bservice Set the cluster name to CS, When calling asevice Instance is not a priority call in the same cluster aservice example . This is because services are selected through load balancing rules when selecting instances , The default rule of load balancing is polling scheduling . Therefore, you want to prioritize the scheduling of instances in the same cluster , It is necessary to modify the rules of load balancing .
The modification method is as follows :
First set the cluster name of the dispatcher's service
Set load balancing in this service IRule by NacosRule, This rule gives priority to finding services in the same cluster as yourself ( It's just random scheduling in the same cluster )
aservice: # The name of the service to be dispatched ribbon: NFLoadBalancerRuleClassName: com.alibaba.cloud.nacos.ribbon.NacosRule # Load balancing rules
5.5 Load balancing according to weight
Nacos Weight configuration is provided to control the access frequency of instances , The greater the weight, the greater the frequency of access .
Application scenarios :
Set more weights for machines with good performance , Set the machine with poor performance with less weight .
The modification method is as follows :
stay Nacos The console can set the weight value of the instance , First click the Edit button of the instance
Modify the weight to the value you want ( Weight value in 0~1 Between ,0 It means that it will not be accessed )
5.6 Environmental isolation namespace
Nacos The outermost layer of both service storage and data storage in is called namespace Things that are , Used for the outermost isolation . Every namespace There is only one ID, Different namespace The service under is invisible .
stay Nacos We can see the console , Our registered instances are stored by default in a file called public In the namespace of
How to configure the new namespace :
stay Nacos Create a new namespace on the console
When it's created , You can see the newly created namespace in the service list .
Modify service's application.yml file , Add the following configuration :
spring: cloud: nacos: discovery: namespace: a6fedd4e-c8fc-4695-b5d1-60bf72205819 # Namespace ID
Restart the service
5.7 Temporary and non temporary instances
Nacos Support the server to actively detect the provider status : The temporary instance adopts heartbeat mode , Active detection mode is adopted for non temporary instances . The default is temporary instance .
Configure non temporary instance mode :
spring:
cloud:
nacos:
discovery:
ephemeral: false # Set non temporary instances
5.8 Nacos and Eureka The difference between
Common ground :
- Both support service registration and service pull
- All support service providers' heartbeat for health detection
difference :
- Nacos Support the server to actively detect the provider status : The temporary instance adopts heartbeat mode , Active detection mode is adopted for non temporary instances .
- Temporary abnormal heartbeat will be eliminated , Non temporary instances will not be rejected .
- Nacos Support the message push mode of service list change , The service list is updated more timely .
- Nacos The cluster adopts... By default AP Pattern , When there are non temporary instances in the cluster , use CP Pattern ;Eureka use AP Pattern
6. Nacos Configuration Management
6.1 Nacos Configuration management
stay Nacos Add configuration information to the console
Fill in the configuration information in the pop-up form
6.2 Micro service acquisition Nacos Configuration in
When only local configuration files are read , Steps are as follows :
When you need to read nacos Configuration files in the console , Steps are as follows :
introduce Nacos The configuration management client depends on
<dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId> </dependency>
In service resources Add a
bootstrap.yml
file ( This file is the boot file , Priority over application.yml)spring: application: name: aservice # The service name ( And nacos The console configuration file name corresponds to ) profiles: active: dev # development environment , Here is dev( And nacos The console configuration file name corresponds to ) cloud: nacos: server-addr: localhost:8848 # Nacos Address config: file-extension: yaml # File suffix ( And nacos The console configuration file name corresponds to )
6.3 Configure hot update
Nacos After the configuration file in is changed , Microservices can sense... Without restarting . However, it needs to be implemented through the following two configurations :
Mode one : stay
@Value
Add an annotation on the class where the injected variable is located@RefreshScope
@Value
The function of this annotation is to read out the properties of the configuration file , Yes@Value("${}")
and@Value("#{}")
Two waysMode two : Use
@ConfigurationProperties
annotationThe above example will read all the configuration files with pattern The properties of the beginning , And on and on bean To match fields in .
6.4 Priority of multiple configurations
Microservices from nacos When reading the configuration file, two configurations will be read :
[ service name ]-[spring.profile.active].yaml
Environment configuration[ service name ].yaml
The default configuration , Multi environment sharing
priority :
nacos Current environment configuration in ( service name - Environmental Science .yaml)> nacos Share configuration in ( service name .yaml)> Local configuration
7. HTTP client Feign
7.1 Definition and use Feign
Basic introduction :
Feign It's a declarative one HTTP client , It can help us achieve HTTP Send request . Official address :https://github.com/OpenFeign/feign
Use Feign Steps are as follows :
Introduce dependencies :
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-openfeign</artifactId> </dependency>
Add
@EnableFeignClients
Annotations to open Feign The function of :@SpringBootApplication @EnableFeignClients public class BApplication { public static void main(String[] args) { SpringApplication.run(BApplication.class, args); } }
To write FeignClient Interface :
@FeignClient("aservice") // Microservices to be scheduled public interface AClient { // This interface contains and aservice Many of the services need scheduling methods @GetMapping("say/dog") public String dogSay(); }
Use the written FeignClient The method defined in
@RestController @RequestMapping("b") public class BController { @Autowired private AClient aClient; @GetMapping("say") public String bSay(){ return aClient.dogSay(); } }
7.2 Customize Feign Configuration of
Feign Run custom configuration to override the default configuration , The configuration that can be modified is as follows :
type | effect | explain |
---|---|---|
feign.Logger.Level | Modify log level | Contains four different levels :NONE( Default )、BASIC、HEADERS、FULL |
feign.coder.Decoder | The parser that responds to the result | HTTP Analyze the result of remote call , For example, parsing json String is java object |
feign.coder.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 |
To configure Feign There are two ways to log :
Mode one : Configuration file mode
Global effect
feign: client: config: default: # default Represents global configuration , That is, the following configurations are made for all scheduled microservices loggerLevel: Full # The level of logging
Partial effect
feign: client: config: aservice: # Specific service name , Configure a micro service to be scheduled loggerLevel: Full # The level of logging
Mode two :java Code mode , You need to declare a Bean
public class FeignClientConfiguration{ @Bean public Logger.Level feignLogLevel(){ return Logger.Level.BASIC; } }
Then, if it is a global configuration , Then put it in
@EnableFeignClients
In this note@EnableFeignClients(defaultConfiguration = FeignClientConfiguration.class);
In case of local configuration , Then put it in
@FeignClient
In this note@FeignClient(value = "aservice", configuration = FeignClientConfiguration.class);
7.3 Feign Performance optimization
Feign The underlying client implementation :
- URLConnection: Default implementation , Connection pooling is not supported
- Apache HttpClient: Support connection pool
- OKHttp: Support connection pool
Optimize Feign The performance mainly includes :
- Use the connection pool instead of the default connection pool URLConnection, It can reduce the performance loss of connection creation and destruction
- Log level is best used basic or none, If the level is low, the performance is higher
Feign add to HttpClient The way to support :
Introduce dependencies
<dependency> <groupId>io.github.openfeign</groupId> <artifactId>feign-httpclient</artifactId> </dependency>
Configure connection pool :
feign: httpclient: enabled: true # Turn on feign Yes httpClient Support for max-connections: 200 # maximum connection max-connections-per-route: 50 # Maximum number of connections per path
7.4 Feign The best realization of
Mode one ( Inherit ): For consumers FeignClient And provider's controller Define a unified parent interface as a standard
Mode two ( extract ):
First create a module, Name it feign-api, Then introduce the feign Of starter rely on
stay feign-api Write the provider's FeignClient、POJO and Feign Default configuration
Introduce feign-api Dependence
Restart project
When defined FeignClient be not in SpringBootApplication When scanning the package range of , these FeignClient Can't use . There are two ways to solve :
Mode one : Appoint FeignClient Location package
@EnableFeignClients(basePackages = "com.mmr.feign.clients")
Mode two : Appoint FeignClient Bytecode
@EnableFeignClients(clients = { AClient.class})
8. Unified gateway Gateway
8.1 Know the gateway
Function of gateway :
- Perform identity authentication and authority verification on user requests
- Route user requests to microservices , And load balancing
- Limit the current of user requests
Technical implementation of gateway : stay SpringCloud The implementation of gateway in includes two methods
- gateway
- zuul
Zuul Is based on Servlet The implementation of the , It belongs to blocking programming . and SpringCloudGateway Is based on Spring5 Provided in WebFlux, It belongs to the implementation of responsive programming , Better performance .
8.2 Build gateway service
Steps of building gateway server :
Create a new module, introduce SpringCloudGateway and nacos Service discovery depends on
<!-- Gateway depends on --> <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 configuration and nacos Address
server: port: 10010 # Gateway port spring: application: name: gateway # The service name cloud: nacos: server-addr: localhost:8848 # nacos Address gateway: routes: # Gateway routing configuration - id: a-service # route id, Customize , only uri: lb://aservice # The destination address of the route ,lb Represents load balancing , Followed by the service name predicates: # Route assertion , It is used to judge whether the request meets the conditions of routing rules - Path=/a/** # Path matching , As long as it is with /a/ Meet the requirements at the beginning
8.3 Route assertion factory Route Predicate Factory
Gateway routing can be configured as follows :
- route id: Route unique identification
- uri: The destination of the route , Support lb and http Two kinds of
- predicates: Route assertion , Determine whether the request meets the requirements , If yes, it will be forwarded to the routing destination , If not, skip the rule
- filters: Routing filter , Process a request or response
Route assertion factory Route Predicate Factory The role of :
The assertion rules written in the configuration file are just strings , These strings will be Predicate Factory Read and process , The condition for changing to routing judgment .
Spring Provides 11 Species basic Predicate factory :
name | explain | Example |
---|---|---|
After | It's a request after a certain point in time | - After=2037-01-20T17:42:47.789-07:00[America/Denver] |
Before | It's a request before a certain point in time | - Before=2037-04-13T15:42:47.433+07:00[Asia/Shanghai] |
Between | It's a request before two points in time | - Between=2037-01-20T17:42:47.789-07[America/Denver],2037-04-13T15:42:47.433+07:00[America/Denver] |
Cookie | The request must contain some cookie | - Cookie=chocolate,ch.p |
Header | The request must contain some header | - Header-X-Request-Id,\d+ |
Host | The request must be to access a host( domain name ) | - Host=**.somehost.org, * *.anotherhost.org |
Method | The request method must be the specified method | - Method=GET,POST |
Path | The request path must comply with the specified rules | - Path=/red/{segment},/blue/** |
Query | The requestor's parameters must contain the specified parameters | - Query=name,jack |
RemoteAddr | Requestor's ip Must be the specified range | - RemoteAddr=192.168.1.1/24 |
Weight | Weight processing |
8.4 Routing filter GatewatyFilter
GatewayFilter It is a filter provided in the gateway , You can process the request to enter the gateway and the response returned by the microservice .
Spring Provides 31 There are different routing filter factories , for example :
name | explain |
---|---|
AddRequestHeader | Add a request header to the current request |
RemoveRequestHeader | Remove the request header in the request |
AddResponseHeader | Add a response header to the response result |
RemoveResponseHeader | Remove a response header from the corresponding result |
RequestRateLimiter | Limit the requested traffic |
How to add filters to a route :
spring:
cloud:
gateway:
routes: # Gateway routing configuration
- id: a-service
uri: lb://aservice
predicates:
- Path=/a/**
filters: # filter
- AddRequestHeader=Truth, new header # Add request header , Key value pairs are separated by commas
Default filter :
If you want to add a filter to all routes , It can be said that the filter factory wrote default-filters Next .
spring:
cloud:
gateway:
routes: # Gateway routing configuration
- id: a-service
uri: lb://aservice
predicates:
- Path=/a/**
default-filters: # Default filter , It will take effect for all routing requests
- AddRequestHeader=Truth, new header # Add request header , Key value pairs are separated by commas
8.5 Global filter
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 :
Case study : Define global filters , Intercept and determine the user's identity
demand : Whether there is authorization, And authorization Whether the parameter value of is admin
@Order(-1) // Sequential annotation , It can also be implemented through the interface Ordered
@Component
public class Authorization implements GlobalFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
// 1. Get request parameters
ServerHttpRequest request = exchange.getRequest();
MultiValueMap<String, String> queryParams = request.getQueryParams();
// 2. Get... In the parameter authorization Parameters
String authorization = queryParams.getFirst("authorization");
// 3. Judge whether the parameter value is equal to admin
if("admin".equals(authorization)){
// 4. yes , release
return chain.filter(exchange);
}
// 5. no , Intercept
// 5.1 Set status code , Indicates that you are not logged in
exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
// 5.2 Intercept request
return exchange.getResponse().setComplete();
}
}
8.6 Filter execution sequence
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 .
Filter execution order :
- 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 .
8.7 Gateway cross domain problem handling
Cross domain : Domain name inconsistency is cross domain , Don't include :
- Domain name is different
- Domain name is the same , Different ports
Cross-domain problem : browser Cross domain communication between the initiator of the request and the server is prohibited ajax request , The request is blocked by the browser
Solution : CORS
The gateway handles cross domain transactions in the same way CORS programme , And it only needs simple configuration to realize :
spring:
cloud:
gateway:
globalcors: # Global cross domain processing
add-to-simple-url-handler-mapping: true # solve options The request is blocked
corsConfigurations:
'[/**]': # Intercept all requests , Cross domain processing
allowedOrigins: # Allow cross domain requests for which websites
- "http://localhost:8090"
- "http://www.baidu.com"
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
边栏推荐
- 使用Aspect制作全局异常处理类
- Parker驱动器维修COMPAX控制器维修CPX0200H
- regular expression
- Poj3414广泛搜索
- Four components of logger
- SQL common syntax records
- Teach yourself to train pytorch model to Caffe (I)
- 张丽俊:穿透不确定性要靠四个“不变”
- Feng Tang's "spring breeze is not as good as you" digital collection, logged into xirang on July 8!
- crm创建基于fetch自己的自定义报告
猜你喜欢
Two ways to realize video recording based on avfoundation
Reptile practice
ICMP 介绍
Deeply convinced plan X - network protocol basic DNS
The Blue Bridge Cup web application development simulation competition is open for the first time! Contestants fast forward!
让开发效率飞速提升的跨端方案
MMAP
Recursive query of multi-level menu data
Feng Tang's "spring breeze is not as good as you" digital collection, logged into xirang on July 8!
"Grain mall" -- Summary and induction
随机推荐
Two ways to realize video recording based on avfoundation
Did you brush the real title of the blue bridge cup over the years? Come here and teach you to counter attack!
Advantages of robot framework
About the writing method of SQL field "this includes" and "included in" strings
Teach yourself to train pytorch model to Caffe (I)
Poj3414 extensive search
[daily training -- Tencent select 50] 89 Gray code (only after seeing the solution of the problem)
ESP32
Comprehensive optimization of event R & D workflow | Erda version 2.2 comes as "7"
阿里云有奖体验:用PolarDB-X搭建一个高可用系统
AD637使用笔记
EBS Oracle 11g 克隆步骤(单节点)
poj 3237 Tree(樹鏈拆分)
MMAP学习
Summary of data analysis steps
力扣------经营摩天轮的最大利润
Deployment of Jenkins under win7
Some common processing problems of structural equation model Amos software
sql常用语法记录
Scenario interview: ten questions and ten answers about distributed locks