Zookeeper for data synchronization

zhurd 2021-01-23 23:18:11
zookeeper data synchronization

The goal is

  • soul zookeeper Mode data synchronization principle and source code analysis

We were right in the last one Soul The gateway webscoket A simple analysis of data synchronization mode is made , Got it websocket The basic process of synchronization . Now let's take a look at Next Soul The gateway zookeeper Data synchronization mode .

Synchronization principle

Soul gateway zookeeper Synchronization principle :

zookeeper Synchronization is mainly dependent on zookeeper Of watch Mechanism ,soul-web Will listen to the configured nodes ,soul-admin At startup , The data will be written in full zookeeper, When subsequent data changes , Will be incrementally updated zookeeper The node of , meanwhile ,soul-web Nodes that listen for configuration information , Once there is a change in information , Will update the local cache . If updated Selector Data synchronization flow chart of :


Soul Gateway on zookeeper Sync :

  • soul-bootstrap Add the following dependencies :

    <!--soul data sync start use zookeeper-->
  • application.yml Add related configuration

     soul :
    url: localhost:2181
    sessionTimeout: 5000
    connectionTimeout: 2000
    #url: Configure it for your zk Address , For cluster environment, please use (,) Separate 

soul-admin To configure , Or in the soul-admin Set... In startup parameters --soul.sync.zookeeper='', Then restart the service

url: localhost:2181
sessionTimeout: 5000
connectionTimeout: 2000

Source code analysis

soul-admin Data synchronization

soul-admin After the user changes his data , Will pass spring Of ApplicationEventPublisher Issue data change notification , from DataChangedEventDispatcher Process the change notice , And then according to the configuration zookeeper Synchronization strategies , Send the configuration to the corresponding event handler .

soul-admin Data change notification for ,Soul Three data synchronization methods of gateway webscoket、zookeeper、http Long polling The principle is the same , It's just that different data synchronization configurations have different event processors .

  • Data change notification source code analysis

If we were soul-admin After the background management has done the creation and update of the configuration , Will trigger publishEvent event

private void publishEvent(final SelectorDO selectorDO, final List<SelectorConditionDTO> selectorConditionDTOs) {
PluginDO pluginDO = pluginMapper.selectById(selectorDO.getPluginId());
List<ConditionData> conditionDataList =
// publish change event.
eventPublisher.publishEvent(new DataChangedEvent(ConfigGroupEnum.SELECTOR, DataEventTypeEnum.UPDATE,
Collections.singletonList(SelectorDO.transFrom(selectorDO, pluginDO.getName(), conditionDataList))));

publishEvent Event method , adopt DataChangedEvent Medium groupKey To handle events related to different components .

DataChangedEvent The specific implementation class of is DataChangedEventDispatcher

public class DataChangedEventDispatcher implements ApplicationListener<DataChangedEvent>, InitializingBean {
private ApplicationContext applicationContext;
private List<DataChangedListener> listeners;
public DataChangedEventDispatcher(final ApplicationContext applicationContext) {
this.applicationContext = applicationContext;
* Data change event distribution
public void onApplicationEvent(final DataChangedEvent event) {
for (DataChangedListener listener : listeners) {
// Listeners that handle different components
switch (event.getGroupKey()) {
case APP_AUTH:
listener.onAppAuthChanged((List<AppAuthData>) event.getSource(), event.getEventType());
case PLUGIN:
listener.onPluginChanged((List<PluginData>) event.getSource(), event.getEventType());
case RULE:
listener.onRuleChanged((List<RuleData>) event.getSource(), event.getEventType());
listener.onSelectorChanged((List<SelectorData>) event.getSource(), event.getEventType());
listener.onMetaDataChanged((List<MetaData>) event.getSource(), event.getEventType());
throw new IllegalStateException("Unexpected value: " + event.getGroupKey());
public void afterPropertiesSet() {
Collection<DataChangedListener> listenerBeans = applicationContext.getBeansOfType(DataChangedListener.class).values();
this.listeners = Collections.unmodifiableList(new ArrayList<>(listenerBeans));
  • zookeeper Listener source code analysis

We've opened it in front of us soul.sync.zookeeper.url=' Address ', Then there must be a place in the project to read the configuration . adopt `soul.sync.zookeeper Search for configuration classes for data synchronization DataSyncConfiguration, Here is zookeeper Configuration code for :

* The type Zookeeper listener.
@ConditionalOnProperty(prefix = "soul.sync.zookeeper", name = "url")
static class ZookeeperListener {
* Config event listener data changed listener.
* @param zkClient the zk client
* @return the data changed listener
public DataChangedListener zookeeperDataChangedListener(final ZkClient zkClient) {
return new ZookeeperDataChangedListener(zkClient);
* Zookeeper data init zookeeper data init.
* @param zkClient the zk client
* @param syncDataService the sync data service
* @return the zookeeper data init
public ZookeeperDataInit zookeeperDataInit(final ZkClient zkClient, final SyncDataService syncDataService) {
return new ZookeeperDataInit(zkClient, syncDataService);

zookeeperDataChangedListener Class is DataChangedListener The concrete implementation of the interface , adopt zkClient Send data change information

public void onSelectorChanged(final List<SelectorData> changed, final DataEventTypeEnum eventType) {
if (eventType == DataEventTypeEnum.REFRESH) {
// refresh
final String selectorParentPath = ZkPathConstants.buildSelectorParentPath(changed.get(0).getPluginName());
for (SelectorData data : changed) {
final String selectorRealPath = ZkPathConstants.buildSelectorRealPath(data.getPluginName(), data.getId());
if (eventType == DataEventTypeEnum.DELETE) {
// delete
final String selectorParentPath = ZkPathConstants.buildSelectorParentPath(data.getPluginName());
//create or update
upsertZkNode(selectorRealPath, data);
* create or update zookeeper node.
* @param path node path
* @param data node data
private void upsertZkNode(final String path, final Object data) {
if (!zkClient.exists(path)) {
zkClient.createPersistent(path, true);
// Update node
zkClient.writeData(path, data);
private void deleteZkPath(final String path) {
if (zkClient.exists(path)) {
// General deletion
private void deleteZkPathRecursive(final String path) {
if (zkClient.exists(path)) {
// Recursive delete

thus ,soul-admin The data transmission has been completed .

soul-bootstrap Gateway data synchronization

Turn on zookeeper Sync , Need to be in soul-bootstrap Introduction in soul-spring-boot-starter-sync-data-zookeeper, Find the corresponding customization in the project spring-boot-starter, Found out ZookeeperSyncDataConfiguration Configuration class .

@ConditionalOnProperty(prefix = "soul.sync.zookeeper", name = "url")
public class ZookeeperSyncDataConfiguration {
* Sync data service sync data service.
* zk Data synchronization
* @param zkClient the zk client
* @param pluginSubscriber the plugin subscriber
* @param metaSubscribers the meta subscribers
* @param authSubscribers the auth subscribers
* @return the sync data service
public SyncDataService syncDataService(final ObjectProvider<ZkClient> zkClient, final ObjectProvider<PluginDataSubscriber> pluginSubscriber,
final ObjectProvider<List<MetaDataSubscriber>> metaSubscribers, final ObjectProvider<List<AuthDataSubscriber>> authSubscribers) {
log.info("you use zookeeper sync soul data.......");
return new ZookeeperSyncDataService(zkClient.getIfAvailable(), pluginSubscriber.getIfAvailable(),
metaSubscribers.getIfAvailable(Collections::emptyList), authSubscribers.getIfAvailable(Collections::emptyList));
* register zkClient in spring ioc.
* yml In the document zookeeper To configure
* @param zookeeperConfig the zookeeper configuration
* @return ZkClient {@linkplain ZkClient}
public ZkClient zkClient(final ZookeeperConfig zookeeperConfig) {
return new ZkClient(zookeeperConfig.getUrl(), zookeeperConfig.getSessionTimeout(), zookeeperConfig.getConnectionTimeout());

With Selector For example , to glance at ZookeeperSyncDataService Class listening Selector The logic of data change :

// Monitor selector
private void watcherSelector(final String pluginName) {
// Assembly parent node address
String selectorParentPath = ZkPathConstants.buildSelectorParentPath(pluginName);
// Get child nodes
List<String> childrenList = zkClientGetChildren(selectorParentPath);
if (CollectionUtils.isNotEmpty(childrenList)) {
childrenList.forEach(children -> {
// Assemble real nodes
String realPath = buildRealPath(selectorParentPath, children);
// Reads the value of the specified node and updates the cache data
// Only monitor the change of node data
// Add monitoring to the parent node to monitor the changes of the child node ( Only for new child nodes 、 Reduce child nodes 、 Delete node event triggers )
subscribeChildChanges(ConfigGroupEnum.SELECTOR, selectorParentPath, childrenList);
// Only monitor the changes of nodes
private void subscribeChildChanges(final ConfigGroupEnum groupKey
, final String groupParentPath, final List<String> childrenList) {
switch (groupKey) {
// handleChildChanges(String parentPath, List<String> currentChilds)
zkClient.subscribeChildChanges(groupParentPath, (parentPath, currentChildren) -> {
if (CollectionUtils.isNotEmpty(currentChildren)) {
// from currentChildren Filter out what has been dealt with before childrenList( Data change nodes )
List<String> addSubscribePath = addSubscribePath(childrenList, currentChildren);
addSubscribePath.stream().map(addPath -> {
String realPath = buildRealPath(parentPath, addPath);
return realPath;
// Only monitor the change of node data
private void subscribeSelectorDataChanges(final String path) {
zkClient.subscribeDataChanges(path, new IZkDataListener() {
// Triggered when node data changes
public void handleDataChange(final String dataPath, final Object data) {
cacheSelectorData((SelectorData) data);
// Trigger when a node is deleted
public void handleDataDeleted(final String dataPath) {
// Get child nodes
private List<String> zkClientGetChildren(final String parent) {
if (!zkClient.exists(parent)) {
zkClient.createPersistent(parent, true);
return zkClient.getChildren(parent);
// Update cache data
private void cacheSelectorData(final SelectorData selectorData) {
.ifPresent(data -> Optional.ofNullable(pluginDataSubscriber).ifPresent(e -> e.onSelectorSubscribe(data)));

above cacheSelectorData Methods for updating cached data , The specific implementation classes are CommonPluginDataSubscriber, This is the same as the last one webscoket The call to update the cached data is the same .


  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云