Spring Cloud Zuul 使用 Groovy 便携 Filter

  1. 首先在pom.xml中引入groovy所需的jar
    
        org.codehaus.groovy
        groovy-all
        2.5.0-beta-2
    

     

  2. 在项目中编写GroovyFilter.groovy过滤器
    import com.netflix.zuul.ZuulFilter
    import com.netflix.zuul.context.RequestContext
    import com.netflix.zuul.exception.ZuulException
    import org.apache.catalina.servlet4preview.http.HttpServletRequest
    import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants
    
    class GroovyFilter extends ZuulFilter{
        @Override
        String filterType() {
            return FilterConstants.PRE_TYPE
        }
    
        @Override
        int filterOrder() {
            return 5 // 过滤器优先级
        }
    
        @Override
        boolean shouldFilter() {
            return true
        }
    
        @Override
        Object run() throws ZuulException {
            HttpServletRequest request = RequestContext.currentContext.getRequest() as HttpServletRequest
            Iterator headerIt = request.getHeaderNames().iterator();
            while (headerIt.hasNext()) {
                String name = (String) headerIt.next()
                String value = request.getHeader(name)
                println("header: " + name + ":" + value)
            }
            println("This is Groovy Filter")
            return null
        }
    }

     

  3. 在Application.java 启动主类中添加Groovy加载器
     @Component
        public static class GroovyRunner implements CommandLineRunner {
    
            @Override
            public void run(String... args) throws Exception {
                MonitoringHelper.initMocks();
                FilterLoader.getInstance().setCompiler(new GroovyCompiler());
                try {
                    FilterFileManager.setFilenameFilter(new GroovyFileFilter());
                    // 这里写书的是绝对路径F:\\MyWork\\IDEA\\mall-cloud\\groovy目录下
                    FilterFileManager.init(20, "F:\\MyWork\\IDEA\\mall-cloud\\groovy");
                } catch (Exception e) {
                    throw new RuntimeException();
                }
            }
        }

    编码结束,神奇的一幕即将来临。
    启动服务后:修改GroovyFilter.groovy中的输出语句,不需重启服务,精心等待一小会时间,重新发送请求,你会发现输出语句是当前修改的输出!

你可能感兴趣的:(Spring,Cloud)