gateway understanding
A gateway is similar to
海关
or大门
,出入都需要经过这个网关
. Others will never see what's inside without passing through this gateway. It can be done at the gateway条件过滤
, for example, only the corresponding key can enter the gate. Gateways, like gates, are always exposed to the outsideno gateway
The front end needs to remember the IP and port of each service
If there are multiple deployments of a service, the front end needs to allocate it by itself
use gateway
The front end does not need to remember the IP and port of each service, it only needs to send the request to the gateway, and the gateway will do it according to the resource path
路由跳转
Gateway can do
安全控制
such as Token verification, current limiting, etc.can do
负载均衡
Understanding of Gateway
It is a set of gateway components launched by Spring official website to replace Zuul
It's designed to let
路由跳转更加方便、灵活
, yet offer something powerful过滤器功能
. For example: IP blacklist, Token verification, etc.Based on the webFlux framework, the bottom layer of the webFlux framework uses Netty, a high-performance Reactor mode communication framework.
Gateway is an API gateway service built on top of the Spring ecosystem, based on technologies such as Spring 5, Spring Boot 2 and Project Reactor.Gateway aims to provide a simple and effective way to route APIs, and provide some powerful filter functions, such as: circuit breaking, current limiting, retrying, etc.
① Gateway working principle
The client sends a request to Gateway, and then Gateway HandlerMapping compares the mapping to find a matching route and sends it to Gateway WebHandler. The Handler distributes the request to the actual business logic through the specified filter and returns it.
You can add code in the filter:
Do validation etc. in
请求之前
[pre]Do log output etc. in
请求之后
[post]Gateway core logic: do routing and forwarding according to the resource path, and execute the filter chain.
② Three core concepts of Gateway
Route
Combine with eureka for dynamic routing
Components: a routing ID, a unique resource locator URI, a set of assertions, a set of Filters
If the route predicate is true, then the URL matches the configured route
Predicate
returns a boolean expression
Filter
The filters in Gateway are divided into Gateway Filter (for a route) and Global Filter (global)
Validation rules and response processing can be written in the filter
③ Difference between Gateway and Nginx
Nginx needs to modify the nginx.conf configuration file for current limiting, load balancing, and routing
The combination of Gateway and eureka realizes automatic routing jump; and Ribbon collection realizes load balancing. Gateway can also implement current limiting through configuration
Routing usage
① Access flow
② Loing-service
@RestController public class LoginController { @GetMapping("doLogin") public String doLogin(String username,String password){ System.out.println(username+" -> "+password); String token = UUID.randomUUID().toString(); return token; } }
② Gateway-server
gateway dependency
<dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>
configure routing
server: port: 80 spring: application: name: gateway-server cloud: gateway: enabled: true # 默认开启Gateway routes: # 路由组 - id: login-service-route # 路由ID 保证唯一 uri: http://localhost:8080 # uri唯一资源定位符 url唯一资源标识符 predicates: # 断言 - Path=/doLogin # 和服务中的路径匹配
④ Programmatic routing
Routing and forwarding is realized by encoding without the help of configuration files
@Configuration public class RouteConfig { @Bean public RouteLocator customRouteLocator(RouteLocatorBuilder builder) { return builder.routes() .route("anime-id", r->r.path("/anime").uri("https://www.bilibili.com")) .route("variety-id",r->r.path("/variety").uri("https://www.bilibili.com")) .build(); } }
If
uri
the resource path behindpath
is the same as the route in, the gateway will notpath
splice the route in touri
the back.Programmatic and configuration files can be combined
dynamic routing
If the URL is directly hard-coded during routing and forwarding, so that the IP and port are also hard-coded, the Gateway will not be able to achieve the effect of load balancing. It should only provide the service name, and then use this name to find the corresponding service, so as to achieve the effect of load balancing
Let the Gateway service also register in the registration center, then the Gateway will be able to have all the service information
服务名为路径
Gateway will create a dynamic route for each forwarding according to the list of services in the registration center① The first implementation method
Use the lb (Load Balance) protocol to enable the Gateway's load balancing function
server: port: 80 spring: application: name: gateway-server cloud: gateway: enabled: true # 默认开启Gateway routes: # 路由组 - id: login-service-route # 路由ID 保证唯一 # uri: http://localhost:8080 # uri唯一资源定位符 url唯一资源标识符 uri: lb://login-service # lb://服务名 predicates: - Path=/doLogin # 和服务中的路径匹配
Call: http://localhost/doLogin
② The second implementation method
Use service discovery to automatically create dynamic routes to achieve load balancing
server: port: 80 spring: application: name: gateway-server cloud: gateway: enabled: true # 默认开启Gateway discovery: locator: enabled: true # 开启动态路由 lower-case-service-id: true # 将注册列表中的服务名小写
Affirmation
When the project starts, Gateway will load some routing assertion factories, such as: After, Query
Assertion is to add some to the route
匹配规则
. If the request sent meets these规则
, you can access it, otherwise 404. Simply put, these matching rules are some boolean expressions, either true to enter, or false to reject① classification
② use
In the configuration file, operate on a route. Dynamic routing cannot use assertions
spring: application: name: gateway-server cloud: gateway: enabled: true # 默认开启Gateway routes: - id: login-service-route uri: lb://login-service predicates: - Path=/doLogin - Method=GET,POST # GET,POST请求能够访问 - After=2022-11-02T17:23:16.423+08:00[Asia/Shanghai] # 在指定时间后才能访问 通过ZonedDateTime获取 - Query=username,admin. # 必须给username传值 后面的值必须是:adminx
filter
The filter in the Gateway is similar to the filter in the Servlet, and the user modifies the incoming HTTP request and HTTP response
Divided into GatewayFilter (for a certain route) and GlobalFilter (global filtering)
① Custom global filter
Write business logic in custom filters, such as Token verification and current limiting.
@Component public class TestFilter implements GlobalFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { // 获取请求对象 ServerHttpRequest request = exchange.getRequest(); RequestPath path = request.getPath(); // 打印路由以及服务名 System.out.println(path); HttpHeaders headers = request.getHeaders(); // 获取主机IP String ip = headers.getHost().getHostName(); System.out.println(ip); // 获取响应对象 ServerHttpResponse response = exchange.getResponse(); // 放过 return chain.filter(exchange); } }
Define filter order
@Component public class TestFilter implements Ordered { @Override public int getOrder() { // 数字越小 越往前 return 0; } }
Return value handling
// 获取响应对象 ServerHttpResponse response = exchange.getResponse(); // 设置响应头 response.getHeaders().set("content-Type","application/json;charset=UTF-8"); // 封装返回数据 Map<String,Object> map = new HashMap<>(); map.put("code", 401); map.put("msg","没有该权限"); ObjectMapper objectMapper = new ObjectMapper(); try { // 将map集合转为byte数组 byte[] bytes = objectMapper.writeValueAsBytes(map); // 将byte数组包装成一个数据缓冲包 DataBuffer wrap = response.bufferFactory().wrap(bytes); // 返回 return response.writeWith(Mono.just(wrap)); } catch (JsonProcessingException e) { e.printStackTrace(); }
Limiting
Within a certain period of time, limit the user's access frequency.
① Current limiting model
Funnel algorithm, token pass algorithm, calculator algorithm, window sliding algorithm
Making ends meet: Tokens cannot be produced as fast as they can be used
The system produces tokens at a rate configured in advance.
Set a threshold for the token bucket. When the bucket is full, excess tokens are discarded directly
Clients need to get tokens when sending requests
If the token is not obtained, the request cannot be accessed successfully
If you get the token, you will access the service and delete the token after completing the business processing
When the number of tokens in the bucket reaches the minimum amount, the used tokens are returned
② Current limiting in Gateway
Gateway has built-in RequestRateLimiterGatewayFilterFactory, combined with Redis as token bucket algorithm. Redis dependencies need to be imported
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis-reactive</artifactId> </dependency>
Configure traffic limiting rules
@Configuration public class RequestLimiterConfig { /* 基于IP做限流 */ @Bean @Primary // 主候选 public KeyResolver ipKeyResolver(){ return exchange-> Mono.just(exchange.getRequest().getHeaders().getHost().getHostName()); } /* 基于API接口最限流 */ @Bean public KeyResolver apiKeyResolver(){ return exchange -> Mono.just(exchange.getRequest().getPath().toString()); } }
Modify the configuration file
spring: application: name: gateway-server cloud: gateway: enabled: true # 默认开启Gateway routes: - id: login-service-route uri: lb://login-service predicates: - Path=/doLogin filters: - name: RequestRateLimiter # 过滤器名称 args: key-resolver: '#{@ipKeyResolver}' # Bean对象的名字 redis-rate-limiter.replenishRate: 1 # 每秒钟生产多少令牌 redis-rate-limiter.burstCapacity: 3 # 令牌桶中的容量
only for a certain route
cross-domain configuration
Cross-domain:
CORS
same-origin policy.Because the gateway is the edge of the service, all requests need to go through the gateway, and the cross-domain configuration is written on the gateway.
programmatic
@Configuration public class CorsConfig { @Bean public CorsWebFilter corsFilter() { CorsConfiguration config = new CorsConfiguration(); config.addAllowedMethod("*"); config.addAllowedOrigin("*"); config.addAllowedHeader("*"); UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration("/**", config); return new CorsWebFilter(source); } }
configuration file
spring: cloud: gateway: globalcors: cors-configurations: '[/**]': # 针对那些路径 allowCredentials: true # 可以携带Cookie allowedHeaders: '*' allowedMethods: '*' allowedOrigins: '*'
interview questions
What is a Microservice Gateway
Spring Cloud Gateway is a gateway developed by Spring based on technologies such as Spring 5.x, Spring Boot 2.0 and Project Reactor. Spring Cloud Gateway aims to provide a simple and effective unified API routing management method for microservice architecture. As a gateway in the Spring Cloud ecosystem , Spring Cloud Gateway aims to replace Netflix Zuul . It not only provides a unified routing method, but also provides basic functions of the gateway based on the Filter chain, such as: security, monitoring/indicators and elasticity.
Advantages of using Gateway
Spring Cloud Gateway can be regarded as an upgraded version and replacement of Zuul 1.x. It uses Netty to implement asynchronous IO earlier than Zuul 2, thus realizing a simple, more efficient than Zuul 1.x, and close to Spring Cloud. Compatible API Gateway.
Spring Cloud Gateway clearly distinguishes between Router and Filter, and a great feature is that it has a lot of built-in out-of-the-box functions, and all of them can be used through SpringBoot configuration or manual coding chain calls .
For example, there are 10 built-in routers, so that we can configure them directly and do routing according to Header, Path, Host, or Query as we like.
For example, general Filter and global Filter are distinguished, 20 kinds of Filters and 9 kinds of global Filters are built in, and all of them can be used directly. Of course custom Filter is also very convenient.Comparison between zuul and spring cloud gateway
- zuul: It belongs to Netflix and is implemented based on servlet. It is a blocking API and does not support long connections.
- gateway: It is a micro-service gateway developed by springcloud itself. It is built based on Spring5 and can implement responsive non-blocking APIs and support long connections.
The composition of the gateway
- Routing: The basic module of the gateway, consisting of ID, target URI, a set of assertions and a set of filters
- Assertion: It is the access rule to access the tour, which can be used to match any content from the http request, such as headers or parameters
- Filter: This is what we usually call a filter. It is used to filter some requests. The gateway has its own default filter. For details, please refer to the official website. We can also customize the filter, but we need to implement two interfaces, ordered and globalfilter