此文属于博主原创,如有转载,一经查证,必进行法律制裁
整合之前必须要配置好apollo,并且启动,启动之后的界面为
然后编写pom.xml配置文件信息 org.springframework.boot spring-boot-starter-parent 2.0.1.RELEASE org.springframework.cloud spring-cloud-dependencies Finchley.M7 pom import org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client org.springframework.cloud spring-cloud-starter-netflix-zuul org.springframework.boot spring-boot-starter-actuator com.ctrip.framework.apollo apollo-client 1.2.0 com.spring4all swagger-spring-boot-starter 1.7.0.RELEASE spring-milestones Spring Milestones https://repo.spring.io/libs-milestone false
zuul网关的配置文件application.xml
server.port=81 ###eureka注册中心服务地址 #eureka.client.service-url.default-zone=http://localhost:8100/eureka/ eureka.client.serviceUrl.defaultZone=http://localhost:8100/eureka/ ###服务在注册中心的名称 spring.application.name=apollo-zuul ###开启swagger扫描 swagger.base-package=com.kaicom ###开启所有的端点,这个地方一定要配置,不然有坑 management.endpoints.web.exposure.include=* ###配置apollo app.id=springcloud-2.0-apollo apollo.meta=http://192.168.85.38:8080
第一种方式:
编写启动类 @SpringBootApplication @EnableEurekaClient @EnableZuulProxy @EnableSwagger2Doc @EnableApolloConfig @RestController public class AppGateWay {
public static final String ZUUL_PROPERTIES_BEAN = "ZUUL_PROPERTIES_BEAN"; @Value("${zuul.routes.api-a.path:defaultPath}") private String zuulMember ; /*@Autowired private ZuulProperties zuulProperties ;*/ public static void main(String[] args) throws Exception { SpringApplication.run(AppGateWay.class, args); } @Primary @Bean(ZUUL_PROPERTIES_BEAN) @ConfigurationProperties("zuul") @RefreshScope public ZuulProperties zuulProperties(){ return new ZuulProperties(); } @RequestMapping("/getMsg") public String getMsg(){ System.out.println("会员服务在apollo配置中心的信息 :"+zuulMember); return "会员服务在apollo配置中心的信息 :"+zuulMember; }}
编写配置文件修改监听 @Component public class ZuulPropertiesRefresher {
private static final Logger logger = LoggerFactory.getLogger(ZuulPropertiesRefresher.class);
@Autowired private RefreshScope refreshScope;
@ApolloConfigChangeListener public void onChange(ConfigChangeEvent changeEvent) { logger.info(“apollo配置文件监听启动”); boolean zuulPropertiesChanged = false; for (String changedKey : changeEvent.changedKeys()) { if (changedKey.startsWith(“zuul.”)) { zuulPropertiesChanged = true; break; } }
if (zuulPropertiesChanged) { logger.info("Refreshing zuul properties! 文件修改了"); refreshScope.refresh(AppGateWay.ZUUL_PROPERTIES_BEAN); } logger.info("是否修改了配置 -------------------> "+zuulPropertiesChanged); logger.info("apollo配置文件监听结束");} }
启动服务类,此时就可以进行实时刷新了
第二种方式: @RestController public class UserController {
@ApolloConfig private Config config; @GetMapping("getMsg") public String getMsg(){ //第一个参数代表在apollo配置中心中的key 第二个参数代表如果没有这个key的默认值 return config.getProperty("msg","default") ; }}