Spring Cloud Gateway Filter ordering
Asked Answered
M

2

5

I'm using spring cloud gateway filter, and want to filter request by GatewayFilterFactory, but order not working with @Order annotation

I tried to swap the order of filters, but not working.


@Slf4j
@Order(1)
@Component
public class AccessFilter implements GatewayFilterFactory<AccessFilter.Config> {

    @Override
    public GatewayFilter apply(AccessFilter.Config config) {
        return (exchange, chain) -> { 
           log.info("in AccessFilter second");
           // do something
        }
    }
}

@Order(-1)
@Slf4j
@Component
public class AddTraceIdGlobalFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("in globalfilter first");
        // do something
    }

}

My yaml file:

spring:
  cloud:
    gateway:
      routes:
      - id: user_1
        uri: http://user:8080
        predicates:
        - Path=/v1/user/info
        filters:
        - AccessFilter

I expect the output:

in globalfilter first
in AccessFilter second

but the actual output:

in AccessFilter second
in globalfilter first
Micron answered 21/5, 2019 at 6:46 Comment(0)
H
8

GatewayFilterFactory cannot be applied @Order or Ordered. You have to use OrderedGatewayFilter.

@Component
public class AccessFilter implements GatewayFilterFactory<AccessFilter.Config> {

    @Override
    public GatewayFilter apply(AccessFilter.Config config) {
        return new OrderedGatewayFilter((exchange, chain) -> { 
           log.info("in AccessFilter second");
           // do something
        }, 1)
    }
}
Harald answered 7/8, 2019 at 15:43 Comment(0)
T
0

You can implement Ordered interface:

public class RewriteTokenGlobalPreFilter implements GlobalFilter, Ordered 
{
     ....

     @Override
     public int getOrder() {
        return 3;
     }
}
Tound answered 8/11, 2022 at 10:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.