本章将介绍如何通过Apollo配置中心与Zuul实现动态路由 并实现热更新
专栏目录:
欢迎关注个人公众号: Coder编程
欢迎关注个人网站:www.52melrin.com
版本
Apollo: 0.10.2
SpringBoot: 2.0.3.RELEASE
正文
@EnableApolloConfig
@EnableZuulProxy
@SpringBootApplication
public class Application {
static final String ZUUL_PROPERTIES_BEAN = "ZUUL_PROPERTIES_BEAN";
@Primary
@Bean(ZUUL_PROPERTIES_BEAN)
@RefreshScope
@ConfigurationProperties("zuul")
public ZuulProperties zuulProperties() {
return new ZuulProperties();
}
public static void main(String[] args) throws Exception {
System.setProperty("java.awt.headless", "false");
ApplicationContext context = new SpringApplicationBuilder(Application.class).run(args);
Desktop.getDesktop().browse(
new URI("http://localhost:" + context.getEnvironment().getProperty("server.port", "8080")));
}
}
ZuulPropertiesRefresher.java
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.context.scope.refresh.RefreshScope;
import org.springframework.stereotype.Component;
@Component
public class ZuulPropertiesRefresher {
private static final Logger logger = LoggerFactory.getLogger(ZuulPropertiesRefresher.class);
@Autowired
private RefreshScope refreshScope;
@ApolloConfigChangeListener
public void onChange(ConfigChangeEvent changeEvent) {
boolean zuulPropertiesChanged = false;
for (String changedKey : changeEvent.changedKeys()) {
if (changedKey.startsWith("zuul.")) {
zuulPropertiesChanged = true;
break;
}
}
if (zuulPropertiesChanged) {
logger.info("Refreshing zuul properties!");
refreshScope.refresh(Application.ZUUL_PROPERTIES_BEAN);
}
}
}
将application.properties 内容复制到Apollo配置中心
server.port = 9090
zuul.routes.users.path = /**
zuul.routes.users.url = https://www.baidu.com
![](https://i-blog.csdnimg.cn/blog_migrate/bf525f7637b3a5c9dc1a5970f661b2c9.png)
启动项目,成功跳转百度页面.
在不重启项目的情况下修改路由地址: zuul.routes.users.url = https://www.blog.csdn.net/
可以看到成功跳转至CSDN页面。