Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lettuce RedisCodec For Numbers

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?

like image 577
user1491636 Avatar asked Oct 07 '19 18:10

user1491636


People also ask

What is RedisCodec?

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.

How does Redis cluster connect to lettuce?

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.

What is LettuceConnectionFactory?

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() .


1 Answers

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());
    }

}
like image 127
Laurent Avatar answered Nov 12 '22 08:11

Laurent