Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: load config in parallel way #312

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
package org.springframework.cloud.zookeeper.config;

import java.io.Closeable;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
Expand Down Expand Up @@ -124,7 +124,7 @@ public String getEventDesc(TreeCacheEvent event) {
out.append(", path=").append(event.getData().getPath());
byte[] data = event.getData().getData();
if (data != null && data.length > 0) {
out.append(", data=").append(new String(data, Charset.forName("UTF-8")));
out.append(", data=").append(new String(data, StandardCharsets.UTF_8));
}
return out.toString();
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -42,12 +42,13 @@ public ZookeeperConfigDataLoader(DeferredLogFactory logFactory) {
public ConfigData load(ConfigDataLoaderContext context, ZookeeperConfigDataResource resource) {
try {
CuratorFramework curator = context.getBootstrapContext().get(CuratorFramework.class);
if (curator == null) {
ZookeeperConfigProperties properties = context.getBootstrapContext().get(ZookeeperConfigProperties.class);
if (curator == null || properties == null) {
// this can happen if certain conditions are met
return null;
}
ZookeeperPropertySource propertySource = new ZookeeperPropertySource(resource.getContext(),
curator);
ZookeeperPropertySource propertySource = new ZookeeperPropertySource(resource.getContext(), curator,
properties);
List<ZookeeperPropertySource> propertySources = Collections.singletonList(propertySource);

return new ConfigData(propertySources, source -> {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ public List<ZookeeperConfigDataResource> resolveProfileSpecific(ConfigDataLocati

// create locations
ZookeeperConfigProperties properties = loadConfigProperties(context);
context.getBootstrapContext().register(ZookeeperConfigProperties.class, InstanceSupplier.of(properties));
context.getBootstrapContext().registerIfAbsent(ZookeeperConfigProperties.class, InstanceSupplier.of(properties));

ZookeeperPropertySources sources = new ZookeeperPropertySources(properties, log);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,11 @@ public class ZookeeperConfigProperties {
*/
private boolean failFast = true;

/**
* get config in parallel way.
*/
private boolean parallel = false;

public boolean isEnabled() {
return this.enabled;
}
Expand Down Expand Up @@ -112,6 +117,14 @@ public void setFailFast(boolean failFast) {
this.failFast = failFast;
}

public boolean isParallel() {
return parallel;
}

public void setParallel(boolean parallel) {
this.parallel = parallel;
}

@Override
public String toString() {
return new ToStringCreator(this)
Expand All @@ -121,6 +134,7 @@ public String toString() {
.append("defaultContext", defaultContext)
.append("profileSeparator", profileSeparator)
.append("failFast", failFast)
.append("parallel", parallel)
.toString();

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,12 @@

package org.springframework.cloud.zookeeper.config;

import java.nio.charset.Charset;
import java.util.LinkedHashMap;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Stream;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
Expand All @@ -40,10 +41,14 @@ public class ZookeeperPropertySource extends AbstractZookeeperPropertySource {

private static final Log log = LogFactory.getLog(ZookeeperPropertySource.class);

private Map<String, String> properties = new LinkedHashMap<>();
private final ZookeeperConfigProperties zookeeperConfigProperties;

public ZookeeperPropertySource(String context, CuratorFramework source) {
private Map<String, String> properties = new ConcurrentHashMap<>(256);

public ZookeeperPropertySource(String context, CuratorFramework source,
ZookeeperConfigProperties zookeeperConfigProperties) {
super(context, source);
this.zookeeperConfigProperties = zookeeperConfigProperties;
findProperties(this.getContext(), null);
}

Expand Down Expand Up @@ -86,9 +91,20 @@ private void findProperties(String path, List<String> children) {
if (children == null || children.isEmpty()) {
return;
}
for (String child : children) {

Stream<String> childrenStream = children.stream();
if (zookeeperConfigProperties.isParallel() && this.getContext().equals(path)) {
childrenStream = children.parallelStream();
}
childrenStream.forEach(child -> {
String childPath = path + "/" + child;
List<String> childPathChildren = getChildren(childPath);
List<String> childPathChildren = null;
try {
childPathChildren = getChildren(childPath);
}
catch (Exception e) {
ReflectionUtils.rethrowRuntimeException(e);
}

byte[] bytes = getPropertyBytes(childPath);
if (bytes == null || bytes.length == 0) {
Expand All @@ -97,13 +113,13 @@ private void findProperties(String path, List<String> children) {
}
}
else {
registerKeyValue(childPath,
new String(bytes, Charset.forName("UTF-8")));
registerKeyValue(childPath, new String(bytes, StandardCharsets.UTF_8));
}

// Check children even if we have found a value for the current znode
findProperties(childPath, childPathChildren);
}
});

log.trace("leaving findProperties for path: " + path);
}
catch (Exception exception) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -107,16 +107,4 @@ public PropertySource<?> locate(Environment environment) {
@PreDestroy
public void destroy() {
}

private PropertySource<CuratorFramework> create(String context) {
return new ZookeeperPropertySource(context, this.curator);
}

private void addProfiles(List<String> contexts, String baseContext,
List<String> profiles) {
for (String profile : profiles) {
contexts.add(baseContext + this.properties.getProfileSeparator() + profile);
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ private void addProfiles(List<Context> contexts, String baseContext, List<String

public ZookeeperPropertySource createPropertySource(String context, boolean optional, CuratorFramework curator) {
try {
return new ZookeeperPropertySource(context, curator);
return new ZookeeperPropertySource(context, curator, this.properties);
// TODO: howto call close when /refresh
}
catch (Exception e) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
/*
* Copyright 2015-2019 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

package org.springframework.cloud.zookeeper.config;

import java.lang.reflect.Field;
import java.util.Map;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.RetryOneTime;
import org.junit.Before;
import org.junit.Test;

import org.springframework.cloud.zookeeper.test.ZookeeperTestingServer;
import org.springframework.util.ReflectionUtils;

import static org.assertj.core.api.Assertions.assertThat;

/**
* {@link org.springframework.core.env.PropertySource} that stores properties
* from Zookeeper inside a map. Properties are loaded upon class initialization.
*
* @author lemonJ
* @since 1.0.0
*/
public class ZookeeperPropertySourceTests {

private static final Log log = LogFactory.getLog(ZookeeperPropertySourceTests.class);

public static final String PREFIX = "test__config__";

public static final String ROOT = "/" + PREFIX + UUID.randomUUID();

private ZookeeperTestingServer testingServer;

private CuratorFramework curator;

@Before
public void setup() throws Exception {
this.testingServer = new ZookeeperTestingServer();
testingServer.start();
String connectString = "localhost:" + testingServer.getPort();
this.curator = CuratorFrameworkFactory.builder().retryPolicy(new RetryOneTime(500)).connectString(connectString)
.build();
this.curator.start();
}

@Test
public void loadConfigInParallel() throws Exception {
for (int i = 0; i < 1000; i++) {
String path = ROOT + "/" + i;
this.curator.create().creatingParentsIfNeeded().forPath(path);
this.curator.setData().forPath(path, "testPropValUpdate".getBytes());
}

ZookeeperConfigProperties properties = new ZookeeperConfigProperties();
properties.setParallel(true);
ZookeeperPropertySource parallelPropertySource = new ZookeeperPropertySource(ROOT, curator, properties);

properties.setParallel(false);
ZookeeperPropertySource serialPropertySource = new ZookeeperPropertySource(ROOT, curator, properties);

Field propertiesField = ZookeeperPropertySource.class.getDeclaredField("properties");
propertiesField.setAccessible(true);
Map<String, String> serialPropertyMap = (Map<String, String>) ReflectionUtils.getField(propertiesField,
serialPropertySource);
Map<String, String> parallelPropertyMap = (Map<String, String>) ReflectionUtils.getField(propertiesField,
parallelPropertySource);
assertThat(parallelPropertyMap).as("parallelPropertyMap").containsAllEntriesOf(serialPropertyMap);
}
}