Skip to content

Instantly share code, notes, and snippets.

@sscarduzio
Last active June 8, 2023 14:17
Show Gist options
  • Save sscarduzio/4996202 to your computer and use it in GitHub Desktop.
Save sscarduzio/4996202 to your computer and use it in GitHub Desktop.
Binary codec for Lettuce (asynchronous redis client for Java)
package com.lambdaworks.redis.codec;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.charset.Charset;
/**
* A {@link RedisCodec} that handles binary keys and values.
* This is useful if you are storing non-UTF8 data in Redis
* such as serialized objects or multimedia content.
*
* @author Simone Scarduzio
*/
public class BinaryRedisCodec extends RedisCodec<byte[], byte[]> {
private Charset charset = Charset.forName("UTF-8");
@Override
public byte[] decodeKey(ByteBuffer bytes) {
System.out.println("decoding: " + bytes + " to " +charset.decode(bytes).toString());
return decode(bytes);
}
@Override
public byte[] decodeValue(ByteBuffer bytes) {
return decode(bytes);
}
@Override
public byte[] encodeKey(byte[] key) {
System.out.println("encoding '" + key + "'");
return key;
}
@Override
public byte[] encodeValue(byte[] value) {
System.out.println("encoding value: " + value );
return encode(value);
}
private byte[] encode(byte[] value) {
try {
if(value instanceof byte[]){
return (byte[])value;
}
else {
throw new IOException("byte[] value was expected");
}
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
private byte[] decode(ByteBuffer bytes) {
try {
byte[] ba = new byte[bytes.remaining()];
bytes.get(ba);
return ba;
} catch (Exception e) {
return null;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment