springclound getway(过滤器)

1.pom文件依赖

<dependencies>
<dependency>
    <groupId>cn.kgc</groupId>
    <artifactId>hello-sc-2109-common</artifactId>
    <version>1.0-SNAPSHOT</version>
</dependency>
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>fastjson</artifactId>
    <version>1.2.66</version>
</dependency>
    <!-- gateway依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-gateway</artifactId>
    </dependency>
    <!-- eureka客户端依赖 -->
    <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        <!-- 如果springboot是1.5.X版本 <artifactId>spring-cloud-starter-eureka</artifactId> -->
    </dependency>
</dependencies>

2.yml配置

server:
  port: 11000
eureka:
  client:
    service-url:
      defaultZone: http://admin:1234@localhost:7001/eureka/
    register-with-eureka: true
    fetch-registry: true
spring:
  application:
    name: hello-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true  #开启微服务名称转发模式
          lower-case-service-id: true

        

globalcors:
  corsConfigurations:
    '[/**]':
      allowCredentials: true  #设置允许访问携带cookie
      allowedOrigins: "http://localhost:8888"  #可以填写多个域名,用","隔开, "*"代表允许所有
      allowedMethods: "*"
      allowedHeaders: "*"

3.启动类

@SpringBootApplication
@EnableEurekaClient

4. filter过滤类

@Component
public class MyGatewayFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        String token = request.getQueryParams().getFirst("token");
        if(token == null){
            //拒绝
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);

            Result<Object> result = Result.fail(20006, "请求未授权!!!");

            DataBuffer buffter = response.bufferFactory().wrap(JSON.toJSONString(result).getBytes());

            response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
            return response.writeWith(Mono.just(buffter));

        }
        //放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}

Spring Cloud Gateway 是 Spring Cloud 的一个全新项目,该项目是基于 Spring 5.0,Spring Boot 2.0 和 Project Reactor 等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式。

Spring Cloud Gateway 作为 Spring Cloud 生态系统中的网关,目标是替代 Netflix Zuul,其不仅提供统一的路由方式,并且基于 Filter 链的方式提供了网关基本的功能,例如:安全,监控/指标,和限流。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值