lettuce icon indicating copy to clipboard operation
lettuce copied to clipboard

Update wiki

Open bytestreme opened this issue 1 year ago • 0 comments

Bug Report

Current Behavior

According to RedisCodec javadoc

    /**
     * Encode the value for output to redis.
     *
     * @param value the value, may be {@code null}.
     *
     * @return The encoded value, never {@code null}.
     */
    ByteBuffer encodeValue(V value);

But SerializedObjectCodec in wiki returns null

The command where encodeValue returns null makes Lettuce driver out of sync

Resulting in https://github.com/lettuce-io/lettuce-core/issues/2012

Environment

  • Lettuce version(s): 6.1.8.RELEASE
  • Redis version: 6.2.6

Possible Solution

Update Wiki

Return zero-length ByteBuffer instead of null in encodeValue


class SerializedObjectCodec implements RedisCodec<String, Object> {
    
    private final Charset charset = Charset.forName("UTF-8");
    
    private static final byte[] EMPTY_BYTES = new byte[]{};

    @Override
    public String decodeKey(ByteBuffer bytes) {
        return charset.decode(bytes).toString();
    }

    @Override
    public Object decodeValue(ByteBuffer bytes) {
        try {
            byte[] array = new byte[bytes.remaining()];
            bytes.get(array);
            ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(array));
            return is.readObject();
        } catch (Exception e) {
            return null;
        }
    }

    @Override
    public ByteBuffer encodeKey(String key) {
        return charset.encode(key);
    }

    @Override
    public ByteBuffer encodeValue(Object value) {
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            ObjectOutputStream os = new ObjectOutputStream(bytes);
            os.writeObject(value);
            return ByteBuffer.wrap(bytes.toByteArray());
        } catch (IOException e) {
            return ByteBuffer.wrap(EMPTY_BYTES);
        }
    }
}

Additional context

bytestreme avatar Aug 10 '22 09:08 bytestreme

The better approach is to fix the code in the wiki instead of working around API rules.

mp911de avatar Aug 15 '22 06:08 mp911de

Done.

mp911de avatar Aug 15 '22 06:08 mp911de