31. Zookeeper

Zookeeper is a distributed version from sample Chapter 25, Turnstile.

[Note]Note

This sample needs and external Zookeeper instance accessible from localhost with default port and settings.

Configuration of this sample is almost same as turnstile sample. We only add configuration for distributed state machine where we configure StateMachineEnsemble.

@Override
public void configure(StateMachineConfigurationConfigurer<String, String> config) throws Exception {
    config
        .withDistributed()
            .ensemble(stateMachineEnsemble());
}

Actual StateMachineEnsemble needs to be created as bean together with CuratorFramework client.

@Bean
public StateMachineEnsemble<String, String> stateMachineEnsemble() throws Exception {
    return new ZookeeperStateMachineEnsemble<String, String>(curatorClient(), "/foo");
}

@Bean
public CuratorFramework curatorClient() throws Exception {
    CuratorFramework client = CuratorFrameworkFactory.builder().defaultData(new byte[0])
            .retryPolicy(new ExponentialBackoffRetry(1000, 3))
            .connectString("localhost:2181").build();
    client.start();
    return client;
}

Lets go through a simple example where two different shell instances are started with command java -jar spring-statemachine-samples-zookeeper-1.0.0.BUILD-SNAPSHOT.jar.

First open first shell instance(do not start second instance yet). When state machine is started it will end up into its initial state LOCKED. Then send event COIN to transit into UNLOCKED state.

Shell1. 

sm>sm start
Entry state LOCKED
State machine started

sm>sm event COIN
Exit state LOCKED
Entry state UNLOCKED
Event COIN send

sm>sm state
UNLOCKED

Open second shell instance and start a state machine. You should see that distributed state UNLOCKED is entered instead of default initial state LOCKED.

Shell2. 

sm>sm start
State machine started

sm>sm state
UNLOCKED

Then from either of a shells(we use second instance here) send event PUSH to transit from UNLOCKED into LOCKED state.

Shell2. 

sm>sm event PUSH
Exit state UNLOCKED
Entry state LOCKED
Event PUSH send

In other shell you should see state getting changed automatically based on distributed state kept in Zookeeper.

Shell1. 

sm>Exit state UNLOCKED
Entry state LOCKED