Table of contents
Second, Gateway routing configuration
创建com/springcloud/config/GateWayRoutesConfig.java
2. Modify the application.yml of e-commerce-gateway-20000
A detailed explanation of SpringCloud-Gateway and a complete schematic diagram and code demonstration-below
Second, Gateway routing configuration
1 Method 1: Configuration in application.yml - as mentioned earlier
2 Method 2: Write configuration class injection【Understand】
Log out of application.yml first, and only keep the gateway part when logging out of the gateway routing part
spring:
application:
name: e-commerce-gateway
2. Restart e-commerce-gateway-20000, test again, the gateway route fails
3. Refer to official documents
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#spring-cloud-circuitbreaker-filter-factory ,
创建com/springcloud/config/GateWayRoutesConfig.java
@Configuration
public class GateWayRoutesConfig {
//配置注入路由
/**
* 在理解通过配置类注入/配置 路由,可以对照前面的application.yml来对比理解
* cloud:
* gateway:
* routes: #配置路由,可以配置多个路由 List<RouteDefinition> routes
* - id: member_route01 #路由的id, 程序员自己配置,要求唯一
* #gateway 最终访问的url 是 url=uri+Path
* #匹配后提供服务的路由地址: 也可以是外网 http://www.baidu.com
* #比如: 客户端/浏览器请求 url http://localhost:20000/member/get/1
* #如果根据Path匹配成功 最终访问的url/转发url 就是 url=http://localhost:10000/member/get/1
* #如果匹配失败, 则有gateway返回404信息
* #疑问: 这里配置的 uri 是固定,在当前这种情况其实可以没有有Eureka Server,后面会使用灵活方式
* # 配置,就会使用到Eureka Server
* uri: http://localhost:10000
* predicates: #断言,可以有多种形式
* - Path=/member/get/**
*/
@Bean
public RouteLocator myRouteLocator04(RouteLocatorBuilder routeLocatorBuilder) {
RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
//方法写完
//梳理
//1. 下面的方法我们分别指定了id , uri 和path
//2. Function<PredicateSpec, Route.AsyncBuilder> fn
//(1) 是一个函数式接口
//(2) 接收的类型是 PredicateSpec ,返回的类型是 Route.AsyncBuilder
//(3) r -> r.path("/member/get/**")
// .uri("http://localhost:10000") 就是lambda表达式
//(4) 一会还要用代码进行说明-先使用-再理解
//3. 小伙伴们可以理解这是一个规定写法
return routes.route("member_route04", r -> r.path("/member/get/**")
.uri("http://localhost:10000"))
.build();
}
@Bean
public RouteLocator myRouteLocator05(RouteLocatorBuilder routeLocatorBuilder) {
RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
return routes.route("member_route05", r -> r.path("/member/save")
.uri("http://localhost:10000"))
.build();
}
}
test
1 Start e-commerce-eureka-server-9001
2 Start member-service-provider-10000
3 Start e-commerce-gateway-20000
4 Browser: (access through the gateway) http://localhost:20000/member/get/1
The result is the same as before and will not be shown here.
Don’t forget to restore the code to yml configuration
dynamic routing
schematic diagram
Code
1. Modify the application.yml of e-commerce-gateway-20000
spring:
application:
name: e-commerce-gateway
cloud:
gateway:
routes: #配置路由,可以配置多个路由 List<RouteDefinition> routes
- id: member_route01 #路由的id, 程序员自己配置,要求唯一
#gateway 最终访问的url 是 url=uri+Path
#匹配后提供服务的路由地址: 也可以是外网 http://www.baidu.com
#比如: 客户端/浏览器请求 url http://localhost:20000/member/get/1
#如果根据Path匹配成功 最终访问的url/转发url 就是 url=http://localhost:10000/member/get/1
#如果匹配失败, 则有gateway返回404信息
# 配置,就会使用到Eureka Server
#解读
#1. lb: 协议名 , member-service-provider 注册到eureka server 服务名(小写)
#2. 默认情况下,负载均衡算法是轮询
uri: lb://member-service-provider
predicates: #断言,可以有多种形式
- Path=/member/get/**
- id: member_route02 #路由的id, 程序员自己配置,要求唯一
uri: lb://member-service-provider
predicates: #断言,可以有多种形式
#这时如果客户端/浏览器 访问gateway 的url http://localhost:20000/member/save
#匹配Path成功 最终访问的url 就是 http://localhost:10000/member/save
- Path=/member/save
test
1 Start e-commerce-eureka-server-9001
2 Start member-service-provider-10000
3 Start e-commerce-gateway-20000
4 Browser: (access through the gateway) http://localhost:20000/member/get/1
Postman test added (go through the gateway, it will not be shown here after the previous demonstration)
Notes and Details
1 After the dynamic routing is configured, the Gateway will create a dynamic routing for the request according to the microservice name on the registration center to realize the dynamic routing function
2 The lb protocol used supports load balancing-polling algorithm
3 Configure your own load balancing algorithm, and restore to the original polling algorithm after the test
the code
/**
* RibbonRule: 配置类-配置自己的负载均衡算法
*/
@Configuration
public class RibbonRule {
//配置注入自己的负载均衡算法
@Bean
public IRule myRibbonRule() {
//这里老师返回的是RandomRule,当然小伙伴也可以自己指定
return new RandomRule();
}
}
Predicate
basic introduction
In a word: Predicate is a set of matching rules. When the request is successfully matched, the corresponding Route will be executed. If the match fails, processing/forwarding will be abandoned.
Route Predicate Factories
- Document address:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories
interpret
1. Spring Cloud Gateway includes many built-in Route Predicate factories, all of which match different attributes of HTTP requests and can be used in combination.
2. When Spring Cloud Gateway creates a Route object, it uses RoutePredicateFactory to create a Predicate object, which can be assigned to a Route.
3. All these predicates match different attributes of the HTTP request. Various predicate factories can be combined
Route Predicate instance
After Route Predicate
Requirement: Only requests after 2022-11-18 12:35:50 will be matched/forwarded, and those that do not meet this condition will not be processed
1. Reference document:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories
2. Modify the application.yml of e-commerce-gateway-20000
Note that only the places that need to be modified are shown here. All configurations are listed above.
predicates:
- Path=/member/get/** #断言,路径相匹配的进行路由
- After=2022-11-18T12:35:50.387+08:00[Asia/Shanghai]
3. How to get the time format, create a test class to get the current time, and then modify it as needed
springcloud/T2.java
public class T2 {
public static void main(String[] args) {
ZonedDateTime now = ZonedDateTime.now();
System.out.println(now);
}
}
test
Start e-commerce-eureka-server-9001
Start member-service-provider-10000/10002
Start e-commerce-gateway-20000
Browser: (access through gateway) http://localhost:20000/member/get/1
Before Route Predicate
Requirement: Only requests before 2022-11-18 12:35:50 will be matched/forwarded, and those that do not meet this condition will not be processed
1. Reference document:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories
2. Modify the application.yml of e-commerce-gateway-20000
predicates:
- Path=/member/get/** #断言,路径相匹配的进行路由
#- After=2022-11-18T12:35:50.387+08:00[Asia/Shanghai]
- Before=2022-11-18T12:35:50.387+08:00[Asia/Shanghai]
The test steps are the same as the previous ones, and this one will not be repeated.
Between Route Predicate
Requirements: Only requests between 2020-11-18 12:35:50 and 2022-11-18 12:35:50 will be matched/forwarded, and those that do not meet this condition will not be processed
1. Reference document:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories
2. Modify the application.yml of e-commerce-gateway-20000
predicates:
- Path=/member/get/** #断言,路径相匹配的进行路由
#- After=2022-11-18T12:35:50.387+08:00[Asia/Shanghai]
#- Before=2022-11-18T12:35:50.387+08:00[Asia/Shanghai]
-
Between=2020-11-18T12:35:50.387+08:00[Asia/Shanghai],2022-11-18T12:35:50.387+0
8:00[Asia/Shanghai]
Cookie Route Predicate
Requirement: request with cookie key: user value: nihao only matches/assertion succeeds
1. Reference document:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories
Interpretation:
chocolate is the cookie name ch.p is the value of the cookie, which is matched according to regular expressions
2. Modify the application.yml of e-commerce-gateway-20000
predicates:
- Path=/member/get/** #断言,路径相匹配的进行路由
#- After=2022-11-18T12:35:50.387+08:00[Asia/Shanghai]
#- Before=2022-11-18T12:35:50.387+08:00[Asia/Shanghai]
#-Between=2020-11-18T12:35:50.387+08:00[Asia/Shanghai],2022-11-18T12:35:50.387+08:00[Asia/Shanghai]
- Cookie=user, nihao
This is a bit special, so I took a separate screenshot
If it is the same as the previous one, it will not be displayed here
Header Route Predicate
Requirements: The request header has X-Request-Id, and the value hello can match/assertion is successful
1. Reference document:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories
Interpretation: X-Request-Id is the name of the header, \d+ is a regular expression
2. Modify the application.yml of e-commerce-gateway-20000
#- Cookie=key1, abc
- Header=X-Request-Id, hello
Host Route Predicate
Requirements: Only when the requested Host is **.wyxedu.** can the match/assertion be successful, such as Host www.wyxedu.com
1. Reference document:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories
Interpretation: There can be multiple Hosts, separated by commas
2. Modify the application.yml of e-commerce-gateway-20000
#- Header=X-Request-Id, hello
- Host=**.wyxedu.**
Method Route Predicate
Requirements: The request is only matched/asserted successfully in the Get mode
1. Reference document:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories
Interpretation: There can be multiple request methods, separated by commas
2. Modify the application.yml of e-commerce-gateway-20000
#- Host=**.wyxedu.**
- Method=GET
Pay attention to the GET method we set so it will report an error
Path Route Predicate
1. Reference document:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories
Interpretation: There can be multiple Paths, separated by commas
Query Route Predicate
Requirements: The request has the parameter email, and the basic format of the email must be satisfied to match/asserte successfully
1. Reference document:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories
Interpretation: red is the parameter name gree. It is the value and supports regular expressions
2. Modify the application.yml of e-commerce-gateway-20000
#- Host=**.wyxedu.**
#- Method=GET
- Query=email, [\w-]+@([a-zA-Z]+\.)+[a-zA-Z]+
Note which services are started are the same
here again remind
Start e-commerce-eureka-server-9001
Start member-service-provider-10000/10002
Start e-commerce-gateway-20000
RemoteAddr Route Predicate
Requirement: The requested IP is 127.0.0.1 in order to match/assert successfully
1. Reference document:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gateway-request-predicates-factories
2. Modify the application.yml of e-commerce-gateway-20000
#提示:通过http://127.0.0.1:20000/member/get/1 ,可以看到效果.
- RemoteAddr=127.0.0.1
Note that because the default ip of this machine is 127.0.0.1, it is not necessary to specify it directly, but if it is another ip, it needs to be specified
If the request is 192.168.1.2, if you want to see the effect, go to http://192.168.1.2:20000/member/get/1
After the test, remember to restore the code to before the test
Filter/filter
basic introduction
1. Document address:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#gatewayfilter-factories
interpret
Routing filters can be used to modify incoming HTTP requests and returning HTTP responses.
Spring Cloud Gateway has a variety of built-in routing filters, all of which are generated by the factory class of GatewayFilter
type
1 GatewayFilter
2 GlobalFilter
Document address:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#global-filters
GatewayFilter uses
1 Development uses GatewayFilter seldom directly, generally custom filters
2 Reference examples
Reference document address:
https://cloud.spring.io/spring-cloud-static/spring-cloud-gateway/2.2.1.RELEASE/reference/html/#the-addrequestheader-gatewayfilter-factory
2. Modify the application.yml of e-commerce-gateway-20000
#- RemoteAddr=127.0.0.1
filters:
- AddRequestParameter=color, blue#过滤器工厂会在匹配的请求头加上一对请求头,名称为color 值为blue
- AddRequestParameter=age, 18#过滤器工厂会在匹配的请求头加上一对请求头,名称为age 值为18
3. Verification
修改member-service-provider-10000\src\main\java\com\springcloud\controller\MemberController.java
@GetMapping("/member/get/{id}")
public Result getMemberById(@PathVariable("id") Long id, HttpServletRequest request) {
String color = request.getParameter("color");
String address = request.getParameter("age");
Member member = memberService.queryMemberById(id);
//使用Result把查询到的结果返回
if (member != null) {
return Result.success("查询会员成功 member-service-provider-10000 " + color + "-" + age, member);
} else {
return Result.error("402", "ID= " + id + "不存在");
}
}
Custom GlobalFilter
1 Requirements Analysis/Illustration
1. Customize the global GlobalFilter filter
2. If the request parameters user=wyxdu, pwd=123456, it will be allowed, otherwise it will not pass the verification
Code
1. Create com/springcloud/filter/CustomGateWayFilter.java in e-commerce-gateway-20000
@Component
public class CustomGateWayFilter implements GlobalFilter, Ordered {
//filter是核心的方法,将我们的过滤的业务,写在该方法中
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
System.out.println("------CustomGateWayFilter------");
//先获取到对应的参数值
//比如 http://localhost:20000/member/get/1?user=wyxedu&pwd=123456
String user =
exchange.getRequest().getQueryParams().getFirst("user");
String pwd = exchange.getRequest().getQueryParams().getFirst("pwd");
if(!("wyxdu".equals(user) && "123456".equals(pwd))) {//如果不满足条件
System.out.println("-----非法用户-----");
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);//回应
return exchange.getResponse().setComplete();
}
//验证通过, 放行
return chain.filter(exchange);
}
//order 表示过滤器执行的顺序, 数字越小, 优先级越高
@Override
public int getOrder() {
return 0;
}
}
test
1 Start e-commerce-eureka-server-9001
2 Start member-service-provider-10000/10002
3 Start e-commerce-gateway-20000
4 Browser: (access through gateway) http://localhost:20000/member/ get/1?user=wyxdu&pwd=123456
Show this if it doesn't pass
After the test, remember to restore the code to before the test