Implementing Zuul Filter - TheOpenCloudEngine/uEngine-cloud GitHub Wiki

Zuul Filter

Zuul ์€ dynamic routing ๋“ฑ์„ ์ˆ˜ํ–‰ํ•  ์ˆ˜ ์žˆ๋Š” gateway ์„œ๋น„์Šค, Routing ๊ธฐ๋Šฅ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ,
http ์š”์ฒญ๊ณผ ์‘๋‹ต ์‚ฌ์ด์—์„œ ๋™์ž‘ํ•˜๋Š” filter๋ฅผ ์ง€์›ํ•จ์œผ๋กœ์จ filter ๊ตฌํ˜„๋‚ด์šฉ์— ๋”ฐ๋ผ
๋” ๋‹ค์–‘ํ•œ ๊ธฐ๋Šฅ์„ ์ถ”๊ฐ€ํ•  ์ˆ˜ ์žˆ๊ณ  ์ „์ฒด์ ์œผ๋กœ ์œ ์—ฐํ•œ ์„œ๋น„์Šค ๊ตฌ์„ฑ์ด ๊ฐ€๋Šฅํ•˜๋‹ค.

Zuul์˜ (spring-cloud-netflix reference ๋ฌธ์„œ) ๋ฅผ ๋ณด๋ฉด
filter ๋ฅผ ์ด pre, route, post ๋กœ 3๊ฐ€์ง€๋กœ ์„ค์ • ํ•  ์ˆ˜ ์žˆ๊ฒŒ ๋˜์–ด์žˆ๋‹ค.
pre filter ๋Š” request ๊ฐ€ ๋“ค์–ด์™”์„๋•Œ ์ฒ˜์Œ์— ๊ฑธ์–ด ๋†“๋Š”๋‹ค๋Š” ์˜๋ฏธ๋‹ค.
์˜ˆ์ œ๋ฅผ ๋ณด๋ฉด์„œ ์‚ดํŽด๋ณด์ž.

https://github.com/TheOpenCloudEngine/uEngine-cloud/tree/master/uengine-cloud-zuul/src/main/java/org/uengine/zuul/pre

IAMFilter.java

public class IAMFilter extends ZuulFilter {
    @Override
    public String filterType() {
        return "pre";
    }
    @Override
    public int filterOrder() {
        return 1;
    }
    @Override
    public boolean shouldFilter() {
        return true;
    }
    @Override
    public Object run() {
       RuleService ruleService = ApplicationContextRegistry.getApplicationContext().getBean(RuleService.class);
       // do something
       //๋ผ์šฐํ„ฐ ์Šค์ฝ”ํ”„
       Map<String, String> iamScopes = null;
       if (routeValueMap.containsKey("iam-scopes")) {
           iamScopes = (Map<String, String>) routeValueMap.get("iam-scopes");
       }
       // do something
    }

๊ตฌํ˜„ ๋‚ด์šฉ์€ ์ œ์™ธ ํ•˜์˜€์ง€๋งŒ ZuulFilter๋ฅผ extends ํ•˜์˜€๊ณ ,
LifeCycle ์˜ filterType์„ "pre", filter์˜ Order ๋ฅผ ์ค„์ˆ˜ ์žˆ๊ณ , filter๊ฐ€ ๋™์ž‘ํ•˜๋Š” ๋ถ€๋ถ„์ด run ์ด๋‹ค.

์•„๋ž˜๋Š” filter ๋ฅผ ์‚ฌ์šฉํ•˜์—ฌ custom scope๋ฅผ ๋งŒ๋“œ๋Š” ์˜ˆ์ œ์ด๋‹ค.

application.yml

zuul:
    routes:
        courses:
          path: /courses/**
          serviceId: course
          stripPrefix: false
          # ์ผ๋ฐ˜ ๊ฒŒ์ŠคํŠธ ์œ ์ €์— ๋Œ€ํ•ด์„œ๋Š” (GET) ํ—ˆ์šฉ, catalog-order scope ์„ ๊ฐ€์ง„ ์œ ์ €์ธ ๊ฒฝ์šฐ PUT, PATCH, POST, DELETE ํ—ˆ์šฉ
          iam-scopes:
            - guest/GET
            - catalog-order/PUT-PATCH-POST-DELETE

์šฐ์„  yml ํŒŒ์ผ์˜ zuul ์„ ๊ฐ€์ ธ์˜ค๊ฒŒ ํ•˜๋ ค๋ฉด ์•„๋ž˜์™€ ๊ฐ™์ด ConfigurationProperties ๋ฅผ ์‚ฌ์šฉํ•˜๋ฉด ๋œ๋‹ค.

RuleService.java

@Service
@ConfigurationProperties(prefix = "zuul")
public class RuleService {
  private Map<String, Map> routes;
  ...
}

์ด๋Ÿฐ์‹์œผ๋กœ ์„ค์ •ํŒŒ์ผ์—์„œ property๊ฐ’์„ ๋ฐ›์•„์™€์„œ ZuulFilter์˜ run ๋ถ€๋ถ„์—์„œ ๊ตฌํ˜„์„ ํ•˜๋ฉด ๋œ๋‹ค.
์ด์ œ ์ด๋ ‡๊ฒŒ ๊ตฌํ˜„ํ•œ filter๋ฅผ ์‚ฌ์šฉํ•˜๋ ค๋ฉด ์•„๋ž˜์ฒ˜๋Ÿผ @Bean ์œผ๋กœ ๋“ฑ๋ก์„ ํ•ด์ฃผ๋ฉด ๋œ๋‹ค.

Application.java

public class Application {
  ...
  @Bean
  public IAMFilter iamFilter(){
      return new IAMFilter();
  }
}
โš ๏ธ **GitHub.com Fallback** โš ๏ธ