美文网首页
2020-07-08---gateway

2020-07-08---gateway

作者: 李霖神谷 | 来源:发表于2020-07-08 14:38 被阅读0次

    1.什么是gateway:
    服务网关:它是基于spring5.0、spring boot2.0,和reactor开发的服务网关,它是基于filter提供了网关的基本功能:安全、监控、限流。
    它分为:路由、断言、拦截

    2.配置网关服务:首先pom文件中需要配置相关依赖。需要删除spring boot web和actor相关依赖。否则会启动失败

    
     <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-gateway</artifactId>
            </dependency>
    
    
    基于路劲的网关配置:
    spring:
      application:
        name: spring-cloud-gateway
      cloud:
        gateway:
          routes:
          - id: spring-cloud-gateway
            uri: http://localhost:8888
            predicates:
            - Path=/testGateway
    

    3.自定义网关拦截器:

    package com.shuai1.fileter;
    
    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;
    import sun.net.www.http.HttpClient;
    
    //自定义的拦截器
    @Component
    public class Myfilter implements GlobalFilter, Ordered {
        public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    //获取username参数
            String username= exchange.getRequest().getQueryParams().getFirst("username");
    //判断,为空的话返回相应的响应
            if(username==null){
                System.out.println("非法的用户,不能为空");
                exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
                return exchange.getResponse().setComplete();
            }
            return chain.filter(exchange);
        }
    
        public int getOrder() {
            return 0;
        }
    }
    
    

    相关文章

      网友评论

          本文标题:2020-07-08---gateway

          本文链接:https://www.haomeiwen.com/subject/tgpqcktx.html