Add redis persisting support

- Add new StateMachineContextRepository interface.
- Add new redis module having persisting support
  for StateMachineContext.
- Extract kryo serializers into a new kryo module which
  is then shared with zookeeper and redis modules.
- We'll add redis related tests later when we figure out
  a correct pattern for integration tests.
- Fixes #110
This commit is contained in:
Janne Valkealahti
2015-12-20 15:44:15 +00:00
parent d0aaa4bfee
commit 3e322e4d00
10 changed files with 420 additions and 73 deletions

View File

@@ -149,11 +149,28 @@ project('spring-statemachine-test') {
}
}
project('spring-statemachine-zookeeper') {
description = "Spring State Machine Zookeeper"
project('spring-statemachine-kryo') {
description = "Spring State Machine Kryo"
dependencies {
compile project(":spring-statemachine-core")
compile "com.esotericsoftware.kryo:kryo:$kryoVersion"
testCompile project(":spring-statemachine-test")
testCompile "org.springframework:spring-test:$springVersion"
testCompile "org.hamcrest:hamcrest-core:$hamcrestVersion"
testCompile "org.hamcrest:hamcrest-library:$hamcrestVersion"
testCompile "junit:junit:$junitVersion"
testRuntime "log4j:log4j:$log4jVersion"
}
}
project('spring-statemachine-zookeeper') {
description = "Spring State Machine Zookeeper"
dependencies {
compile project(":spring-statemachine-core")
compile project(":spring-statemachine-kryo")
compile "org.apache.curator:curator-recipes:$curatorVersion"
compile "com.esotericsoftware.kryo:kryo:$kryoVersion"
@@ -163,7 +180,25 @@ project('spring-statemachine-zookeeper') {
testCompile "org.hamcrest:hamcrest-core:$hamcrestVersion"
testCompile "org.hamcrest:hamcrest-library:$hamcrestVersion"
testCompile "junit:junit:$junitVersion"
testRuntime("log4j:log4j:$log4jVersion")
testRuntime "log4j:log4j:$log4jVersion"
}
}
project('spring-statemachine-redis') {
description = "Spring State Machine Redis"
dependencies {
compile project(":spring-statemachine-core")
compile project(":spring-statemachine-kryo")
compile "org.springframework.data:spring-data-redis:$springDataRedisVersion"
compile "redis.clients:jedis:$jedisVersion"
testCompile project(":spring-statemachine-test")
testCompile "org.springframework:spring-test:$springVersion"
testCompile "org.hamcrest:hamcrest-core:$hamcrestVersion"
testCompile "org.hamcrest:hamcrest-library:$hamcrestVersion"
testCompile "junit:junit:$junitVersion"
testRuntime "log4j:log4j:$log4jVersion"
}
}

View File

@@ -1,5 +1,7 @@
springShellVersion=1.1.0.RELEASE
springSecurityVersion=4.0.3.RELEASE
springDataRedisVersion=1.6.2.RELEASE
jedisVersion=2.7.3
junitVersion=4.12
springVersion=4.2.2.RELEASE
kryoVersion=2.24.0

View File

@@ -2,7 +2,9 @@ rootProject.name = 'spring-statemachine'
include 'spring-statemachine-core'
include 'spring-statemachine-test'
include 'spring-statemachine-kryo'
include 'spring-statemachine-zookeeper'
include 'spring-statemachine-redis'
include 'spring-statemachine-recipes'

View File

@@ -0,0 +1,47 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.statemachine;
import org.springframework.statemachine.StateMachineContext;
/**
* Repository interface for saving and retrieving {@link StateMachineContext} objects.
*
* @author Janne Valkealahti
*
* @param <S> the type of state
* @param <E> the type of event
* @param <T> The type of state machine context
*/
public interface StateMachineContextRepository<S, E, T extends StateMachineContext<S, E>> {
/**
* Save a context.
*
* @param context the context
* @param id the id
*/
void save(T context, String id);
/**
* Gets the context.
*
* @param id the id
* @return the context
*/
T getContext(String id);
}

View File

@@ -0,0 +1,54 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.statemachine.support;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachineContextRepository;
import org.springframework.statemachine.StateMachinePersist;
/**
* A {@link StateMachinePersist} using a generic {@link StateMachineContextRepository}
* for persisting {@link StateMachineContext}.
*
* @author Janne Valkealahti
*
* @param <S> the type of state
* @param <E> the type of event
*/
public class RepositoryStateMachinePersist<S, E> implements StateMachinePersist<S, E, String> {
private final StateMachineContextRepository<S, E, StateMachineContext<S,E>> repository;
/**
* Instantiates a new repository state machine persist.
*
* @param repository the repository
*/
public RepositoryStateMachinePersist(StateMachineContextRepository<S, E, StateMachineContext<S, E>> repository) {
this.repository = repository;
}
@Override
public void write(StateMachineContext<S, E> context, String contextOjb) throws Exception {
repository.save(context, contextOjb);
}
@Override
public StateMachineContext<S, E> read(String contextOjb) throws Exception {
return repository.getContext(contextOjb);
}
}

View File

@@ -0,0 +1,53 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.statemachine.kryo;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import org.springframework.messaging.MessageHeaders;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* Kryo {@link Serializer} for spring messaging message headers.
*
* @author Janne Valkealahti
*
*/
public class MessageHeadersSerializer extends Serializer<MessageHeaders> {
@Override
public void write(Kryo kryo, Output output, MessageHeaders object) {
HashMap<String, Object> map = new HashMap<String, Object>();
for (Entry<String, Object> entry : object.entrySet()) {
map.put(entry.getKey(), entry.getValue());
}
kryo.writeClassAndObject(output, map);
}
@SuppressWarnings("unchecked")
@Override
public MessageHeaders read(Kryo kryo, Input input, Class<MessageHeaders> type) {
Map<String, Object> eventHeaders = (Map<String, Object>) kryo.readClassAndObject(input);
return new MessageHeaders(eventHeaders);
}
}

View File

@@ -0,0 +1,60 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.statemachine.kryo;
import java.util.List;
import java.util.Map;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.support.DefaultExtendedState;
import org.springframework.statemachine.support.DefaultStateMachineContext;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* Kryo {@link Serializer} for {@link StateMachineContext}.
*
* @author Janne Valkealahti
*
* @param <S> the type of state
* @param <E> the type of event
*/
public class StateMachineContextSerializer<S, E> extends Serializer<StateMachineContext<S, E>> {
@Override
public void write(Kryo kryo, Output output, StateMachineContext<S, E> context) {
kryo.writeClassAndObject(output, context.getEvent());
kryo.writeClassAndObject(output, context.getState());
kryo.writeClassAndObject(output, context.getEventHeaders());
kryo.writeClassAndObject(output, context.getExtendedState().getVariables());
kryo.writeClassAndObject(output, context.getChilds());
}
@SuppressWarnings("unchecked")
@Override
public StateMachineContext<S, E> read(Kryo kryo, Input input, Class<StateMachineContext<S, E>> clazz) {
E event = (E) kryo.readClassAndObject(input);
S state = (S) kryo.readClassAndObject(input);
Map<String, Object> eventHeaders = (Map<String, Object>) kryo.readClassAndObject(input);
Map<Object, Object> variables = (Map<Object, Object>) kryo.readClassAndObject(input);
List<StateMachineContext<S, E>> childs = (List<StateMachineContext<S, E>>) kryo.readClassAndObject(input);
return new DefaultStateMachineContext<S, E>(childs, state, event, eventHeaders, new DefaultExtendedState(variables));
}
}

View File

@@ -0,0 +1,50 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.statemachine.kryo;
import java.util.UUID;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* Kryo {@link Serializer} for {@link UUID}.
*
* @author Janne Valkealahti
*
*/
public class UUIDSerializer extends Serializer<UUID> {
/**
* Instantiates a new UUID serializer.
*/
public UUIDSerializer() {
setImmutable(true);
}
@Override
public void write(final Kryo kryo, final Output output, final UUID uuid) {
output.writeLong(uuid.getMostSignificantBits());
output.writeLong(uuid.getLeastSignificantBits());
}
@Override
public UUID read(final Kryo kryo, final Input input, final Class<UUID> uuidClass) {
return new UUID(input.readLong(), input.readLong());
}
}

View File

@@ -0,0 +1,110 @@
/*
* Copyright 2015 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.statemachine.redis;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.UUID;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.messaging.MessageHeaders;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachineContextRepository;
import org.springframework.statemachine.kryo.MessageHeadersSerializer;
import org.springframework.statemachine.kryo.StateMachineContextSerializer;
import org.springframework.statemachine.kryo.UUIDSerializer;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
/**
* A {@link StateMachineContextRepository} backed by a redis and kryo serialization.
*
* @author Janne Valkealahti
*
* @param <S> the type of state
* @param <E> the type of event
*/
public class RedisStateMachineContextRepository<S, E> implements StateMachineContextRepository<S, E, StateMachineContext<S, E>> {
private static final ThreadLocal<Kryo> kryoThreadLocal = new ThreadLocal<Kryo>() {
@SuppressWarnings("rawtypes")
@Override
protected Kryo initialValue() {
Kryo kryo = new Kryo();
kryo.addDefaultSerializer(StateMachineContext.class, new StateMachineContextSerializer());
kryo.addDefaultSerializer(MessageHeaders.class, new MessageHeadersSerializer());
kryo.addDefaultSerializer(UUID.class, new UUIDSerializer());
return kryo;
}
};
private final RedisOperations<String,byte[]> redisOperations;
/**
* Instantiates a new redis state machine context repository.
*
* @param redisConnectionFactory the redis connection factory
*/
public RedisStateMachineContextRepository(RedisConnectionFactory redisConnectionFactory) {
redisOperations = createDefaultTemplate(redisConnectionFactory);
}
@Override
public void save(StateMachineContext<S, E> context, String id) {
redisOperations.opsForValue().set(id, serialize(context));
}
@Override
public StateMachineContext<S, E> getContext(String id) {
return deserialize(redisOperations.opsForValue().get(id));
}
private static RedisTemplate<String,byte[]> createDefaultTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String,byte[]> template = new RedisTemplate<String,byte[]>();
template.setKeySerializer(new StringRedisSerializer());
template.setHashKeySerializer(new StringRedisSerializer());
template.setConnectionFactory(connectionFactory);
template.afterPropertiesSet();
return template;
}
private byte[] serialize(StateMachineContext<S, E> context) {
Kryo kryo = kryoThreadLocal.get();
ByteArrayOutputStream out = new ByteArrayOutputStream();
Output output = new Output(out);
kryo.writeObject(output, context);
output.close();
return out.toByteArray();
}
@SuppressWarnings("unchecked")
private StateMachineContext<S, E> deserialize(byte[] data) {
if (data == null || data.length == 0) {
return null;
}
Kryo kryo = kryoThreadLocal.get();
ByteArrayInputStream in = new ByteArrayInputStream(data);
Input input = new Input(in);
return kryo.readObject(input, StateMachineContext.class);
}
}

View File

@@ -18,10 +18,6 @@ package org.springframework.statemachine.zookeeper;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;
import org.apache.curator.framework.CuratorFramework;
@@ -33,12 +29,12 @@ import org.springframework.messaging.MessageHeaders;
import org.springframework.statemachine.StateMachineContext;
import org.springframework.statemachine.StateMachineException;
import org.springframework.statemachine.StateMachinePersist;
import org.springframework.statemachine.support.DefaultExtendedState;
import org.springframework.statemachine.support.DefaultStateMachineContext;
import org.springframework.statemachine.kryo.MessageHeadersSerializer;
import org.springframework.statemachine.kryo.StateMachineContextSerializer;
import org.springframework.statemachine.kryo.UUIDSerializer;
import org.springframework.util.Assert;
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.Serializer;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
@@ -148,66 +144,4 @@ public class ZookeeperStateMachinePersist<S, E> implements StateMachinePersist<S
return kryo.readObject(input, StateMachineContext.class);
}
private static class StateMachineContextSerializer<S, E> extends Serializer<StateMachineContext<S, E>> {
@Override
public void write(Kryo kryo, Output output, StateMachineContext<S, E> context) {
kryo.writeClassAndObject(output, context.getEvent());
kryo.writeClassAndObject(output, context.getState());
kryo.writeClassAndObject(output, context.getEventHeaders());
kryo.writeClassAndObject(output, context.getExtendedState().getVariables());
kryo.writeClassAndObject(output, context.getChilds());
}
@SuppressWarnings("unchecked")
@Override
public StateMachineContext<S, E> read(Kryo kryo, Input input, Class<StateMachineContext<S, E>> clazz) {
E event = (E) kryo.readClassAndObject(input);
S state = (S) kryo.readClassAndObject(input);
Map<String, Object> eventHeaders = (Map<String, Object>) kryo.readClassAndObject(input);
Map<Object, Object> variables = (Map<Object, Object>) kryo.readClassAndObject(input);
List<StateMachineContext<S, E>> childs = (List<StateMachineContext<S, E>>) kryo.readClassAndObject(input);
return new DefaultStateMachineContext<S, E>(childs, state, event, eventHeaders, new DefaultExtendedState(variables));
}
}
private static class MessageHeadersSerializer extends Serializer<MessageHeaders> {
@Override
public void write(Kryo kryo, Output output, MessageHeaders object) {
HashMap<String, Object> map = new HashMap<String, Object>();
for (Entry<String, Object> entry : object.entrySet()) {
map.put(entry.getKey(), entry.getValue());
}
kryo.writeClassAndObject(output, map);
}
@SuppressWarnings("unchecked")
@Override
public MessageHeaders read(Kryo kryo, Input input, Class<MessageHeaders> type) {
Map<String, Object> eventHeaders = (Map<String, Object>) kryo.readClassAndObject(input);
return new MessageHeaders(eventHeaders);
}
}
private static class UUIDSerializer extends Serializer<UUID> {
public UUIDSerializer() {
setImmutable(true);
}
@Override
public void write(final Kryo kryo, final Output output, final UUID uuid) {
output.writeLong(uuid.getMostSignificantBits());
output.writeLong(uuid.getLeastSignificantBits());
}
@Override
public UUID read(final Kryo kryo, final Input input, final Class<UUID> uuidClass) {
return new UUID(input.readLong(), input.readLong());
}
}
}