Java Code Examples for com.ctrip.framework.apollo.ConfigService#getConfig()

The following examples show how to use com.ctrip.framework.apollo.ConfigService#getConfig() . 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: ApolloDataSource.java    From Sentinel-Dashboard-Nacos with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs the Apollo data source
 *
 * @param namespaceName        the namespace name in Apollo, should not be null or empty
 * @param ruleKey              the rule key in the namespace, should not be null or empty
 * @param defaultRuleValue     the default rule value when the ruleKey is not found or any error
 *                             occurred
 * @param parser               the parser to transform string configuration to actual flow rules
 */
public ApolloDataSource(String namespaceName, String ruleKey, String defaultRuleValue,
                        Converter<String, T> parser) {
    super(parser);

    Preconditions.checkArgument(!Strings.isNullOrEmpty(namespaceName), "Namespace name could not be null or empty");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(ruleKey), "RuleKey could not be null or empty!");

    this.ruleKey = ruleKey;
    this.defaultRuleValue = defaultRuleValue;

    this.config = ConfigService.getConfig(namespaceName);

    initialize();

    RecordLog.info(String.format("Initialized rule for namespace: %s, rule key: %s", namespaceName, ruleKey));
}
 
Example 2
Source File: ApolloDataSource.java    From Sentinel with Apache License 2.0 6 votes vote down vote up
/**
 * Constructs the Apollo data source
 *
 * @param namespaceName        the namespace name in Apollo, should not be null or empty
 * @param ruleKey              the rule key in the namespace, should not be null or empty
 * @param defaultRuleValue     the default rule value when the ruleKey is not found or any error
 *                             occurred
 * @param parser               the parser to transform string configuration to actual flow rules
 */
public ApolloDataSource(String namespaceName, String ruleKey, String defaultRuleValue,
                        Converter<String, T> parser) {
    super(parser);

    Preconditions.checkArgument(!Strings.isNullOrEmpty(namespaceName), "Namespace name could not be null or empty");
    Preconditions.checkArgument(!Strings.isNullOrEmpty(ruleKey), "RuleKey could not be null or empty!");

    this.ruleKey = ruleKey;
    this.defaultRuleValue = defaultRuleValue;

    this.config = ConfigService.getConfig(namespaceName);

    initialize();

    RecordLog.info(String.format("Initialized rule for namespace: %s, rule key: %s", namespaceName, ruleKey));
}
 
Example 3
Source File: ApolloAnnotationProcessor.java    From apollo with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example 4
Source File: ApolloApplicationContextInitializer.java    From apollo with Apache License 2.0 6 votes vote down vote up
/**
 * Initialize Apollo Configurations Just after environment is ready.
 *
 * @param environment
 */
protected void initialize(ConfigurableEnvironment environment) {

  if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)) {
    //already initialized
    return;
  }

  String namespaces = environment.getProperty(PropertySourcesConstants.APOLLO_BOOTSTRAP_NAMESPACES, ConfigConsts.NAMESPACE_APPLICATION);
  logger.debug("Apollo bootstrap namespaces: {}", namespaces);
  List<String> namespaceList = NAMESPACE_SPLITTER.splitToList(namespaces);

  CompositePropertySource composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME);
  for (String namespace : namespaceList) {
    Config config = ConfigService.getConfig(namespace);

    composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config));
  }

  environment.getPropertySources().addFirst(composite);
}
 
Example 5
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 6
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 7
Source File: ApolloConfigWatcherRegister.java    From skywalking with Apache License 2.0 6 votes vote down vote up
public ApolloConfigWatcherRegister(ApolloConfigurationCenterSettings settings) {
    super(settings.getPeriod());

    final String namespace = settings.getNamespace();

    final boolean isDefaultNamespace = Strings.isNullOrEmpty(namespace);

    if (isDefaultNamespace) {
        this.configReader = ConfigService.getAppConfig();
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Read dynamic configs from Apollo default namespace");
        }
    } else {
        this.configReader = ConfigService.getConfig(namespace);
        if (LOGGER.isInfoEnabled()) {
            LOGGER.info("Read dynamic configs from Apollo namespace: {}", namespace);
        }
    }
}
 
Example 8
Source File: ApolloSpringApplicationRunListener.java    From summerframework with Apache License 2.0 5 votes vote down vote up
private void initInfraConfig(ConfigurableEnvironment env) {
    com.ctrip.framework.apollo.Config apolloConfig = ConfigService.getConfig(CONFIGCENTER_INFRA_NAMESPACE);
    Set<String> propertyNames = apolloConfig.getPropertyNames();
    if (propertyNames != null && propertyNames.size() > 0) {
        Properties propertes = new Properties();
        for (String propertyName : propertyNames) {
            propertes.setProperty(propertyName, apolloConfig.getProperty(propertyName, null));
        }
        EnumerablePropertySource enumerablePropertySource =
            new PropertiesPropertySource(CONFIGCENTER_INFRA_NAMESPACE, propertes);
        env.getPropertySources().addLast(enumerablePropertySource);
    }
}
 
Example 9
Source File: ApolloConfigManager.java    From jboot with Apache License 2.0 5 votes vote down vote up
private Config getDefaultConfig() {
    ApolloServerConfig apolloServerConfig = Jboot.config(ApolloServerConfig.class);
    if (StrUtil.isNotBlank(apolloServerConfig.getDefaultNamespace())) {
        return ConfigService.getConfig(apolloServerConfig.getDefaultNamespace());
    } else {
        return ConfigService.getAppConfig();
    }
}
 
Example 10
Source File: PropertySourcesProcessor.java    From apollo with Apache License 2.0 5 votes vote down vote up
private void initializePropertySources() {
  if (environment.getPropertySources().contains(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME)) {
    //already initialized
    return;
  }
  CompositePropertySource composite = new CompositePropertySource(PropertySourcesConstants.APOLLO_PROPERTY_SOURCE_NAME);

  //sort by order asc
  ImmutableSortedSet<Integer> orders = ImmutableSortedSet.copyOf(NAMESPACE_NAMES.keySet());
  Iterator<Integer> iterator = orders.iterator();

  while (iterator.hasNext()) {
    int order = iterator.next();
    for (String namespace : NAMESPACE_NAMES.get(order)) {
      Config config = ConfigService.getConfig(namespace);

      composite.addPropertySource(configPropertySourceFactory.getConfigPropertySource(namespace, config));
    }
  }

  // clean up
  NAMESPACE_NAMES.clear();

  // add after the bootstrap property source or to the first
  if (environment.getPropertySources()
      .contains(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME)) {

    // ensure ApolloBootstrapPropertySources is still the first
    ensureBootstrapPropertyPrecedence(environment);

    environment.getPropertySources()
        .addAfter(PropertySourcesConstants.APOLLO_BOOTSTRAP_PROPERTY_SOURCE_NAME, composite);
  } else {
    environment.getPropertySources().addFirst(composite);
  }
}
 
Example 11
Source File: ApolloConfigWrapper.java    From shardingsphere with Apache License 2.0 5 votes vote down vote up
public ApolloConfigWrapper(final CenterConfiguration config, final ApolloProperties props) {
    String appId = props.getValue(ApolloPropertyKey.APP_ID);
    String env = props.getValue(ApolloPropertyKey.ENV);
    String clusterName = props.getValue(ApolloPropertyKey.CLUSTER_NAME);
    System.setProperty(APOLLO_KEY_APP_ID, appId);
    System.setProperty(APOLLO_KEY_ENV, env);
    System.setProperty(ConfigConsts.APOLLO_CLUSTER_KEY, clusterName);
    System.setProperty(ConfigConsts.APOLLO_META_KEY, config.getServerLists());
    String namespace = config.getNamespace();
    apolloConfig = ConfigService.getConfig(namespace);
}
 
Example 12
Source File: ConfigIntegrationTest.java    From apollo with Apache License 2.0 4 votes vote down vote up
@Test
public void testLongPollRefreshWithMultipleNamespacesAndOnlyOneNamespaceNotified()
    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 someOtherConfig = ConfigService.getConfig(someOtherNamespace);
  Config config = ConfigService.getAppConfig();
  assertEquals(someValue, config.getProperty(someKey, null));
  assertEquals(someValue, someOtherConfig.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(5000, TimeUnit.MILLISECONDS);

  assertEquals(anotherValue, config.getProperty(someKey, null));

  TimeUnit.MILLISECONDS.sleep(pollTimeoutInMS * 10);
  assertEquals(someValue, someOtherConfig.getProperty(someKey, null));
}