原创

SpringCloud-Gateway的使用

1.导入依赖


    <!--网关依赖-->
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>
    </dependencies>

2.application.yml配置

spring:
  application:
    name: gateway-web
  #缓存配置
  redis:
    host: 122.**.252.**
    timeout: 10000
  cloud:
    #网关的配置
    gateway:
      globalcors:
        cors-configurations:
          '[/**]': #表示匹配所有的path请求
            allowedOrigins: "*" #跨域处理,*表示允许所有的域访问
            allowedMethods: #支持的请求类型
              - GET
              - POST
              - PUT
              - DELETE
      routes:
        #goods服务的路由配置
        - id: goods #唯一标识符
          #uri: http://localhost:9001 #指定要路由的地址 (单节点)
          # 集群部署 使用LoadBalancer 负载均衡访问微服务存活的节点 goods:服务名(多节点)
          uri: lb://goods
          predicates: #路由规则配置
          # 域名过滤路由
          #- Host=cloud.itheima.com** #表示所有以cloud.itheima.com的请求都将路由到 uri服务中
          # path过滤路由
          #- Path=/brand/**  #表示path以 /brand/的请求都将路由到uri服务中
          - Path=/api/goods/** #goods服务请求
          #
          filters:
          #- PrefixPath=/api #给所有的请求加上 /api 前缀
          - StripPrefix=1 #将请求路径中的第1个路径去掉,比如 /api/brand... 会将/api去除
          #网关限流配置
          - name: RequestRateLimiter #请求数限流 名字不能随便写
            args:
              key-resolver: "#{@ipKeyResolver}" #用户身份唯一标识符 调用启动类的Bean函数 获取用户IP
              redis-rate-limiter.replenishRate: 1 #每秒钟1个请求
              redis-rate-limiter.burstCapacity: 4 #最大宽限每秒并发4个请求
        #user用户服务的路由配置
        - id: user
          uri: lb://user
          predicates: #以下path的请求全部路由给user服务
          - Path=/api/address/**,/api/areas/**,/api/cities/**,/api/provinces/**,/api/user/**
          filters:
          - StripPrefix=1
server:
  port: 8001
#注册中心配置
eureka:
  client:
    service-url:
      defaultZone: http://114.55.**.**:9595/eureka
  instance:
    prefer-ip-address: true
management:
  endpoint:
    gateway:
      enabled: true
    web:
      exposure:
        include: true

3. 网关全局过滤器

/**
 * @author L
 * 网关全局过滤器,实现鉴权
 * 实现接口: GlobalFilter Ordered
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    private static final String AUTHORIZE_TOKEN = "Authorization";//token key

    /**
     * 业务处理体
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //获取令牌
        String token = request.getHeaders().getFirst(AUTHORIZE_TOKEN);//头信息中获取
        boolean flag = true;

        if (StringUtils.isEmpty(token)){
            flag = false;
            token = request.getQueryParams().getFirst(AUTHORIZE_TOKEN);//从请求参数中获取
        }
        if (StringUtils.isEmpty(token)){
            HttpCookie cookie = request.getCookies().getFirst(AUTHORIZE_TOKEN);
            if (cookie != null){
                token = cookie.getValue();//从Cookie中获取
            }
        }
        //没有令牌 拦截
        if (StringUtils.isEmpty(token)){
            //设置无权限的响应码 401
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //校验令牌
        try {
            Claims claims = JwtUtil.parse(token);
        } catch (Exception e) {
            //解析异常
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //将令牌封装到头信息中(令牌传递)
        request.mutate().header(AUTHORIZE_TOKEN,token);
        return chain.filter(exchange);
    }

    /**
     * 执行顺序,越小优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}

4.启动类

/**
 * @author L
 * 微服务网关启动类
 */
@SpringBootApplication
@EnableEurekaClient
public class GatewayWebApplication {
    public static void main(String[] args) {
        SpringApplication.run(GatewayWebApplication.class,args);
    }

    /**
     * 创建用户唯一标识,将ip作为用户唯一标识,根据ip进行限流操作
     */
    @Bean("ipKeyResolver")
    public KeyResolver userKeyResolver(){
        return new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                //获取用户IP
                String ip = exchange.getRequest().getRemoteAddress().getHostString();
                return Mono.just(ip);
            }
        };
    }
}

Java

留言板