spring-cloud-zuul 使用groovy脚本实现filter的热刷新

苏磊
2023-12-01

本文建立在spring-cloud-zuul环境搭建的基础上进行扩展介绍。

介绍

    Zuul提供了一个能够对过滤器进行动态的加载、编译、运行的框架。这些过滤器是由Groovy写成,被放在Zuul Server上的特定目录下面。Zuul会按期轮询这些目录,修改过的过滤器会动态的加载到Zuul Server中。这样如果要对过滤器有改动,就不用进行网关的重新发布了,只需要把过滤器上传到指定目录即可。

    实现修改GroovyFilter.groovy中的代码,不需重启服务。

    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-netflix-zuul</artifactId>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy-all</artifactId>
            <version>2.5.0-beta-2</version>
        </dependency>
        <dependency>
            <groupId>org.codehaus.groovy</groupId>
            <artifactId>groovy</artifactId>
        </dependency>
    </dependencies>

使用groovy脚本的写Filter

package groovy

import com.netflix.zuul.ZuulFilter
import com.netflix.zuul.context.RequestContext
import com.netflix.zuul.exception.ZuulException
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants

import javax.servlet.http.HttpServletRequest

class GroovyFilter extends ZuulFilter {

    @Override
    String filterType() {
        return FilterConstants.PRE_TYPE;
    }

    @Override
    int filterOrder() {
        return 10
    }

    @Override
    boolean shouldFilter() {
        return true
    }

    @Override
    Object run() throws ZuulException {
        println("==== 这是一个 groovy 过滤器 ====")

        HttpServletRequest request = RequestContext.currentContext.request as HttpServletRequest
        Iterator headerIt = request.getHeaderNames().iterator()
        while (headerIt.hasNext()) {
            String name = headerIt.next()
            String value = request.getHeader(name)
            println("header:" + name + ":" + value)
        }

        return null
    }
}

启动器中加载脚本

@EnableEurekaClient
@SpringBootApplication
@EnableZuulProxy
public class ZuulApplication {

    private static final Logger LOGGER = LoggerFactory.getLogger(ZuulApplication.class);

    public static void main(String[] args) {
        SpringApplication.run(ZuulApplication.class, args);
        LOGGER.info("================ zuul start success ==============");
    }

    @Component
    public static class GroovyRunner implements CommandLineRunner{
        @Override
        public void run(String... args) throws Exception {
            MonitoringHelper.initMocks();
            FilterLoader.getInstance().setCompiler(new GroovyCompiler());
            FilterFileManager.setFilenameFilter(new GroovyFileFilter());
            //每隔5秒刷新一次配置文件
            FilterFileManager.init(5, "\zuul\zuul-groovy\src\main\resources\groovy");
        }
    }

}

 

 类似资料: