Skip to content

Instantly share code, notes, and snippets.

@mathieucarbou
Created May 8, 2014 17:43
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mathieucarbou/21051be4a2abd7cc1006 to your computer and use it in GitHub Desktop.
Save mathieucarbou/21051be4a2abd7cc1006 to your computer and use it in GitHub Desktop.
Redisson Kryo Encoder
import com.esotericsoftware.kryo.Kryo;
public interface KryoPool {
Kryo get() throws Exception;
void yield(Kryo kryo);
}
//////////////////////////////////////////////////////////////
public class RedissonKryoCodecException extends RuntimeException {
public RedissonKryoCodecException(Throwable cause) {
super(cause.getMessage(), cause);
setStackTrace(cause.getStackTrace());
}
}
//////////////////////////////////////////////////////////////
import com.esotericsoftware.kryo.Kryo;
import com.esotericsoftware.kryo.io.Input;
import com.esotericsoftware.kryo.io.Output;
import org.redisson.codec.RedissonCodec;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.nio.ByteBuffer;
public class RedissonKryoCodec implements RedissonCodec {
private final KryoPool kryoPool;
public RedissonKryoCodec(KryoPool kryoPool) {
this.kryoPool = kryoPool;
}
private Object decode(ByteBuffer bytes) {
Kryo kryo = null;
try {
kryo = kryoPool.get();
return kryo.readClassAndObject(new Input(new ByteArrayInputStream(bytes.array(), bytes.arrayOffset() + bytes.position(), bytes.limit())));
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RedissonKryoCodecException(e);
} finally {
if (kryo != null) {
kryoPool.yield(kryo);
}
}
}
@Override
public byte[] encodeValue(Object value) {
Kryo kryo = null;
try {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Output output = new Output(baos);
kryo = kryoPool.get();
kryo.writeClassAndObject(output, value);
output.close();
return baos.toByteArray();
} catch (Exception e) {
if (e instanceof RuntimeException) {
throw (RuntimeException) e;
}
throw new RedissonKryoCodecException(e);
} finally {
if (kryo != null) {
kryoPool.yield(kryo);
}
}
}
@Override
public byte[] encodeKey(Object key) {
return encodeValue(key);
}
@Override
public Object decodeKey(ByteBuffer bytes) {
return decode(bytes);
}
@Override
public Object decodeValue(ByteBuffer bytes) {
return decode(bytes);
}
@Override
public byte[] encodeMapValue(Object value) {
return encodeValue(value);
}
@Override
public byte[] encodeMapKey(Object key) {
return encodeKey(key);
}
@Override
public Object decodeMapValue(ByteBuffer bytes) {
return decodeValue(bytes);
}
@Override
public Object decodeMapKey(ByteBuffer bytes) {
return decodeKey(bytes);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment