In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "how to understand Gateway Gateway Services". Many people will encounter such a dilemma in the operation of actual cases. Next, let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Gateway Gateway Services I. Overview
Gateway is an API gateway system based on Spring ecosystem, which is based on Spring5 Springboot2 and Project Reactor technologies.
Gateway aims to provide a simple and efficient way to route API, as well as some powerful filter functions, such as circuit breaker, current limit, retry, etc.
Second, function
Action
Reverse proxy
Authentication
Flow control
Fuse break
Log monitoring
Third, three core concepts
Route (routing)
Routing is the basic module for building a gateway, which consists of ID,URI, a series of assertions and filters, and matches the route if the assertion is true.
Predicate assertion
Refer to the java.util.function.Predicate of java8
Developers can match everything in a HTTP request (such as request headers or request parameters) and route if the request matches the assertion
Filter filtering
An instance of GatewayFilter in the Spring framework that uses filters to modify requests before or after they are routed
Summary:
The web request locates to the real service node through some matching criteria. And do some fine control before and after the forwarding process.
Predicate is our matching condition.
Filter can be understood as an omnipotent filter, with these two elements plus the target Uri can achieve a specific route.
4. Gateway workflow
The client sends a request to the SpringCloudGateway. Then find the route that matches the request in GatewayHandlerMapping and send it to GatewayWebHandler.
Handle then sends the request to our actual service to execute the business logic through the specified filter chain, and then returns.
The filter may "pre" or "post" execute business logic before or after sending the proxy request
Filter filters of "pre" type can do parameter verification, permission verification, flow control, log output, protocol conversion, etc., while filters of "post" type can do changes in response content, response header, log output, traffic monitoring and so on.
Fifth, entry configuration 1. Create a new module cloud-gateway-gateway95272.pom
Spring-boot-starter-web needs to be removed or an error will be reported
Spring MVC found on classpath, which is incompatible with Spring Cloud Gateway at this time. Please remove spring-boot-starter-web dependency.
Org.springframework.cloud spring-cloud-starter-gateway org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.boot spring-boot-devtools runtime true org.projectlombok lombok True org.springframework.boot spring-boot-starter-test test 3.ymlserver: port: 9527spring: application: name: cloud-gatewayeureka: instance: hostname: cloud-gateway-service client: register-with-eureka: true fetchRegistry: true service-url: defaultZone: http://eureka7001.com:7001/eureka4.main@SpringBootApplication@EnableEurekaClientpublic class GateWayMain9527 {public static void main (String [] args) {SpringApplication.run (GateWayMain9527.class) Args) }} 5. Access the interface of 8001 through the gateway
Map two interfac
/ payment/lb
/ payment/get/ {id}
New gateway configuration for YML:
New spring.cloud.gateway.routes section
The ID of server: port: 9527spring: application: name: cloud-gateway cloud: gateway: routes:-id: payment_routh # payment_route # route, which has no fixed rules but is required to be unique It is recommended to match the routing address of the service provided with the service name uri: http://localhost:8001 # predicates:-Path=/payment/get/** # asserts that the path matching ID for routing-id: payment_routh3 # payment_route # has no fixed rules but is required to be unique It is recommended to match the service name uri: http://localhost:8001 # to provide the service's routing address predicates:-Path=/payment/lb/** # asserts that if the path matches, route eureka: instance: hostname: cloud-gateway-service client: register-with-eureka: true fetchRegistry: true service-url: defaultZone: http://eureka7001.com:7001/eureka
Start 7001, cloud-provider-payment8001, 9527
Visit
Http://localhost:9527/payment/get/1
6.YML configuration description
There are two ways to configure Gateway gateway routing
6.1Configuring Bean that injects RouteLocator into code 6.2in YML
Reference: https://spring.io/projects/spring-cloud-gateway
Com.zhl.springcloud.config.GateWayConfig
@ Configurationpublic class GateWayConfig {@ Bean public RouteLocator customeRouteLocator (RouteLocatorBuilder builder) {RouteLocatorBuilder.Builder routes = builder.routes (); routes.route ("path_route_atguigu1", r-> r.path ("/ guonei") .uri ("http://news.baidu.com/guonei")).build(); return routes.build ();}} 6.3 test access
Http://localhost:9527/guonei Jump http://news.baidu.com/guonei
6. Dynamic routing through micro-service name
By default, GateWay will use the list of services registered by the registry
The function of dynamic routing is realized by creating a dynamic route with the micro-service name on the registry as the path for forwarding.
1. Start Eureka and service provider 8001 8002
2.YML
1.spring.cloud.gateway.discovery.locator.enabled:true
2.spring.cloud.gateway.routes [0] .uri: the routing address of the service provided after the lb://cloud-payment-service # match
Spring.cloud.gateway.routes [1] .uri: lb://cloud-payment-service
Server: port: 9527spring: application: name: cloud-gateway cloud: gateway: discovery: locator: enabled: true # enables the function of dynamically creating routes from the registry. Use the micro service name to route routes:-id: payment_routh # payment_route # ID of routes. There are no fixed rules but unique is required. It is recommended to match the routing address of the service provided with the service name uri: lb://cloud-payment-service # predicates:-Path=/payment/get/** # asserts that the path matching ID for routing-id: payment_routh3 # payment_route # has no fixed rules but is required to be unique It is recommended to match the service name uri: lb://cloud-payment-service # to provide the service's routing address predicates:-Path=/payment/lb/** # asserts that if the path matches, route eureka: instance: hostname: cloud-gateway-service client: register-with-eureka: true fetchRegistry: true service-url: defaultZone: http://eureka7001.com:7001/eureka3. test
Visit: http://localhost:9527/payment/lb
8001/8002
What is the use of Predicate? what is 1.Predicate? what is 2.RoutePredicateFactories?
View the background information of the startup:
Spring Cloud Gateway uses route matching as part of the SpringWebFlux HandlerMapping infrastructure
Spring Cloud Gateway includes many built-in Route Predicate factories. All of these Predicate match the different properties of the HTTP request. Multiple RoutePredicate factories can be combined
When Spring Cloud Gateway creates a Route object, you use RoutePredicateFactory to create a Predicate object, and the Predicate object can be assigned to Route. SpringCloudGateway contains many built-in RoutePredicateFatories
3. Commonly used Route Predicate
Refer to the official website:
Https://docs.spring.io/spring-cloud-gateway/docs/2.2.5.RELEASE/reference/html/#gateway-request-predicates-factories
1.After Route Predicate
Use ZonedDateTime.now () to get time after time
-id: payment_routh3 # payment_route # routing ID, which has no fixed rules but is required to be unique. It is recommended to match the service name # uri: http://localhost:8001 # to match the service's routing address uri: lb://cloud-payment-service # match the service's routing address predicates:-Path=/payment/lb/** # assertion Route if the path matches-After=2020-02-21T15:51:37.485+08:00 [Asia/Shanghai]
2.Before Route Predicate
Before time
3.Between Route Predicate
Between time
4.Cookie Route Predicate
-id: payment_routh3 # payment_route # routing ID, which has no fixed rules but is required to be unique. It is recommended to match the service name # uri: http://localhost:8001 # to match the service's routing address uri: lb://cloud-payment-service # match the service's routing address predicates:-Path=/payment/lb/** # assertion Route #-After=2020-02-21T15:51:37.485+08:00 [Asia/Shanghai]-Cookie=username,zzyy if the path matches
Access without cookie
C:\ Users\ Administrator > curl http://localhost:9527/payment/lb{"timestamp":"2020-12-04T14:16:14.906+00:00","path":"/payment/lb","status":404,"error":"Not Found ",.
Bring cookie access
C:\ Users\ Administrator > curl http://localhost:9527/payment/lb-- cookie "username=zzyy" 8002
5.Header
-id: payment_routh3 # payment_route # routing ID, which has no fixed rules but is required to be unique. It is recommended to match the service name uri: lb://cloud-payment-service # to provide the service routing address predicates:-Path=/payment/lb/** # assertion Regular expression C:\ Users\ Administrator > curl http://localhost:9527/payment/lb-H "X-Request-Id:1234" 8002C:\ Users\ Administrator > curl http://localhost:9527/payment/lb-H "X-Request-Id:aaaa" {"timestamp": "2020-12-04T14:22:01.354+00:00" "path": "/ payment/lb", "status": 404, "error": "Not Found"
6.Host
Host Route Predicate receives a set of parameters, a list of matching domain names, this template is an ant split template, using. Number as the delimiter it uses the host address in the parameter as the matching rule.
7.Method
8.Path
9.Query
10. Summary
VIII. The use of Filter
Refers to an instance of GatewayFilter in the Spring framework, which uses a filter to modify the request before or after the request is routed.
Route filters allow incoming HTTP requests or outgoing HTTP responses to be modified in some way. Route filters apply to specific routes. Spring Cloud Gateway includes many built-in GatewayFilter factories
1. Declaration cycle
Pre Post
two。 Kinds
GatewayFilter: single
GlobalFilter: global
3. Commonly used GatewayFilter
AddRequestParameter
4. Custom filter A. Two main interfaces B. Action
Global logging
Unified gateway authentication.
c. Case code
New component: com.zhl.springcloud.filter.MyLogGateWayFilter
@ Component@Slf4jpublic class MyLogGateWayFilter implements GlobalFilter, Ordered {@ Override public Mono filter (ServerWebExchange exchange, GatewayFilterChain chain) {log.info ("* come in MyLogGateWayFilter:" + new Date ()); String name= exchange.getRequest () .getQueryParams () .getFirst ("uname"); if (name==null) {log.info ("* user name is null, illegal user * *") Exchange.getResponse () .setStatusCode (HttpStatus.NOT_ACCEPTABLE); return exchange.getResponse () .setComplete ();} return chain.filter (exchange);} @ Override public int getOrder () {/ * the order in which filters are loaded, the smaller the order, the higher the priority * / return 0;}} D. test
That's all for C:\ Users\ Administrator > curl http://localhost:9527/payment/lb?uname=z38002" how to understand Gateway Gateway Services. Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.