Zuul过滤器动态加载
程序员文章站
2022-07-12 19:10:31
...
一 添加groovy依赖
<dependency>
<groupId>org.codehaus.groovy</groupId>
<artifactId>groovy-all</artifactId>
<version>2.4.12</version>
</dependency>
二 编写启动类
package org.crazyit.cloud;
import java.io.File;
import javax.annotation.PostConstruct;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.cloud.netflix.zuul.EnableZuulProxy;
import com.netflix.zuul.FilterFileManager;
import com.netflix.zuul.FilterLoader;
import com.netflix.zuul.groovy.GroovyCompiler;
import com.netflix.zuul.groovy.GroovyFileFilter;
@SpringBootApplication
@EnableEurekaClient
@EnableZuulProxy
public class GatewayApp {
@PostConstruct
public void zuulInit() {
FilterLoader.getInstance().setCompiler(new GroovyCompiler());
// 读取配置,获取脚本根目录
String scriptRoot = System.getProperty("zuul.filter.root", "groovy/filters");
// 获取刷新间隔
String refreshInterval = System.getProperty("zuul.filter.refreshInterval", "5");
if (scriptRoot.length() > 0) scriptRoot = scriptRoot + File.separator;
try {
FilterFileManager.setFilenameFilter(new GroovyFileFilter());
FilterFileManager.init(Integer.parseInt(refreshInterval), scriptRoot + "pre",
scriptRoot + "route", scriptRoot + "post");
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
new SpringApplicationBuilder(GatewayApp.class).web(true).run(args);
}
}
三 构造动态加载目录
四 新建动态加载的过滤器
package groovy.filters;
import org.springframework.cloud.netflix.zuul.filters.support.FilterConstants;
import com.netflix.zuul.ZuulFilter;
class DynamicFilter extends ZuulFilter {
public boolean shouldFilter() {
return true;
}
public Object run() {
System.out.println("========= 这一个是动态加载的过滤器:DynamicFilter");
return null;
}
public String filterType() {
return FilterConstants.ROUTE_TYPE;
}
public int filterOrder() {
return 3;
}
}
五 动态加载前效果
1 浏览器输入
http://localhost:9000/sale/food-sale/1
2 控制台输出
执行 MyFilter 过滤器
六 动态加载后效果
1 将动态加载过滤器拷贝到groovy.filters.route目录
2 浏览器输入
http://localhost:9000/sale/food-sale/1
3 控制台输出
执行 MyFilter 过滤器
========= 这一个是动态加载的过滤器:DynamicFilter