org.springframework.cloud.context.environment.EnvironmentChangeEvent Java Examples

The following examples show how to use org.springframework.cloud.context.environment.EnvironmentChangeEvent. 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: RateLimiterManager.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Order
@EventListener
public void rateLimiterConfigRefresh(EnvironmentChangeEvent changeEvent) {
    Set<String> refreshKey = changeEvent.getKeys();
    logger.debug("Received configuration update with keys: {}", refreshKey);
    logger.debug("Updated rateLimiterProperties are :{}", rateLimiterProperties);
    if (refreshKey != null && refreshKey.size() > 0
            && refreshKey.toString().contains("formula.ratelimiter")) {
        Set<FormulaRateLimiterConfig> cachedRateLimiterConfigs = new HashSet<>(ratelimiterConfigs.values());
        List<FormulaRateLimiterConfig> newRateLimiterConfigs = rateLimiterProperties.getRatelimiters();
        Set<String> names = getNamesWithUpdates(cachedRateLimiterConfigs, newRateLimiterConfigs);
        updateRateLimiterConfigMap();
        updatePatternsRequestMap();
        if (null != names && names.size() > 0) {
            for (String name : names) {
                logger.debug("RateLimiter to be refresh with name: {}", name);
                refreshRateLimiter(name, 1);
            }
        }
    }
}
 
Example #2
Source File: RateLimiterManagerTest.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Test
public void testRateLimiterRuleUpdate() {

    List<FormulaRateLimiterConfig> configList = rateLimiterProperties.getRatelimiters();
    logger.info("Configure list: {}", configList);
    String key = configList.get(0).getLimiterName();
    Integer originalThreshHold = registryManager.getRatelimiterConfigs().get(key).getThreshold();
    Integer newThreshHold = originalThreshHold + 1;
    configList.get(0).setThreshold(newThreshHold);
    rateLimiterProperties.setRatelimiters(configList);
    // assert not equal before refresh
    assertNotEquals(newThreshHold, registryManager.getRatelimiterConfigs().get(key).getThreshold());

    // manually trigger change event
    Set<String> changedKeys = new HashSet<>();
    changedKeys.add("formula.ratelimiter.ratelimiters[0].threshold");
    EnvironmentChangeEvent changeEvent = new EnvironmentChangeEvent(changedKeys);
    registryManager.rateLimiterConfigRefresh(changeEvent);
    assertEquals(newThreshHold, registryManager.getRatelimiterConfigs().get(key).getThreshold());

    // change back
    configList.get(0).setThreshold(originalThreshHold);
    rateLimiterProperties.setRatelimiters(configList);
    registryManager.rateLimiterConfigRefresh(changeEvent);
    assertEquals(originalThreshHold, registryManager.getRatelimiterConfigs().get(key).getThreshold());
}
 
Example #3
Source File: RateLimiterManagerTest.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Test
public void testRateLimiterRuleDisable() {

    List<FormulaRateLimiterConfig> configList = rateLimiterProperties.getRatelimiters();
    logger.info("Configure list: {}", configList);
    String key = configList.get(1).getLimiterName();
    configList.get(1).setEnabled(false);
    rateLimiterProperties.setRatelimiters(configList);
    // assert not equal before refresh
    assertNotEquals(false, registryManager.getRatelimiterConfigs().get(key).getEnabled());

    // manually trigger change event
    Set<String> changedKeys = new HashSet<>();
    changedKeys.add("formula.ratelimiter.ratelimiters[1].enabled");
    EnvironmentChangeEvent changeEvent = new EnvironmentChangeEvent(changedKeys);
    registryManager.rateLimiterConfigRefresh(changeEvent);
    assertEquals(false, registryManager.getRatelimiterConfigs().get(key).getEnabled());

    // change back
    configList.get(1).setEnabled(true);
    rateLimiterProperties.setRatelimiters(configList);
    registryManager.rateLimiterConfigRefresh(changeEvent);
    assertEquals(true, registryManager.getRatelimiterConfigs().get(key).getEnabled());
}
 
Example #4
Source File: RateLimiterManagerTest.java    From spring-cloud-formula with Apache License 2.0 6 votes vote down vote up
@Test
public void testRateLimiterRuleDelete() {

    List<FormulaRateLimiterConfig> configList = rateLimiterProperties.getRatelimiters();
    logger.info("Configure list: {}", configList);
    FormulaRateLimiterConfig configuration = configList.get(1);
    configList.remove(1);
    assertEquals(2, registryManager.getRatelimiterConfigs().size());

    // manually trigger change event
    Set<String> changedKeys = new HashSet<>();
    changedKeys.add("formula.ratelimiter.ratelimiters[1]");
    EnvironmentChangeEvent changeEvent = new EnvironmentChangeEvent(changedKeys);
    registryManager.rateLimiterConfigRefresh(changeEvent);
    assertEquals(1, registryManager.getRatelimiterConfigs().size());

    // change back
    configList.add(configuration);
    registryManager.rateLimiterConfigRefresh(changeEvent);
    assertEquals(2, registryManager.getRatelimiterConfigs().size());
}
 
Example #5
Source File: RefreshablePeerEurekaNodesTests.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
@Test
public void updatedWhenAvailabilityZoneChanged() {
	changeProperty("eureka.client.use-dns-for-fetching-service-urls=false",
			"eureka.client.region=region4",
			"eureka.client.availability-zones.region3=region3-zone",
			"eureka.client.service-url.region4-zone=https://region4-zone-host:8678/eureka/",
			"eureka.client.service-url.defaultZone=https://default-host3:8678/eureka/");
	this.context.publishEvent(new EnvironmentChangeEvent(
			Collections.singleton("eureka.client.availability-zones.region3")));
	assertThat(this.peerEurekaNodes.getPeerEurekaNodes().get(0).getServiceUrl()
			.equals("https://default-host3:8678/eureka/")).isTrue();

	changeProperty("eureka.client.availability-zones.region4=region4-zone");
	this.context.publishEvent(new EnvironmentChangeEvent(
			Collections.singleton("eureka.client.availability-zones.region4")));
	assertThat(serviceUrlMatches("https://region4-zone-host:8678/eureka/")).as(
			"PeerEurekaNodes' are not updated when eureka.client.availability-zones are changed")
			.isTrue();
}
 
Example #6
Source File: RefreshablePeerEurekaNodesTests.java    From spring-cloud-netflix with Apache License 2.0 6 votes vote down vote up
@Test
public void updatedWhenRegionChanged() {
	changeProperty("eureka.client.use-dns-for-fetching-service-urls=false",
			"eureka.client.region=region1",
			"eureka.client.availability-zones.region1=region1-zone",
			"eureka.client.availability-zones.region2=region2-zone",
			"eureka.client.service-url.region1-zone=https://region1-zone-host:8678/eureka/",
			"eureka.client.service-url.region2-zone=https://region2-zone-host:8678/eureka/");
	this.context
			.publishEvent(new EnvironmentChangeEvent(Collections.singleton(REGION)));
	assertThat(serviceUrlMatches("https://region1-zone-host:8678/eureka/")).as(
			"PeerEurekaNodes' are not updated when eureka.client.region is changed")
			.isTrue();

	changeProperty("eureka.client.region=region2");
	this.context
			.publishEvent(new EnvironmentChangeEvent(Collections.singleton(REGION)));
	assertThat(serviceUrlMatches("https://region2-zone-host:8678/eureka/")).as(
			"PeerEurekaNodes' are not updated when eureka.client.region is changed")
			.isTrue();
}
 
Example #7
Source File: DataSourceRefresher.java    From apollo-use-cases with Apache License 2.0 6 votes vote down vote up
private synchronized void refreshDataSource(Set<String> changedKeys) {
  try {
    logger.info("Refreshing data source");

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

    DataSource newDataSource = dataSourceManager.createAndTestDataSource();
    DataSource oldDataSource = dynamicDataSource.setDataSource(newDataSource);
    asyncTerminate(oldDataSource);

    logger.info("Finished refreshing data source");
  } catch (Throwable ex) {
    logger.error("Refreshing data source failed", ex);
  }
}
 
Example #8
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 #9
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 #10
Source File: RefreshablePeerEurekaNodesTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Test
public void updatedWhenDnsIsFalse() {
	changeProperty("eureka.client.use-dns-for-fetching-service-urls=false",
			"eureka.client.region=unavailable-region", // to force defaultZone
			"eureka.client.service-url.defaultZone=https://default-host2:8678/eureka/");
	this.context.publishEvent(new EnvironmentChangeEvent(
			new HashSet<>(Arrays.asList(USE_DNS, DEFAULT_ZONE))));

	assertThat(serviceUrlMatches("https://default-host2:8678/eureka/")).as(
			"PeerEurekaNodes' are not updated when eureka.client.use-dns-for-fetching-service-urls is false")
			.isTrue();
}
 
Example #11
Source File: PropertySourceBootstrapConfiguration.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
private void setLogLevels(ConfigurableApplicationContext applicationContext,
		ConfigurableEnvironment environment) {
	LoggingRebinder rebinder = new LoggingRebinder();
	rebinder.setEnvironment(environment);
	// We can't fire the event in the ApplicationContext here (too early), but we can
	// create our own listener and poke it (it doesn't need the key changes)
	rebinder.onApplicationEvent(new EnvironmentChangeEvent(applicationContext,
			Collections.<String>emptySet()));
}
 
Example #12
Source File: LoggingRebinderTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void logLevelsChanged() {
	then(this.logger.isTraceEnabled()).isFalse();
	StandardEnvironment environment = new StandardEnvironment();
	TestPropertyValues.of("logging.level.org.springframework.web=TRACE")
			.applyTo(environment);
	this.rebinder.setEnvironment(environment);
	this.rebinder.onApplicationEvent(new EnvironmentChangeEvent(environment,
			Collections.singleton("logging.level.org.springframework.web")));
	then(this.logger.isTraceEnabled()).isTrue();
}
 
Example #13
Source File: LoggingRebinderTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void logLevelsLowerCase() {
	then(this.logger.isTraceEnabled()).isFalse();
	StandardEnvironment environment = new StandardEnvironment();
	TestPropertyValues.of("logging.level.org.springframework.web=trace")
			.applyTo(environment);
	this.rebinder.setEnvironment(environment);
	this.rebinder.onApplicationEvent(new EnvironmentChangeEvent(environment,
			Collections.singleton("logging.level.org.springframework.web")));
	then(this.logger.isTraceEnabled()).isTrue();
}
 
Example #14
Source File: LoggingRebinderTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void logLevelFalseResolvedToOff() {
	ch.qos.logback.classic.Logger logger = (ch.qos.logback.classic.Logger) LoggerFactory
			.getLogger("org.springframework.cloud");
	StandardEnvironment environment = new StandardEnvironment();
	TestPropertyValues.of("logging.level.org.springframework.cloud=false")
			.applyTo(environment);
	rebinder.setEnvironment(environment);
	rebinder.onApplicationEvent(new EnvironmentChangeEvent(environment,
			Collections.singleton("logging.level.org.springframework.cloud")));
	then(Level.OFF).isEqualTo((logger.getLevel()));
}
 
Example #15
Source File: RefreshEndpointTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Test
public void eventsPublishedInOrder() throws Exception {
	this.context = new SpringApplicationBuilder(Empty.class)
			.web(WebApplicationType.NONE).bannerMode(Mode.OFF).run();
	RefreshScope scope = new RefreshScope();
	scope.setApplicationContext(this.context);
	ContextRefresher contextRefresher = new ContextRefresher(this.context, scope);
	RefreshEndpoint endpoint = new RefreshEndpoint(contextRefresher);
	Empty empty = this.context.getBean(Empty.class);
	endpoint.refresh();
	int after = empty.events.size();
	then(2).isEqualTo(after).as("Shutdown hooks not cleaned on refresh");
	then(empty.events.get(0) instanceof EnvironmentChangeEvent).isTrue();
}
 
Example #16
Source File: RefreshEndpointTests.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(ApplicationEvent event) {
	if (event instanceof EnvironmentChangeEvent
			|| event instanceof RefreshScopeRefreshedEvent) {
		this.events.add(event);
	}
}
 
Example #17
Source File: RefreshablePeerEurekaNodesTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Test
public void notUpdatedWhenDnsIsTrue() {
	changeProperty("eureka.client.use-dns-for-fetching-service-urls=true",
			"eureka.client.region=unavailable-region", // to force defaultZone
			"eureka.client.service-url.defaultZone=https://default-host1:8678/eureka/");
	this.context.publishEvent(new EnvironmentChangeEvent(
			new HashSet<>(Arrays.asList(USE_DNS, DEFAULT_ZONE))));

	assertThat(serviceUrlMatches("https://default-host1:8678/eureka/")).as(
			"PeerEurekaNodes' are updated when eureka.client.use-dns-for-fetching-service-urls is true")
			.isFalse();
}
 
Example #18
Source File: LoggingRebinder.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(EnvironmentChangeEvent event) {
	if (this.environment == null) {
		return;
	}
	LoggingSystem system = LoggingSystem.get(LoggingSystem.class.getClassLoader());
	setLogLevels(system, this.environment);
}
 
Example #19
Source File: RefreshablePeerEurekaNodesTests.java    From spring-cloud-netflix with Apache License 2.0 5 votes vote down vote up
@Test
public void notUpdatedForRelaxedKeys() {
	changeProperty("eureka.client.use-dns-for-fetching-service-urls=false",
			"eureka.client.region=unavailable-region", // to force defaultZone
			"eureka.client.service-url.defaultZone=https://defaul-host6:8678/eureka/");
	this.context.publishEvent(new EnvironmentChangeEvent(
			Collections.singleton("eureka.client.serviceUrl.defaultZone")));
	assertThat(serviceUrlMatches("https://defaul-host6:8678/eureka/"))
			.as("PeerEurekaNodes' are updated for keys with relaxed binding")
			.isFalse();
}
 
Example #20
Source File: ConsulPropertySourceLocatorTests.java    From spring-cloud-consul with Apache License 2.0 5 votes vote down vote up
@EventListener
public void handle(EnvironmentChangeEvent event) {
	if (event.getKeys().contains(TEST_PROP)) {
		countDownLatch1().countDown();
	}
	else if (event.getKeys().contains(TEST_PROP3)) {
		countDownLatch2().countDown();
	}
}
 
Example #21
Source File: ArchaiusBasicConfigurationIntegrationTest.java    From tutorials with MIT License 5 votes vote down vote up
@Test
public void givenIntialPropertyValue_whenPropertyChanges_thenArchaiusRetrievesNewValue() {
    String initialValue = testPropertyWithDynamic.get();

    TestPropertyValues.of("baeldung.archaius.test.properties.one=new-value")
        .applyTo(context);
    context.publishEvent(new EnvironmentChangeEvent(Collections.singleton("baeldung.archaius.test.properties.one")));
    String finalValue = testPropertyWithDynamic.get();

    assertThat(initialValue).isEqualTo("test-one");
    assertThat(finalValue).isEqualTo("new-value");
}
 
Example #22
Source File: ConfigurationPropertiesRebinder.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(EnvironmentChangeEvent event) {
	if (this.applicationContext.equals(event.getSource())
			// Backwards compatible
			|| event.getKeys().equals(event.getSource())) {
		rebind();
	}
}
 
Example #23
Source File: ContextRefresher.java    From spring-cloud-commons with Apache License 2.0 5 votes vote down vote up
public synchronized Set<String> refreshEnvironment() {
	Map<String, Object> before = extract(
			this.context.getEnvironment().getPropertySources());
	addConfigFilesToEnvironment();
	Set<String> keys = changes(before,
			extract(this.context.getEnvironment().getPropertySources())).keySet();
	this.context.publishEvent(new EnvironmentChangeEvent(this.context, keys));
	return keys;
}
 
Example #24
Source File: ZookeeperPropertySourceLocatorTests.java    From spring-cloud-zookeeper with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(EnvironmentChangeEvent event) {
	log.debug("Event keys: " + event.getKeys());
	if (event.getKeys().contains(KEY_BASIC)) {
		countDownLatch().countDown();
	}
}
 
Example #25
Source File: RefreshEurekaServersListener.java    From onetwo with Apache License 2.0 5 votes vote down vote up
@Override
public void onApplicationEvent(EnvironmentChangeEvent event) {
	loadBalancers.stream().forEach(lb -> {
		if (lb instanceof DynamicServerListLoadBalancer) {
			((DynamicServerListLoadBalancer<?>)lb).updateListOfServers();
		}
	});
}
 
Example #26
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 #27
Source File: LoggerLevelRefresher.java    From apollo-use-cases with Apache License 2.0 5 votes vote down vote up
private void refreshLoggingLevels(Set<String> changedKeys) {
  System.out.println("Refreshing logging levels");

  /**
   * refresh logging levels
   * @see org.springframework.cloud.logging.LoggingRebinder#onApplicationEvent
   */
  this.applicationContext.publishEvent(new EnvironmentChangeEvent(changedKeys));

  System.out.println("Logging levels refreshed");
}
 
Example #28
Source File: ScmContextRefresher.java    From super-cloudops with Apache License 2.0 5 votes vote down vote up
@Override
public synchronized Set<String> refresh() {
	Map<String, Object> before = extract(context.getEnvironment().getPropertySources());
	addScmConfigToEnvironment();
	Set<String> keys = changes(before, extract(context.getEnvironment().getPropertySources())).keySet();
	context.publishEvent(new EnvironmentChangeEvent(context, keys));
	scope.refreshAll();
	return keys;
}
 
Example #29
Source File: RouteListener.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
/**
 * 监听EnvironmentChangeEvent 事件,更改相关环境变量
 * @param event
 */
@Override
@EventListener(EnvironmentChangeEvent.class)
public void onApplicationEvent(EnvironmentChangeEvent event) {
    try {
        LOGGER.info("environment change.");
        Map<String, Object> propertySource = Maps.newHashMap();
        if (!routeMatcher.match()) {
            LOGGER.info("this route rules does not match this instance.");
            return;
        }
        // 多条路由规则已先后顺序进行匹配
        FormulaRouteProperty formulaRouteProperty = routeMatcher.getMatchedFormulaRouteProperty();
        // 获取新的负载均衡策略
        String iRuleName = formulaRouteProperty.getLoadbalance();
        String destServiceName = formulaRouteProperty.getDestServiceName();
        IRule oldRule = springClientFactory.getInstance(destServiceName, IRule.class);
        if (oldRule instanceof WeightedResponseTimeRule) {
            // 关闭线程池
            ((WeightedResponseTimeRule) oldRule).shutdown();
        }
        // 清理ribbon 中 所有的client的负载均衡器配置,更改环境变量值,等待下次重新加载client的负载均衡配置
        springClientFactory.destroy();

        // 按照ribbon的规范,配置IRule
        String configClientRule = destServiceName + "." + CONFIG_NAMESPACE + "." + CONFIG_RULE_CLASS;

        propertySource.put(configClientRule, IRuleInfo.getRulePath(iRuleName));
        // 加入至环境变量中
        this.configurableEnvironment.getPropertySources().addFirst(new RoutePropertySource(ROUTE_PROPERTY_SOURCE,
                propertySource));
    } catch (Exception e) {
        LOGGER.error("refresh route rule exception: {}", e);
    }

}
 
Example #30
Source File: ConsulPropertySourceLocatorTests.java    From spring-cloud-formula with Apache License 2.0 5 votes vote down vote up
@EventListener
public void handle(EnvironmentChangeEvent event) {
    if (event.getKeys().contains(TEST_PROP)) {
        countDownLatch1().countDown();
    } else if (event.getKeys().contains(TEST_PROP2)) {
        countDownLatch2().countDown();
    }
}