Gateway网关

Gateway网关_第1张图片
引入maven依赖

		 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
         </dependency>

注意:引入gateway依赖的同时,引入nacos依赖,成为微服务,实现服务之间的调用
配置文件application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: http://example.org
        predicates:
        - Path=/foo/{segment},/bar/{segment}

这个路由匹配以/foo或者/bar开头的路径,转发到http:example.org。例如 /foo/1 or /foo/bar or /bar/baz.

spring:
  cloud:
    gateway:
      routes:
        - id: nacos-consumer 唯一标识
          ## uri: http://127.0.0.1:8080 建议使用服务名
          lb://nacos-consumer
          predicates:
            - Path=/hi
        - id: nacos-provider
          uri: http://127.0.0.1:8070
          predicates:
            - Path=/hello  ## 匹配/hello的请求

Gateway网关_第2张图片
上面的配置中,所有的/foo/**开始的路径都会命中配置的router,并执行过滤器的逻辑,在本案例中配置了RewritePath过滤器工厂,此工厂将/foo/(?.*)重写为{segment},然后转发到http://example.org。比如在网页上请求localhost:8090/foo/forezp,此时会将请求转发到http://example.org/forezp的页面

自定义过滤器

1.创建自定义过滤器类实现GatewayFilter接口,添加到spring容器中,重写public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain)方法
以校验登录cookie为例

 	@Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        // 获取request和response,注意:不是HttpServletRequest及HttpServletResponse
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取所有cookie
        MultiValueMap<String, HttpCookie> cookies = request.getCookies();
        // 如果cookies为空或者不包含指定的token,则相应认证未通过
        if (CollectionUtils.isEmpty(cookies) || !cookies.containsKey(this.jwtProperties.getCookieName())) {
            // 响应未认证!
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            // 结束请求
            return response.setComplete();
        }
        // 获取cookie
        HttpCookie cookie = cookies.getFirst(this.jwtProperties.getCookieName());
        try {
            // 校验cookie
            JwtUtils.getInfoFromToken(cookie.getValue(), this.jwtProperties.getPublicKey());
        } catch (Exception e) {
            e.printStackTrace();
            // 校验失败,响应未认证
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 认证通过放行
        return chain.filter(exchange);
    }

2.创建过滤器工厂,继承AbstractGatewayFilterFactory类,并注入到spring容器中,将自定义的过滤器对象注入到重写的apply方法中

@Component
public class AuthGatewayFilterFactory extends AbstractGatewayFilterFactory<Object> {

    @Autowired
    private AuthGatewayFilter authGatewayFilter;

    @Override
    public GatewayFilter apply(Object config) {
        return authGatewayFilter;
    }
}

3.配置文件使用过滤器,只需要命名前缀
Gateway网关_第3张图片

你可能感兴趣的:(springcloud)