Skip to main content

dawdler-discovery-center-core

Module Introduction​

Registry core module, providing the DiscoveryCenter interface and the DiscoveryCenterFactory factory. To extend with another registry, depend on this module and implement DiscoveryCenter; after SPI registration the factory discovers and manages instances uniformly, and the plug of each side (server/client/gateway) obtains the registry through the factory to perform service registration and service discovery.

1. Adding the dependency in pom​

<groupId>club.dawdler</groupId>
<artifactId>dawdler-discovery-center-core</artifactId>

2. The DiscoveryCenter interface​

public interface DiscoveryCenter {

final String ROOT_PATH = "/dawdler";

/**
* Registry type identifier, used as the DiscoveryCenterFactory key, e.g. zookeeper / consul.
* The implementation must provide a public no-arg constructor and be registered as an SPI
* via META-INF/services. Configuration reading and connection setup go in init() (not in
* the constructor), and the factory calls init() on first acquisition.
*/
String type();

/**
* Whether the instance has been destroyed; the factory rebuilds the instance on the next acquisition.
*/
default boolean isDestroyed() {
return false;
}

/**
* Initialization method
*/
void init() throws Exception;

/**
* Destroy method
*/
void destroy() throws Exception;

/**
* Get the service list
*/
List<String> getServiceList(String path) throws Exception;

/**
* Add a service provider
*/
boolean addProvider(String path, String value, Map<String, Object> attributes) throws Exception;

/**
* Update a service provider
*/
default boolean updateProvider(String path, String value, Map<String, Object> attributes) throws Exception {
return true;
}

/**
* Delete a service provider
*/
default boolean deleteProvider(String path, String value) throws Exception {
return true;
}

/**
* Whether the entry exists
*/
boolean isExist(String path, String value) throws Exception;

}

3. Implementation conventions​

An implementation must follow the conventions below to be managed correctly by DiscoveryCenterFactory:

  1. Provide a public no-arg constructor (required for SPI instantiation), and do not read configuration or perform network actions in the constructor;
  2. Put configuration reading and connection setup in init(). The factory calls init() on first acquisition; missing configuration or an unreachable registry is thrown explicitly during startup instead of surfacing later at some call site during runtime;
  3. destroy() must be idempotent (e.g. guard with an AtomicBoolean) and isDestroyed() must be overridden to return that flag. After an instance is destroyed, the next acquisition by the factory rebuilds a new instance and calls init() again;
  4. type() returns a globally unique type identifier; an implementation registered with a duplicate type is ignored and an error log is printed.

4. SPI registration​

As with the other SPIs in this repository, two registration mechanisms are supported, and registering with both is recommended:

4.1 META-INF/services​

Create a file named club.dawdler.core.discoverycenter.DiscoveryCenter under the implementation module's src/main/resources/META-INF/services/, containing the fully qualified name of the implementation class. Taking the Consul implementation as an example:

club.dawdler.core.discovery.consul.ConsulDiscoveryCenter

4.2 module-info.java​

provides club.dawdler.core.discoverycenter.DiscoveryCenter
with club.dawdler.core.discovery.consul.ConsulDiscoveryCenter;

Existing implementations:

typeModule
zookeeperdawdler-discovery-center-zookeeper-core
consuldawdler-discovery-center-consul-core

5. DiscoveryCenterFactory​

// Obtain explicitly by type
DiscoveryCenter center = DiscoveryCenterFactory.getDiscoveryCenter("zookeeper");

// Automatic selection: returns directly when there is only one implementation on the classpath, no configuration needed
DiscoveryCenter center = DiscoveryCenterFactory.getDiscoveryCenter();

Instance management semantics of the factory:

  • init() is called on first acquisition and only once; repeated acquisitions return the same instance;
  • An exception from a failed init() is rethrown directly (an explicit failure during startup), and the next acquisition retries with a new instance;
  • After an instance is destroy()ed, the next acquisition rebuilds a new instance and calls init() again.

When several implementations are on the same classpath, automatic selection is not possible and the type must be specified explicitly, in one of two ways:

System property:

-Ddawdler.discovery.center.type=zookeeper

Or discovery-center.properties on the classpath:

type=zookeeper

discovery-center.properties also supports the unified configuration center, with the path /discovery-center, see Unified configuration center module

6. Extending with a new registry​

Taking Consul as an example, the complete source is in dawdler-discovery-center-consul. Each implementation is an independent module group split by responsibility into -core, -server-plug, -client-plug and (optionally) -gateway-plug modules, decoupling the core implementation from the per-side plugs so they can be depended on as needed.

6.1 Directory structure​

Following consul/zookeeper, create a module group as below (trim as needed; omit -gateway-plug if there is no gateway requirement):

dawdler-discovery-center-{type}/
├── dawdler-discovery-center-{type}-core/ # Core implementation, implements the DiscoveryCenter interface
├── dawdler-server-plug-discovery-center-{type}/ # Server-side registration lifecycle
├── dawdler-client-plug-discovery-center-{type}/ # Client-side instance change subscription
└── dawdler-gateway-discovery-center-{type}/ # (Optional) gateway side
  • -core: the only required module; depends on dawdler-discovery-center-core and implements DiscoveryCenter per section 3;
  • -server-plug: depends on -core and dawdler-discovery-center-server-plug, providing a thin LifeCycle that hooks into server-side registration;
  • -client-plug / -gateway-plug: depend on -core and provide instance change subscriptions driven by registry-specific capabilities (e.g. ZooKeeper's CuratorCache, Consul's blocking query).

6.2 Implementing DiscoveryCenter (the -core module)​

Implement the interface per section 3. The core skeleton:

public class ConsulDiscoveryCenter implements DiscoveryCenter {

public static final String TYPE = "consul";

private final AtomicBoolean destroyed = new AtomicBoolean();
private ConsulClient client;
private CloseableHttpClient httpClient;
private TLSConfig tlsConfig;

public ConsulDiscoveryCenter() { }

@Override
public String type() { return TYPE; }

@Override
public boolean isDestroyed() { return destroyed.get(); }

@Override
public void init() throws Exception {
Properties ps = PropertiesUtil.loadPropertiesIfNotExistLoadConfigCenter("consul");
String host = ps.getProperty("host");
int port = PropertiesUtil.getIfNullReturnDefaultValueInt("port", 8500, ps);
// Reading of healthCheckType/checkTime/token/TLS and tlsConfig construction omitted
httpClient = createHttpClient(tlsConfig);
client = new ConsulClient(new ConsulRawClient(host, port, httpClient));
}

@Override
public void destroy() {
if (destroyed.compareAndSet(false, true)) {
// Clear the service list cache and close httpClient
}
}

// getServiceList/addProvider/deleteProvider/isExist omitted; implemented on ConsulClient's health/agent/catalog APIs

}

Key points:

  • The TYPE constant serves both as the type() return value and as the factory key, and must match the type key in discovery-center.properties;
  • Inside init(), read configuration via PropertiesUtil.loadPropertiesIfNotExistLoadConfigCenter(type) (falling back to discovery-center.properties when absent); connection setup / missing configuration errors are thrown explicitly during startup;
  • If getServiceList falls back to a local cache (as ZooKeeper does), it may return a cached snapshot instead of throwing on failure;
  • destroy() uses AtomicBoolean.compareAndSet for idempotency and that result is returned by isDestroyed().

6.3 Registering the SPI​

See SPI registration; once the implementation is registered as an SPI it is managed uniformly by the factory:

  • Write the fully qualified implementation class name into META-INF/services/club.dawdler.core.discoverycenter.DiscoveryCenter;
  • Declare it in module-info.java with provides ... with ... (registering both is recommended).

6.4 Server-side registration (the -server-plug module)​

Server-side service registration, heartbeat re-registration and deregistration are driven automatically through the factory by AbstractServerDiscoveryCenterLifeCycle of dawdler-discovery-center-server-plug. A new implementation only needs to provide a thin subclass of AbstractServerDiscoveryCenterLifeCycle:

  • Override afterInit(), fill in the attributes needed by addProvider(attributes) and then call it (health-check related attributes are added as needed);
  • getDiscoveryCenter() is selected automatically through the factory by default and needs no override; override it as DiscoveryCenterFactory.getDiscoveryCenter(TYPE) to bind this implementation;
  • Service address / heartbeat re-registration / deregistration logic is handled uniformly by the abstract class, so subclasses do not reimplement it.

See ConsulLifeCycle in dawdler-server-plug-discovery-center-consul for an example.

6.5 Client and gateway instance subscription (the -client-plug / -gateway-plug modules)​

Since v0.1.7 instance subscription is event-driven: each implementation provides a shared subscriber (ZkServiceSubscriber for ZooKeeper, ConsulServiceSubscriber for Consul) that writes the full instance list into the single JVM-wide ServiceInstanceCache.

  • In prepareInit(), obtain the registry with DiscoveryCenterFactory.getDiscoveryCenter(type) and call discoveryCenter.subscribe(serviceName) for each consumed service;
  • ConnectionPool is already wired to listen on ServiceInstanceCache when addServerChannelGroup is called, so instance changes automatically drive a full-diff refresh of connections without writing your own watcher;
  • The gateway's route resolver RouteResolver reads ServiceInstanceCache directly and selects an instance via the load balancing strategy (see section 7);
  • Call discoveryCenter.destroy() in destroy() (the class loader of each deploy is isolated and the factory's static tables and instances are deploy-private, so destroying directly is enough).

6.6 The unified ServiceInstance model​

ServiceInstance carries serviceName/host/port; address parsing uses lastIndexOf(":") to support IPv6 literals.

6.7 Self-protection mode (discovery-center.properties)​

KeyDefaultDescription
selfProtectionEnabledtrueWhether to enable self-protection
selfProtectionThreshold0.85Deletions are suppressed when the retention ratio of an update (including RESYNC) within an unstable window falls below this threshold
selfProtectionWindowSeconds60Duration (seconds) of the unstable window after a registry failure

Within the window after a registry connection failure (calling ServiceInstanceCache.markRegistryUnstable()), both EVENT and RESYNC updates are protected: an update whose deletion volume exceeds the threshold keeps the local old instances and only merges additions, preventing a batch of false deregistrations caused by a ZooKeeper session flap; only FORCE (unsubscribe and clear) bypasses protection and takes effect directly. A RESYNC that does not trigger protection (the full result is healthy or the window has passed) clears the unstable window and ends protection early; a RESYNC that triggers protection is both merged under protection and does not clear the window; once the window expires (60 seconds by default) any update takes effect directly again, and the window duration bounds how long zombie instances may persist.

7. Load balancing SPI (the loadbalance package)​

club.dawdler.core.discoverycenter.loadbalance provides a load balancing SPI in the same module as the registry. It is shared by the RPC client (dawdler-client) and the gateway (dawdler-web-gateway). Interface signature:

public interface LoadBalance<T> {
T select(String service, List<T> instances); // Public entry point; returns the only instance directly when size<=1
T doSelect(String service, List<T> instances); // The actual selection algorithm implemented by subclasses
String getName(); // Strategy name, used as the SPI registration key
}

Built-in implementations:

nameImplementationAlgorithm
randomRandomLoadBalanceUniform random via ThreadLocalRandom
roundRobinRoundRobinLoadBalanceAtomicInteger modulo round-robin (the cursor is held by the instance; callers are advised to hold instances per service, see below)

LoadBalanceFactory caches only the SPI provider types; newLoadBalance(name) reflectively creates a new instance every time, and the lifecycle and isolation granularity of instances are up to the caller - for stateful strategies such as roundRobin the cursor lives inside the instance, so sharing an instance across services would make the round-robin distribution interfere with itself; hold one per service:

// RPC client: isolated by lbName#serviceName (Transaction)
// Gateway: isolated by serviceName (RouteResolver)
Map<String, LoadBalance<ServiceInstance>> lbs = new ConcurrentHashMap<>();
LoadBalance<ServiceInstance> lb = lbs.computeIfAbsent(serviceName,
k -> LoadBalanceFactory.newLoadBalance("roundRobin"));
T selected = lb.select(serviceName, instances);

Custom extensions work the same as for DiscoveryCenter: implement LoadBalance and register with both mechanisms:

  • Write the fully qualified implementation class name into META-INF/services/club.dawdler.core.discoverycenter.loadbalance.LoadBalance;
  • Declare it in module-info.java with provides club.dawdler.core.discoverycenter.loadbalance.LoadBalance with <your implementation>;.

dawdler-discovery-center-zookeeper ZooKeeper implementation

dawdler-discovery-center-consul Consul implementation

dawdler-discovery-center-server-plug server-side registration

dawdler-discovery-center-client-plug web-side registration