AlibabaCloud笔记05 - 网关SpringCloud Gateway

1.创建SpringCloud网关项目和依赖添加
添加依赖:

        
            org.springframework.cloud
            spring-cloud-starter-gateway
        

添加配置属性文件:

server:
  port: 9851

spring:
  application:
    name: gateway
  cloud:
    gateway:
      routes: #数组形式
        - id: order-service  #路由唯一标识
          uri: http://127.0.0.1:9000  #想要转发到的地址
          order: 1 #优先级,数字越小优先级越高
          predicates: #断言 配置哪个路径才转发
            - Path=/order-server/**
          filters: #过滤器,请求在传递过程中通过过滤器修改
            - StripPrefix=1  #去掉第一层前缀

#访问路径 http://localhost:8888/order-server/api/v1/video_order/list
#转发路径 http://localhost:8000/order-server/api/v1/video_order/list
#需要过滤器去掉前面第一层

效果:
AlibabaCloud笔记05 - 网关SpringCloud Gateway_第1张图片

2.Gateway配置Nocas
网关添加naocs依赖:

        
        
            com.alibaba.cloud
            spring-cloud-starter-alibaba-nacos-discovery
        

启动类开启支持:

@EnableDiscoveryClient

修改配置文件:

uri: lb://order-service  # 从nacos获取名称转发,lb是负载均衡轮训策略

AlibabaCloud笔记05 - 网关SpringCloud Gateway_第2张图片

访问路径:
http://localhost:9851/order-server/api/v1/order/save4/40

3.Gateway全局过滤器实现用户鉴权
自定义全局过滤器实现鉴权:

package hecr.filter;

import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Component
public class MyGlobalFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String token = exchange.getRequest().getHeaders().getFirst("token");

        System.out.println(token);
        if (StringUtils.isBlank(token)) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }

        //继续往下执行
        return chain.filter(exchange);
    }

    //数字越小,优先级越高
    @Override
    public int getOrder() {
        return 0;
    }
}

效果:
AlibabaCloud笔记05 - 网关SpringCloud Gateway_第3张图片

你可能感兴趣的:(spring相关,gateway,网关,spring,cloud)