Spring Cloud Zookeeper Dependency Watcher

Dependency Watcher 机制允许你为依赖项注册监听器。实际上,该功能是 Observer 模式的一种实现。当依赖项发生变化时,即其状态变为 UP 或 DOWN 时,可以应用一些自定义逻辑。

The Dependency Watcher mechanism lets you register listeners to your dependencies. The functionality is, in fact, an implementation of the Observer pattern. When a dependency changes, its state (to either UP or DOWN), some custom logic can be applied.

Activating

必须启用 Spring Cloud Zookeeper Dependencies 功能,才能使用 Dependency Watcher 机制。

Spring Cloud Zookeeper Dependencies functionality needs to be enabled for you to use the Dependency Watcher mechanism.

Registering a Listener

要注册一个监听器,你必须实现一个名为`org.springframework.cloud.zookeeper.discovery.watcher.DependencyWatcherListener`的接口并将其注册为一个 Bean。此接口提供一个方法:

To register a listener, you must implement an interface called org.springframework.cloud.zookeeper.discovery.watcher.DependencyWatcherListener and register it as a bean. The interface gives you one method:

void stateChanged(String dependencyName, DependencyState newState);

如果你想为特定依赖项注册一个监听器,dependencyName 将作为你的具体实现的辨别符。newState 会告知你的依赖项是变为 CONNECTED 还是 DISCONNECTED

If you want to register a listener for a particular dependency, the dependencyName would be the discriminator for your concrete implementation. newState provides you with information about whether your dependency has changed to CONNECTED or DISCONNECTED.

Using the Presence Checker

与 Dependency Watcher 绑定在一起的功能称为 Presence Checker。它允许你提供自定义行为,以便在应用程序启动时根据依赖项的状态采取相应措施。

Bound with the Dependency Watcher is the functionality called Presence Checker. It lets you provide custom behavior when your application boots, to react according to the state of your dependencies.

抽象`org.springframework.cloud.zookeeper.discovery.watcher.presence.DependencyPresenceOnStartupVerifier` 类的默认实现是`org.springframework.cloud.zookeeper.discovery.watcher.presence.DefaultDependencyPresenceOnStartupVerifier`,其工作方式如下。

The default implementation of the abstract org.springframework.cloud.zookeeper.discovery.watcher.presence.DependencyPresenceOnStartupVerifier class is the org.springframework.cloud.zookeeper.discovery.watcher.presence.DefaultDependencyPresenceOnStartupVerifier, which works in the following way.

  1. If the dependency is marked us required and is not in Zookeeper, when your application boots, it throws an exception and shuts down.

  2. If the dependency is not required, the org.springframework.cloud.zookeeper.discovery.watcher.presence.LogMissingDependencyChecker logs that the dependency is missing at the WARN level.

由于只有在没有类型为 DependencyPresenceOnStartupVerifier 的 Bean 时才注册 DefaultDependencyPresenceOnStartupVerifier,因此可以覆盖此功能。

Because the DefaultDependencyPresenceOnStartupVerifier is registered only when there is no bean of type DependencyPresenceOnStartupVerifier, this functionality can be overridden.