请稍等 ...
×

采纳答案成功!

向帮助你的同学说点啥吧!感谢那些助人为乐的人

gateway全局过滤器没起作用问题

你好,我在gateway自定义了一个简单的全局过滤器,但是为什么我通过gateway调用微服务时,没有经过这个全局过滤器的?

gateway的配置和代码:

gateway的配置-application.yml:

server:
  port: 8100
  max-http-header-size: 4048576

spring:
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848
    sentinel:
      transport:
        port: 8720
        dashboard: 127.0.0.1:8080
    gateway:
      discovery:
        locator:
          # 让gateway通过服务发现组件找到其他的微服务
          enabled: true
          lower-case-service-id: true

  application:
    name: gateway

management:
  endpoints:
    web:
      exposure:
        include: '*'
  endpoint:
    health:
      show-details: always

全局过滤器1-bean方式

@Slf4j
@Configuration
// @EnableWebFluxSecurity
public class GatewaySecurityConfig {

    @Bean
    @Order(-1)
    public GlobalFilter PreLog() {
        return (exchange, chain) -> {
            log.info("==============================first pre filter");
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                ServerHttpRequest modifiedRequest = exchange.getRequest()
                        .mutate()
                        .build();
                HttpHeaders headers = modifiedRequest.getHeaders();
                List<String> authorization = headers.get("Authorization");
                log.info("=======================token inof================={}", authorization.toString());
                ServerWebExchange modifiedExchange = exchange.mutate()
                        .request(modifiedRequest)
                        .build();
                log.info("third post filter");
            }));
        };
    }

}

全局过滤器2-@Component方式

@Slf4j
@Component
public class PreLogGlobalGatewayFilter implements GlobalFilter, Ordered{
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        List<String> authorization = exchange.getRequest().getHeaders().get("Authorization");
        log.info("=======================token info================={}", authorization.toString());
        if (authorization == null) {
            exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
            return exchange.getResponse().setComplete();
        }
        return chain.filter(exchange);
    }

    /**
     * Get the order value of this object.
     * <p>Higher values are interpreted as lower priority. As a consequence,
     * the object with the lowest value has the highest priority (somewhat
     * analogous to Servlet {@code load-on-startup} values).
     * <p>Same order values will result in arbitrary sort positions for the
     * affected objects.
     * @return the order value
     * @see #HIGHEST_PRECEDENCE
     * @see #LOWEST_PRECEDENCE
     */
    @Override
    public int getOrder() {
        return 0;
    }
}

a系统调用B微服务

@GetMapping("/getDemoInfo/{demoInfo}")
    @ResponseBody
    public SimpleResponse<String> getInfo(@PathVariable String demoInfo,HttpServletRequest request) throws IOException {
        String access_token = CookieUtil.getToken(request, "access_token");
        String demoGetwAYUrl = "http://gateway.troylc.cn:8100/sso-demo/demo/testInfo/{demoInfo}";
        HttpHeaders headers = new HttpHeaders();
        headers.add("Authorization", "bearer " + access_token);
        ResponseEntity<SimpleResponse> returnDemoInfo = restTemplate.exchange(demoGetwAYUrl,HttpMethod.GET, new HttpEntity<>(headers),SimpleResponse.class, demoInfo);
        return returnDemoInfo.getBody();
    }

我从A应用中发一个调用B微服务的链接,经过gateway,但是没有进入这两个全局过滤器,这是为啥??
我直接访问gateway放开的全局过滤器的端点,也没有发现我自定义的这两个过滤器,这是为啥?

#url: http://gateway.troylc.cn:8100/actuator/gateway/globalfilters
{
org.springframework.cloud.gateway.filter.RemoveCachedBodyFilter@4978777f: -2147483648,
org.springframework.cloud.gateway.filter.ForwardRoutingFilter@67bd351e: 2147483647,
org.springframework.cloud.gateway.filter.NettyRoutingFilter@1b90fee4: 2147483647,
org.springframework.cloud.gateway.filter.RouteToRequestUrlFilter@7bc6935c: 10000,
org.springframework.cloud.gateway.filter.ForwardPathFilter@4cc7d00d: 0,
org.springframework.cloud.gateway.filter.NettyWriteResponseFilter@3513c84c: -1,
org.springframework.cloud.gateway.filter.LoadBalancerClientFilter@2e4389ed: 10100,
org.springframework.cloud.gateway.filter.WebsocketRoutingFilter@468e8565: 2147483646,
org.springframework.cloud.gateway.filter.GatewayMetricsFilter@91da29b: 0,
org.springframework.cloud.gateway.filter.AdaptCachedBodyGlobalFilter@3610f277: -2147482648
}

图片描述

正在回答 回答被采纳积分+3

1回答

大目 2020-03-23 22:28:58

https://img1.sycdn.imooc.com/szimg/5e78c74609cd55a127161654.jpg


您好,我拿您的代码测试(只去掉了Slf4j的日志打印)是可以进入的。

建议打个端点,看能否加载(断点上是否有对号),如果没加载,那应该是类所在的包有问题。

spring boot默认只会扫描启动类所在的包以及启动类的子包。

0 回复 有任何疑惑可以回复我~
  • 提问者 troylc #1
    我清空了idea的缓存,可调用到全局过滤器,可能是我idea的问题,但是日志不会被打印,为啥slf4j在里的打印不生效呢?
    回复 有任何疑惑可以回复我~ 2020-03-25 11:41:54
  • 大目 回复 提问者 troylc #2
    slf也是生效的吧。。
    我去掉slf4j只是因为我本地的gateway代码没有引入lombok而已
    回复 有任何疑惑可以回复我~ 2020-03-25 14:27:11
问题已解决,确定采纳
还有疑问,暂不采纳
意见反馈 帮助中心 APP下载
官方微信