Apollo热发布配置

一、背景

项目中需要用的阿波罗热发布,一种是利用注解ApolloConfigChangeListener的方式,可用如下配置就可。


@Component
@Slf4j
public class ApolloRefreshConfig2  implements ApplicationContextAware{

    @Autowired
    private RefreshScope refreshScope;
    private ApplicationContext applicationContext;

    @ApolloConfigChangeListener()
    public void onChange(ConfigChangeEvent changeEvent) {
        refreshProperties(changeEvent);
    }

    private void refreshProperties(ConfigChangeEvent changeEvent) {
        this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));
        refreshScope.refreshAll();
    }

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }
}

可是在测试中发现热部署并没有更新,后查看注解ApolloConfigChangeListener,发现如果不指定value值则默认namespace为 application。而我们项目中并没有使用application,而是拆分出来更多的命名空间;所以并不适用,需要指定value,如value={"edl-pub-service-common","Java.bmc-local-eureka","Java.bmc-pub-mysql","Java.bmc-redis","Java.bmc-rabbitmq","Java.bmc-httplog"};

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.METHOD)
@Documented
public @interface ApolloConfigChangeListener {
  /**
   * Apollo namespace for the config, if not specified then default to application
   */
  String[] value() default {ConfigConsts.NAMESPACE_APPLICATION};
  String[] interestedKeys() default {};
  String[] interestedKeyPrefixes() default {};
}

这里放一下我们的配置文件

# 应用ID(在Apollo服务端新增项目添加的应用ID)
app:
  id: bmc
# apollo-configservice地址
apollo:
  meta: http://10.197.236.187:7070
  bootstrap:
    enabled: true
    namespaces: edl-pub-service-common,Java.bmc-local-eureka,Java.bmc-pub-mysql,Java.bmc-redis,Java.bmc-rabbitmq,Java.bmc-httplog
    eagerLoad:
      enabled: true

可以不想再value中硬编码,那么问题来了:能否将value中的动态配置,比如读取配置文件中的数据?

二、尝试

1.@ApolloConfigChangeListener()注解的value直接设置EL表达式,结果------失败。

如下代码设置

    @ApolloConfigChangeListener(value = "${apollo.bootstrap.namespacesArr}")
    public void onChange(ConfigChangeEvent changeEvent) {
        refreshProperties(changeEvent);
    }

经过debug尝试,发现Apollo会默认注册 AutoUpdateConfigChangeListener监听器,如果扫描到ApolloConfigChangeListener注解也会注册到监听器中(源码见com.ctrip.framework.apollo.spring.annotation.ApolloAnnotationProcessor),可是在获取此注解的时候并没有判断是不是EL表达式,所以你传入 {apollo.bootstrap.namespacesArr} ,那么 namespace 的名称就是{apollo.bootstrap.namespacesArr};代码如下

@Override
  protected void processMethod(final Object bean, String beanName, final Method method) {
    ApolloConfigChangeListener annotation = AnnotationUtils
        .findAnnotation(method, ApolloConfigChangeListener.class);
    if (annotation == null) {
      return;
    }
    Class<?>[] parameterTypes = method.getParameterTypes();
    Preconditions.checkArgument(parameterTypes.length == 1,
        "Invalid number of parameters: %s for method: %s, should be 1", parameterTypes.length,
        method);
    Preconditions.checkArgument(ConfigChangeEvent.class.isAssignableFrom(parameterTypes[0]),
        "Invalid parameter type: %s for method: %s, should be ConfigChangeEvent", parameterTypes[0],
        method);

    ReflectionUtils.makeAccessible(method);
// *********** 重点在这里 ,直接读取 ***********
    String[] namespaces = annotation.value();
    String[] annotatedInterestedKeys = annotation.interestedKeys();
    String[] annotatedInterestedKeyPrefixes = annotation.interestedKeyPrefixes();
    ConfigChangeListener configChangeListener = new ConfigChangeListener() {
      @Override
      public void onChange(ConfigChangeEvent changeEvent) {
        ReflectionUtils.invokeMethod(method, bean, changeEvent);
      }
    };

    Set<String> interestedKeys = annotatedInterestedKeys.length > 0 ? Sets.newHashSet(annotatedInterestedKeys) : null;
    Set<String> interestedKeyPrefixes = annotatedInterestedKeyPrefixes.length > 0 ? Sets.newHashSet(annotatedInterestedKeyPrefixes) : null;

    for (String namespace : namespaces) {
      Config config = ConfigService.getConfig(namespace);

      if (interestedKeys == null && interestedKeyPrefixes == null) {
        config.addChangeListener(configChangeListener);
      } else {
        config.addChangeListener(configChangeListener, interestedKeys, interestedKeyPrefixes);
      }
    }
  }

所以该我们配置文件的属性改变因为不是指定的namespaces就不会更新。

2.利用反射动态修改@ApolloConfigChangeListener()注解的value,将value赋值为配置的属性,结果------失败。

此方法明显行不通,因为ApolloAnnotationProcessor中每次获取的ApolloConfigChangeListener 开始设置的值,而不是通过我们反射获取的值,反射的主要代码如下

 try {
                method = ApolloRefreshConfig.class.getMethod("onChange", ConfigChangeEvent.class);
                ApolloConfigChangeListener annotation = method.getAnnotation(ApolloConfigChangeListener.class);
                InvocationHandler invocationHandler = Proxy.getInvocationHandler(annotation);
                Field value = invocationHandler.getClass().getDeclaredField("memberValues");
                value.setAccessible(true);
                Map<String, String[]> stringObjectMap = (Map<String, String[]>) value.get(invocationHandler);
                stringObjectMap.put("value", namespacesArr);
            } catch (NoSuchMethodException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }

3.新写监听器,加入监听器集合中,结果------失败。

因为始终读取不到配置文件,猜测跟ApolloProcessor 继承 BeanPostProcessor有关吧。

@Component
@Slf4j
public class ApolloRefreshListener extends ApolloProcessor implements ApplicationContextAware {

    @Autowired
    private RefreshScope refreshScope;

    @Value("${apollo.bootstrap.namespaces}")
    private String namespaces;

    private ApplicationContext applicationContext;
    @Autowired
    private ConfigPropertySourceFactory configPropertySourceFactory;

/*    @PostConstruct
    private void init(){
        List<String> namespacesList = Lists.newArrayList();
        Splitter.on(",").omitEmptyStrings().split(namespaces).forEach(item -> namespacesList.add(item));
        namespacesArr = new String[namespacesList.size()];
    }*/


    @Override
    protected void processField(Object bean, String beanName, Field field) {
        ApolloConfig annotation = AnnotationUtils.getAnnotation(field, ApolloConfig.class);
        if (annotation == null) {
            return;
        }

        Preconditions.checkArgument(Config.class.isAssignableFrom(field.getType()),
                "Invalid type: %s for field: %s, should be Config", field.getType(), field);

        String namespace = annotation.value();
        Config config = ConfigService.getConfig(namespace);

        ReflectionUtils.makeAccessible(field);
        ReflectionUtils.setField(field, bean, config);
    }

    @Override
    protected void processMethod(final Object bean, String beanName, final Method method) {

        ApolloRefreshConfig apolloRefreshListener = new ApolloRefreshConfig();
        List<ConfigPropertySource> allConfigPropertySources = configPropertySourceFactory.getAllConfigPropertySources();
        for (ConfigPropertySource allConfigPropertySource : allConfigPropertySources) {
            Config config = ConfigService.getConfig(allConfigPropertySource.getName());
            config.addChangeListener(apolloRefreshListener);
        }
    }


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        this.applicationContext = applicationContext;
    }

}

三、结论

暂无解决办法,目前只有写死。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,490评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,581评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 165,830评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,957评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,974评论 6 393
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,754评论 1 307
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,464评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,357评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,847评论 1 317
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,995评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,137评论 1 351
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,819评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,482评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,023评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,149评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,409评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,086评论 2 355