ZooKeeper Watcher is an Apache ZooKeeper watcher for jCasbin.
For Maven
<dependency> <groupId>org.casbin</groupId> <artifactId>jcasbin-zookeeper-watcher</artifactId> <version>1.0.0</version> </dependency>
ZooKeeper Watcher uses Apache ZooKeeper's watch mechanism to synchronize policy changes across multiple jCasbin instances. When one instance updates its policy (via addPolicy, removePolicy, etc.), it updates a ZooKeeper node, which triggers watches on all other instances subscribed to that node. These instances then receive notifications and reload their policies.
Creating a ZooKeeperWatcher will:
When you call e.setWatcher(zooKeeperWatcher), it sets a default updateCallback that calls e.LoadPolicy() to reload the policy from the adapter.
If you have two Casbin instances A and B:
A: Producer
// Initialize ZooKeeper Watcher String connectString = "localhost:2181"; int sessionTimeout = 5000; String nodePath = "/casbin/policy"; ZooKeeperWatcher watcher = new ZooKeeperWatcher(connectString, sessionTimeout, nodePath); Enforcer enforcer = new SyncedEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv"); enforcer.setWatcher(watcher); // The following code is not necessary and generally does not need to be written unless you understand what you want to do /* Runnable updateCallback = () -> { // Custom behavior }; watcher.setUpdateCallback(updateCallback); */ // Modify policy, it will notify B enforcer.addPolicy(...);
B: Consumer
// Initialize ZooKeeper Watcher with same node path String connectString = "localhost:2181"; int sessionTimeout = 5000; String nodePath = "/casbin/policy"; ZooKeeperWatcher watcher = new ZooKeeperWatcher(connectString, sessionTimeout, nodePath); Enforcer enforcer = new SyncedEnforcer("examples/rbac_model.conf", "examples/rbac_policy.csv"); enforcer.setWatcher(watcher); // B sets watcher and subscribes to the node path, then it will receive the notification from A // and call LoadPolicy to reload policy
The ZooKeeperWatcher constructor accepts three parameters:
You can set a custom callback that will be invoked when policy updates are detected:
ZooKeeperWatcher watcher = new ZooKeeperWatcher(connectString, sessionTimeout, nodePath); // Using Runnable callback watcher.setUpdateCallback(() -> { System.out.println("Policy updated!"); // Custom logic here }); // Using Consumer callback for detailed information watcher.setUpdateCallback((message) -> { System.out.println("Received update: " + message); // Custom logic here });
When you're done with the watcher, remember to close it:
watcher.close();
This project is under Apache 2.0 License. See the LICENSE file for the full license text.