spring gateway网关常用的作用

时间:2020-06-09 14:14:39   收藏:0   阅读:102
spring:
application:
name: sysgateway
cloud:
gateway:
globalcors:
cors-configurations:
‘[/**]‘: # 匹配所有请求
allowedOrigins: "*" #跨域处理 允许所有的域
allowedMethods: # 支持的方法
- GET
- POST
- PUT
- DELETE
routes:
- id: goods
uri: lb://goods
predicates:
- Path=/goods/**
filters:
- StripPrefix= 1
- name: RequestRateLimiter #请求数限流 名字不能随便写
args:
key-resolver: "#{@ipKeyResolver}"
redis-rate-limiter.replenishRate: 1
redis-rate-limiter.burstCapacity: 1
- id: system
uri: lb://system
predicates:
- Path=/system/**
filters:
- StripPrefix= 1
# 配置Redis 127.0.0.1可以省略配置
redis:
host: 127.0.0.1
port: 6379
password: xxx
server:
port: 9101
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:6868/eureka
instance:
prefer-ip-address: true
login:
filter:
allowPaths:
- /system/admin/login

 

globalcors:
        cors-configurations:
          ‘[/**]‘: # 匹配所有请求
            allowedOrigins: "*" #跨域处理 允许所有的域
            allowedMethods: # 支持的方法
              - GET
              - POST
              - PUT
              - DELETE

 2这是微服务网关跨域。在controller控制类上加个@CrossOrigin配合使用

 

login:
  filter:
    allowPaths:
      - /system/admin/login

 

package com.changgou.config;

import org.springframework.boot.context.properties.ConfigurationProperties;

import java.util.List;

@ConfigurationProperties(prefix = "login.filter")
public class FilterProperties
{
    private List<String> allowPaths;

    public List<String> getAllowPaths() {
        return allowPaths;
    }

    public void setAllowPaths(List<String> allowPaths) {
        this.allowPaths = allowPaths;
    }
}

 

package com.changgou.filter;

import com.changgou.config.FilterProperties;
import com.changgou.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@EnableConfigurationProperties({FilterProperties.class})
public class loginFilter implements GlobalFilter, Ordered {

    @Autowired
    private FilterProperties properties;

    private  final static String TOKEN_NAME = "token";

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        List<String> allowPaths = properties.getAllowPaths();
        for (String allowPath : allowPaths){
            if (request.getURI().getPath().contains(allowPath)){
                return chain.filter(exchange);
            }
        }
        HttpHeaders headers = request.getHeaders();
        String token = headers.getFirst(TOKEN_NAME);
        if (StringUtils.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try
        {
            JwtUtil.parseJWT(token);
        } catch (Exception e)
        {
            e.printStackTrace();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        return chain.filter(exchange);
    }

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

 3.以上是网关通过过滤器做网关鉴权的功能。

  # 配置Redis 127.0.0.1可以省略配置
  redis:
    host: 127.0.0.1
    port: 6379
    password: xxxxxx

 

routes:
        - id: goods
          uri: lb://goods
          predicates:
            - Path=/goods/**
          filters:
            - StripPrefix= 1
            - name: RequestRateLimiter #请求数限流 名字不能随便写
              args:
                key-resolver: "#{@ipKeyResolver}"
                redis-rate-limiter.replenishRate: 1
                redis-rate-limiter.burstCapacity: 1

 

 

4,filters底下还可以配置网关限流的操作。是通过以上yml配置加上启动类注入一下类
@Bean
    public KeyResolver ipKeyResolver() {
        return new KeyResolver() {
            @Override
            public Mono<String> resolve(ServerWebExchange exchange) {
                return Mono.just(exchange.getRequest().getRemoteAddress().getHostName());
            }
        };
    }

 



原文:https://www.cnblogs.com/ykpkris/p/13072279.html

评论(0
© 2014 bubuko.com 版权所有 - 联系我们:wmxa8@hotmail.com
打开技术之扣,分享程序人生!