com.ctrip.framework.apollo.model.ConfigChangeEvent Java Examples

The following examples show how to use com.ctrip.framework.apollo.model.ConfigChangeEvent. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JavaConfigAnnotationTest.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Test
public void testApolloConfigChangeListenerWithYamlFile() throws Exception {
  String someKey = "someKey";
  String someValue = "someValue";
  String anotherValue = "anotherValue";

  YamlConfigFile configFile = prepareYamlConfigFile(APPLICATION_YAML_NAMESPACE,
      readYamlContentAsConfigFileProperties("case9.yml"));

  TestApolloConfigChangeListenerWithYamlFile bean = getBean(TestApolloConfigChangeListenerWithYamlFile.class, AppConfig9.class);

  Config yamlConfig = bean.getYamlConfig();
  SettableFuture<ConfigChangeEvent> future = bean.getConfigChangeEventFuture();

  assertEquals(someValue, yamlConfig.getProperty(someKey, null));
  assertFalse(future.isDone());

  configFile.onRepositoryChange(APPLICATION_YAML_NAMESPACE, readYamlContentAsConfigFileProperties("case9-new.yml"));

  ConfigChangeEvent configChangeEvent = future.get(100, TimeUnit.MILLISECONDS);
  ConfigChange change = configChangeEvent.getChange(someKey);
  assertEquals(someValue, change.getOldValue());
  assertEquals(anotherValue, change.getNewValue());

  assertEquals(anotherValue, yamlConfig.getProperty(someKey, null));
}
 
Example #2
Source File: ApolloMockServerApiTest.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Test
public void testDeleteSamePropertyTwice() throws Exception {
  Config otherConfig = ConfigService.getConfig(anotherNamespace);

  final Semaphore changes = new Semaphore(0);

  otherConfig.addChangeListener(new ConfigChangeListener() {
    @Override
    public void onChange(ConfigChangeEvent changeEvent) {
      changes.release();
    }
  });

  assertEquals("otherValue6", otherConfig.getProperty("key6", null));

  embeddedApollo.deleteProperty(anotherNamespace, "key6");
  embeddedApollo.deleteProperty(anotherNamespace, "key6");

  assertTrue(changes.tryAcquire(5, TimeUnit.SECONDS));
  assertNull(otherConfig.getProperty("key6", null));
  assertEquals(0, changes.availablePermits());
}
 
Example #3
Source File: ApolloMockServerApiTest.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Test
public void testUpdateSamePropertyTwice() throws Exception {
  String someNewValue = "someNewValue";

  Config otherConfig = ConfigService.getConfig(anotherNamespace);

  final Semaphore changes = new Semaphore(0);

  otherConfig.addChangeListener(new ConfigChangeListener() {
    @Override
    public void onChange(ConfigChangeEvent changeEvent) {
      changes.release();
    }
  });

  assertEquals("otherValue3", otherConfig.getProperty("key3", null));

  embeddedApollo.addOrModifyProperty(anotherNamespace, "key3", someNewValue);
  embeddedApollo.addOrModifyProperty(anotherNamespace, "key3", someNewValue);

  assertTrue(changes.tryAcquire(5, TimeUnit.SECONDS));
  assertEquals(someNewValue, otherConfig.getProperty("key3", null));
  assertEquals(0, changes.availablePermits());
}
 
Example #4
Source File: ZuulPropertiesRefresher.java    From apollo-use-cases with Apache License 2.0 6 votes vote down vote up
private void refreshZuulProperties(ConfigChangeEvent changeEvent) {
  logger.info("Refreshing zuul properties!");

  /**
   * rebind configuration beans, e.g. ZuulProperties
   * @see org.springframework.cloud.context.properties.ConfigurationPropertiesRebinder#onApplicationEvent
   */
  this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));

  /**
   * refresh routes
   * @see org.springframework.cloud.netflix.zuul.ZuulServerAutoConfiguration.ZuulRefreshListener#onApplicationEvent
   */
  this.applicationContext.publishEvent(new RoutesRefreshedEvent(routeLocator));

  logger.info("Zuul properties refreshed!");
}
 
Example #5
Source File: ZuulPropertiesRefresher.java    From mini-platform with MIT License 6 votes vote down vote up
private void refreshZuulProperties(ConfigChangeEvent changeEvent) {
    logger.info("Refreshing zuul properties!");

    /**
     * rebind configuration beans, e.g. ZuulProperties
     * @see org.springframework.cloud.context.properties.ConfigurationPropertiesRebinder#onApplicationEvent
     */
    this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));

    /**
     * refresh routes
     * @see org.springframework.cloud.netflix.zuul.ZuulServerAutoConfiguration.ZuulRefreshListener#onApplicationEvent
     */
    this.applicationContext.publishEvent(new RoutesRefreshedEvent(routeLocator));

    logger.info("Zuul properties refreshed!");
}
 
Example #6
Source File: AutoUpdateConfigChangeListener.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Override
public void onChange(ConfigChangeEvent changeEvent) {
  Set<String> keys = changeEvent.changedKeys();
  if (CollectionUtils.isEmpty(keys)) {
    return;
  }
  for (String key : keys) {
    // 1. check whether the changed key is relevant
    Collection<SpringValue> targetValues = springValueRegistry.get(beanFactory, key);
    if (targetValues == null || targetValues.isEmpty()) {
      continue;
    }

    // 2. update the value
    for (SpringValue val : targetValues) {
      updateSpringValue(val);
    }
  }
}
 
Example #7
Source File: AbstractConfig.java    From apollo with Apache License 2.0 6 votes vote down vote up
protected void fireConfigChange(final ConfigChangeEvent changeEvent) {
  for (final ConfigChangeListener listener : m_listeners) {
    // check whether the listener is interested in this change event
    if (!isConfigChangeListenerInterested(listener, changeEvent)) {
      continue;
    }
    m_executorService.submit(new Runnable() {
      @Override
      public void run() {
        String listenerName = listener.getClass().getName();
        Transaction transaction = Tracer.newTransaction("Apollo.ConfigChangeListener", listenerName);
        try {
          listener.onChange(changeEvent);
          transaction.setStatus(Transaction.SUCCESS);
        } catch (Throwable ex) {
          transaction.setStatus(ex);
          Tracer.logError(ex);
          logger.error("Failed to invoke config change listener {}", listenerName, ex);
        } finally {
          transaction.complete();
        }
      }
    });
  }
}
 
Example #8
Source File: SimpleConfig.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void onRepositoryChange(String namespace, Properties newProperties) {
  if (newProperties.equals(m_configProperties)) {
    return;
  }
  Properties newConfigProperties = propertiesFactory.getPropertiesInstance();
  newConfigProperties.putAll(newProperties);

  List<ConfigChange> changes = calcPropertyChanges(namespace, m_configProperties, newConfigProperties);
  Map<String, ConfigChange> changeMap = Maps.uniqueIndex(changes,
      new Function<ConfigChange, String>() {
        @Override
        public String apply(ConfigChange input) {
          return input.getPropertyName();
        }
      });

  updateConfig(newConfigProperties, m_configRepository.getSourceType());
  clearConfigCache();

  this.fireConfigChange(new ConfigChangeEvent(m_namespace, changeMap));

  Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace);
}
 
Example #9
Source File: SimpleApolloConfigDemo.java    From apollo with Apache License 2.0 6 votes vote down vote up
public SimpleApolloConfigDemo() {
  ConfigChangeListener changeListener = new ConfigChangeListener() {
    @Override
    public void onChange(ConfigChangeEvent changeEvent) {
      logger.info("Changes for namespace {}", changeEvent.getNamespace());
      for (String key : changeEvent.changedKeys()) {
        ConfigChange change = changeEvent.getChange(key);
        logger.info("Change - key: {}, oldValue: {}, newValue: {}, changeType: {}",
            change.getPropertyName(), change.getOldValue(), change.getNewValue(),
            change.getChangeType());
      }
    }
  };
  config = ConfigService.getAppConfig();
  config.addChangeListener(changeListener);
}
 
Example #10
Source File: DefaultConfig.java    From apollo with Apache License 2.0 6 votes vote down vote up
@Override
public synchronized void onRepositoryChange(String namespace, Properties newProperties) {
  if (newProperties.equals(m_configProperties.get())) {
    return;
  }

  ConfigSourceType sourceType = m_configRepository.getSourceType();
  Properties newConfigProperties = propertiesFactory.getPropertiesInstance();
  newConfigProperties.putAll(newProperties);

  Map<String, ConfigChange> actualChanges = updateAndCalcConfigChanges(newConfigProperties, sourceType);

  //check double checked result
  if (actualChanges.isEmpty()) {
    return;
  }

  this.fireConfigChange(new ConfigChangeEvent(m_namespace, actualChanges));

  Tracer.logEvent("Apollo.Client.ConfigChanges", m_namespace);
}
 
Example #11
Source File: ApolloMockServerSpringIntegrationTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Test
@DirtiesContext
public void testListenerTriggeredByDel()
    throws InterruptedException, ExecutionException, TimeoutException {
  embeddedApollo.deleteProperty(otherNamespace, "key1");
  ConfigChangeEvent changeEvent = testBean.futureData.get(5000, TimeUnit.MILLISECONDS);
  assertEquals(otherNamespace, changeEvent.getNamespace());
  assertEquals(PropertyChangeType.DELETED, changeEvent.getChange("key1").getChangeType());
}
 
Example #12
Source File: ApolloMockServerSpringIntegrationTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Test
@DirtiesContext
public void shouldNotifyOnInterestedPatterns() throws Exception {
  embeddedApollo.addOrModifyProperty(otherNamespace, "server.port", "8080");
  embeddedApollo.addOrModifyProperty(otherNamespace, "server.path", "/apollo");
  embeddedApollo.addOrModifyProperty(otherNamespace, "spring.application.name", "whatever");
  ConfigChangeEvent changeEvent = testInterestedKeyPrefixesBean.futureData.get(5000, TimeUnit.MILLISECONDS);
  assertEquals(otherNamespace, changeEvent.getNamespace());
  assertEquals("8080", changeEvent.getChange("server.port").getNewValue());
  assertEquals("/apollo", changeEvent.getChange("server.path").getNewValue());
}
 
Example #13
Source File: ZuulRateLimitPropertiesRefreshConfig.java    From apollo-use-cases with Apache License 2.0 5 votes vote down vote up
@ApolloConfigChangeListener(interestedKeyPrefixes = PREFIX)
public void onChange(ConfigChangeEvent changeEvent) {
  logger.info("Refreshing Zuul rateLimit Properties");

  this.applicationContext.publishEvent(new EnvironmentChangeEvent(changeEvent.changedKeys()));

  logger.info("Zuul rateLimit Properties refreshed!");
}
 
Example #14
Source File: ApolloMockServerSpringIntegrationTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Test
@DirtiesContext
public void testListenerTriggeredByAdd() throws InterruptedException, ExecutionException, TimeoutException {
  embeddedApollo.addOrModifyProperty(otherNamespace, "someKey", "someValue");
  ConfigChangeEvent changeEvent = testBean.futureData.get(5000, TimeUnit.MILLISECONDS);
  assertEquals(otherNamespace, changeEvent.getNamespace());
  assertEquals("someValue", changeEvent.getChange("someKey").getNewValue());
}
 
Example #15
Source File: ApolloConfig.java    From java-tutorial with MIT License 5 votes vote down vote up
@ApolloConfigChangeListener(ConfigConsts.NAMESPACE_APPLICATION)
public void onChange(ConfigChangeEvent changeEvent) {
    logger.info("before refresh");
    for (String changedKey : changeEvent.changedKeys()) {
        logger.info("===============================================================");
        logger.info("changedKey:{} value:{}", changedKey, changeEvent.getChange(changedKey));
        ConfigChange configChange = changeEvent.getChange(changedKey);
        configChange.getOldValue();
    }
    refreshScope.refreshAll();
    logger.info("after refresh");
}
 
Example #16
Source File: SpringBootApolloRefreshConfig.java    From apollo with Apache License 2.0 5 votes vote down vote up
@ApolloConfigChangeListener(value = {ConfigConsts.NAMESPACE_APPLICATION, "TEST1.apollo", "application.yaml"},
    interestedKeyPrefixes = {"redis.cache."})
public void onChange(ConfigChangeEvent changeEvent) {
  logger.info("before refresh {}", sampleRedisConfig.toString());
  refreshScope.refresh("sampleRedisConfig");
  logger.info("after refresh {}", sampleRedisConfig.toString());
}
 
Example #17
Source File: ApolloDataSource.java    From Sentinel with Apache License 2.0 5 votes vote down vote up
private void initializeConfigChangeListener() {
    configChangeListener = new ConfigChangeListener() {
        @Override
        public void onChange(ConfigChangeEvent changeEvent) {
            ConfigChange change = changeEvent.getChange(ruleKey);
            //change is never null because the listener will only notify for this key
            if (change != null) {
                RecordLog.info("[ApolloDataSource] Received config changes: " + change.toString());
            }
            loadAndUpdateRules();
        }
    };
    config.addChangeListener(configChangeListener, Sets.newHashSet(ruleKey));
}
 
Example #18
Source File: ApolloConfigWrapperTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertAddChangeListener() throws Exception {
    final SettableFuture<ConfigChangeEvent> future = SettableFuture.create();
    ConfigChangeListener listener = future::set;
    configWrapper.addChangeListener(listener, Collections.singleton("test.children.2"));
    embeddedApollo.addOrModifyProperty("orchestration", "test.children.2", "value3");
    ConfigChangeEvent changeEvent = future.get(5, TimeUnit.SECONDS);
    assertTrue(changeEvent.isChanged("test.children.2"));
    assertThat(changeEvent.getChange("test.children.2").getOldValue(), is("value2"));
    assertThat(changeEvent.getChange("test.children.2").getNewValue(), is("value3"));
    assertThat(changeEvent.getChange("test.children.2").getChangeType(), is(PropertyChangeType.MODIFIED));
}
 
Example #19
Source File: ApolloConfigLoader.java    From tunnel with Apache License 2.0 5 votes vote down vote up
@Override
public void onChange(ConfigChangeEvent changeEvent) {
    Set<String> keys = changeEvent.changedKeys();
    for (String key : keys) {
        ConfigChange change = changeEvent.getChange(key);
        if (change == null) {
            continue;
        }

        String oldValue = change.getOldValue();
        String newValue = change.getNewValue();
        configListener.onChange(key, oldValue, newValue);
    }
}
 
Example #20
Source File: ApolloDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 5 votes vote down vote up
private void initializeConfigChangeListener() {
    configChangeListener = new ConfigChangeListener() {
        @Override
        public void onChange(ConfigChangeEvent changeEvent) {
            ConfigChange change = changeEvent.getChange(ruleKey);
            //change is never null because the listener will only notify for this key
            if (change != null) {
                RecordLog.info("[ApolloDataSource] Received config changes: " + change.toString());
            }
            loadAndUpdateRules();
        }
    };
    config.addChangeListener(configChangeListener, Sets.newHashSet(ruleKey));
}
 
Example #21
Source File: ApolloConfigWrapperTest.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
@Test
public void assertAddChangeListenerWithInterestedKeyPrefixes() throws Exception {
    final SettableFuture<ConfigChangeEvent> future = SettableFuture.create();
    ConfigChangeListener listener = future::set;
    configWrapper.addChangeListener(listener, Collections.singleton("test.children.1"), Collections.singleton("test.children.2"));
    embeddedApollo.addOrModifyProperty("orchestration", "test.children.2.1", "value4");
    ConfigChangeEvent changeEvent = future.get(5, TimeUnit.SECONDS);
    assertTrue(changeEvent.isChanged("test.children.2.1"));
    assertThat(changeEvent.getChange("test.children.2.1").getNewValue(), is("value4"));
    assertThat(changeEvent.getChange("test.children.2.1").getChangeType(), is(PropertyChangeType.ADDED));
}
 
Example #22
Source File: ZuulPropertiesRefresher.java    From mini-platform with MIT License 5 votes vote down vote up
@ApolloConfigChangeListener
    public void onChange(ConfigChangeEvent changeEvent) {
        refreshZuulProperties(changeEvent);
//        boolean zuulPropertiesChanged = false;
//        for (String changedKey : changeEvent.changedKeys()) {
//            if (changedKey.startsWith("zuul.")||changedKey.startsWith("link.") || changedKey.contains(".ribbon.listOfServers")) {
//                zuulPropertiesChanged = true;
//                break;
//            }
//        }
//
//        if (zuulPropertiesChanged) {
//            refreshZuulProperties(changeEvent);
//        }
    }
 
Example #23
Source File: AbstractConfig.java    From apollo with Apache License 2.0 5 votes vote down vote up
private boolean isConfigChangeListenerInterested(ConfigChangeListener configChangeListener, ConfigChangeEvent configChangeEvent) {
  Set<String> interestedKeys = m_interestedKeys.get(configChangeListener);
  Set<String> interestedKeyPrefixes = m_interestedKeyPrefixes.get(configChangeListener);

  if ((interestedKeys == null || interestedKeys.isEmpty())
      && (interestedKeyPrefixes == null || interestedKeyPrefixes.isEmpty())) {
    return true; // no interested keys means interested in all keys
  }

  if (interestedKeys != null) {
    for (String interestedKey : interestedKeys) {
      if (configChangeEvent.isChanged(interestedKey)) {
        return true;
      }
    }
  }

  if (interestedKeyPrefixes != null) {
    for (String prefix : interestedKeyPrefixes) {
      for (final String changedKey : configChangeEvent.changedKeys()) {
        if (changedKey.startsWith(prefix)) {
          return true;
        }
      }
    }
  }

  return false;
}
 
Example #24
Source File: ConfigIntegrationTest.java    From apollo with Apache License 2.0 5 votes vote down vote up
@Test
public void testLongPollRefresh() throws Exception {
  final String someKey = "someKey";
  final String someValue = "someValue";
  final String anotherValue = "anotherValue";
  long someNotificationId = 1;

  long pollTimeoutInMS = 50;
  Map<String, String> configurations = Maps.newHashMap();
  configurations.put(someKey, someValue);
  ApolloConfig apolloConfig = assembleApolloConfig(configurations);
  ContextHandler configHandler = mockConfigServerHandler(HttpServletResponse.SC_OK, apolloConfig);
  ContextHandler pollHandler =
      mockPollNotificationHandler(pollTimeoutInMS, HttpServletResponse.SC_OK,
          Lists.newArrayList(
              new ApolloConfigNotification(apolloConfig.getNamespaceName(), someNotificationId)),
          false);

  startServerWithHandlers(configHandler, pollHandler);

  Config config = ConfigService.getAppConfig();
  assertEquals(someValue, config.getProperty(someKey, null));

  final SettableFuture<Boolean> longPollFinished = SettableFuture.create();

  config.addChangeListener(new ConfigChangeListener() {
    @Override
    public void onChange(ConfigChangeEvent changeEvent) {
      longPollFinished.set(true);
    }
  });

  apolloConfig.getConfigurations().put(someKey, anotherValue);

  longPollFinished.get(pollTimeoutInMS * 20, TimeUnit.MILLISECONDS);

  assertEquals(anotherValue, config.getProperty(someKey, null));
}
 
Example #25
Source File: ApolloConfigLoader.java    From tunnel with Apache License 2.0 5 votes vote down vote up
@Override
public void onChange(ConfigChangeEvent changeEvent) {
    Set<String> keys = changeEvent.changedKeys();
    for (String key : keys) {
        ConfigChange change = changeEvent.getChange(key);
        if (change == null) {
            continue;
        }

        String oldValue = change.getOldValue();
        String newValue = change.getNewValue();
        configListener.onChange(key, oldValue, newValue);
    }
}
 
Example #26
Source File: JavaConfigAnnotationTest.java    From apollo with Apache License 2.0 4 votes vote down vote up
@ApolloConfigChangeListener
private void someOnChange(ConfigChangeEvent changeEvent) {
  this.someChangeEvent = changeEvent;
}
 
Example #27
Source File: JavaConfigAnnotationTest.java    From apollo with Apache License 2.0 4 votes vote down vote up
public ConfigChangeEvent getChangeEvent2() {
  return changeEvent2;
}
 
Example #28
Source File: JavaConfigAnnotationTest.java    From apollo with Apache License 2.0 4 votes vote down vote up
@ApolloConfigChangeListener(interestedKeys = {"someKey"})
private void someOnChange(ConfigChangeEvent changeEvent) {}
 
Example #29
Source File: JavaConfigAnnotationTest.java    From apollo with Apache License 2.0 4 votes vote down vote up
public ConfigChangeEvent getSomeChangeEvent() {
  return someChangeEvent;
}
 
Example #30
Source File: XMLConfigAnnotationTest.java    From apollo with Apache License 2.0 4 votes vote down vote up
public ConfigChangeEvent getChangeEvent3() {
  return changeEvent3;
}