赞
踩
- package com.learning.springcloud.custom;
-
- import org.apache.commons.lang.StringUtils;
- import org.springframework.cloud.gateway.filter.GatewayFilter;
- import org.springframework.cloud.gateway.filter.GatewayFilterChain;
- import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
- import org.springframework.http.HttpStatus;
- import org.springframework.stereotype.Component;
- import org.springframework.web.server.ServerWebExchange;
- import reactor.core.publisher.Mono;
-
- import java.util.Arrays;
- import java.util.List;
-
- @Component
- public class DemoGatewayFilterFactory extends AbstractGatewayFilterFactory<DemoGatewayFilterFactory.Config> {
-
- public DemoGatewayFilterFactory() {
- super(Config.class);
- }
-
- public List<String> shortcutFieldOrder() {
- return Arrays.asList("name", "value");
- }
-
- @Override
- public GatewayFilter apply(DemoGatewayFilterFactory.Config config) {
- return new GatewayFilter() {
- public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
- String value = exchange.getRequest().getQueryParams().getFirst("name");
-
- if (StringUtils.isBlank(value)) {
- // 为空 则证明是正常的请求 需要放行
- return chain.filter(exchange);
- }
- if ("YES".equals(value)) {
- return chain.filter(exchange);
- }
- exchange.getResponse().setStatusCode(HttpStatus.NOT_FOUND);
- return exchange.getResponse().setComplete();
- }
- };
- }
-
- public static class Config {
- private String name;
- private String value;
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getValue() {
- return value;
- }
-
- public void setValue(String name) {
- this.value = name;
- }
- }
- }
- server:
- port: 8088
- spring:
- application:
- name: api-gateway
- cloud:
- nacos:
- discovery:
- server-addr: 127.0.0.1:8847
- username: nacos
- password: nacos
- gateway:
- routes:
- - id: order_route # 路由唯一标识
- #uri: http://localhost:8020 # 需要转发的地址
- uri: lb://order-service # 需要转发的地址
- # 断言规则 用于路由规则的匹配
- predicates:
- # - Path=/order-serv/**
- # - After=2024-01-01T23:00:11.518+08:00[Asia/Shanghai]
- # - Before=2025-01-01T23:00:11.518+08:00[Asia/Shanghai]
- - Between=2024-01-01T23:00:11.518+08:00[Asia/Shanghai],2025-01-01T23:00:11.518+08:00[Asia/Shanghai]
- # - Header=X-Request-Id,\d+
- # - Host=127.0.0.1
- # - Query=name,lq
- # - Method=GET,POST
- # http://localhost:8088/order-serv/order/add => http://localhost:8020/order-serv/order/add
- - Demo=YES
- #配置过滤器工厂
- filters:
- - StripPrefix=1 # 转发去掉第一层路径
- - AddRequestHeader=X-Request-name,tom #添加请求头
- - AddRequestParameter=color, blue # 添加请求参数
- - PrefixPath=/demo
- # - RedirectTo=302, https://www.baidu.com/ #重定向到百度
- - Demo=name,YES # 自定义过滤工厂配置
- # http://localhost:8020/order-serv/order/add => http://localhost:8020/order/add
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。