微服务网关Gateway使用自定义Filter简单案例

一、相关依赖


  org.springframework.cloud
  spring-cloud-starter-gateway
server:
  port: 9527
spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true #开启从注册中心动态创建路由的功能,利用微服务名称进行路由
      routes:
        - id: payment_routh #路由的id,没有固定规则但要求唯一,建议配合服务名
          #uri: http://localhost:8001 固定ip
          uri: lb://cloud-payment-service #根据服务名称
          predicates:
           - Path=/payment/getById/**
        - id: payment_routh2
          #uri: http://localhost:8001
          uri: lb://cloud-payment-service #根据服务名称
          predicates:
           - Path=/payment/lb/**
           - After=2020-10-21T09:37:11.029+08:00[GMT+08:00]
eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    #表示是否将自己注册进Eureka Server 默认为true
    register-with-eureka: true
    #是否从Eureka Server抓取已有的注册信息,默认为true。单节点无所谓。集群必须设置为true才能配合ribbon使用负载均衡
    fetch-registry: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/,http://eureka7002.com:7002/eureka/


二、相关案例代码

@Component
@Slf4j
public class MyLogGatewayFilter implements GlobalFilter,Ordered {
    @Override
    public Mono filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("*******进入 全局日志过滤");
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if(uname==null){
            log.error("非法用户");
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }else {
            log.info("用户:{}访问系统",uname);
        }
        return chain.filter(exchange);
    }

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

你可能感兴趣的:(微服务,gateway,eureka)