Using Lettuce 5 as a Redis client for the first time, I'm finding it rather confusing to simply create a RedisCommands<String, Long>
for getting/setting Redis values as a Long.
It's a little unclear to me how I can accomplish this. From what I gather, the simplest way is to use the RedisClient
overloaded constructor which takes a RedisCodec
and RedisURI
, but it seems I also need to implement the codec decoding/encoding methods?
Since storing numbers is a fairly common use case with Redis, I find this approach rather bloated and I'm surprised there is no predefined codec for integer/long. Given this, I suspect there may be a simpler alternative that I have not come across. Is there an alternate approach?
A RedisCodec encodes keys and values sent to Redis, and decodes keys and values in the command output. The methods are called by multiple threads and must be thread-safe. Author: Will Glozer, Mark Paluch, Dimitris Mandalidis.
Basic Usage. Create the RedisClient instance and provide a Redis URI pointing to localhost, Port 6379 (default port). Issue a GET command to get the key foo . Close the connection when you're done.
public class LettuceConnectionFactory extends Object implements InitializingBean, DisposableBean, RedisConnectionFactory, ReactiveRedisConnectionFactory. Connection factory creating Lettuce-based connections. This factory creates a new LettuceConnection on each call to getConnection() .
I was experiencing a similar need and end up writing the following codec:
import io.lettuce.core.codec.RedisCodec;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;
public class StringLongRedisCodec implements RedisCodec<String, Long> {
@Override
public String decodeKey(final ByteBuffer bytes) {
return StandardCharsets.US_ASCII.decode(bytes).toString();
}
@Override
public Long decodeValue(final ByteBuffer bytes) {
final CharBuffer charSequence = StandardCharsets.US_ASCII.decode(bytes);
return Long.parseLong(charSequence, 0, charSequence.length(), 10);
}
@Override
public ByteBuffer encodeKey(final String key) {
return StandardCharsets.US_ASCII.encode(key);
}
@Override
public ByteBuffer encodeValue(final Long value) {
return ByteBuffer.wrap(Long.toString(value).getBytes());
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With