4

I have a complex java object with all types of data types. We need to push this object to Redis cache with string as key and value is this object. We have Redis cluster of 6 machines.

How to push this object through java code using lettuce cluster client?

Shabbir Dhangot
  • 8,954
  • 10
  • 58
  • 80

2 Answers2

8

You have two options:

  1. You perform serialization (JDK serialization, JSON, Protobuf, ...) on your own. You can do that before sending data to Redis, or you implement an own RedisCodec that does the job (see CustomCodecTest.java or CustomCodecTest.java)
  2. Use a framework in front of lettuce (such as Spring Data Redis). Spring Data Redis comes with various codecs that provide serialization out of the box.
yelliver
  • 5,648
  • 5
  • 34
  • 65
mp911de
  • 17,546
  • 2
  • 55
  • 95
  • Able to do that with jdk serialization. Thanks for your support. – Pavan Kumar R R Sep 01 '16 at 07:00
  • Need one more help. I have redis installed in two clouds. each has set six machines, will all 12 be part of same cluster or they are two different clusters with 6 machines each? If I want all 12 to be same cluster how can I achieve this easily? – Pavan Kumar R R Sep 01 '16 at 07:02
  • Depends on your configuration. If the two installations are able to connect each other, it should be feasible. – mp911de Sep 01 '16 at 07:17
  • The interface was changed so CustomCodecTest.java cannot run, even the link is dead now, I just post my answer for reference purposes – yelliver Nov 29 '21 at 04:26
1

This is the customized RedisCodec to save the object as serialized form:

StatefulRedisConnection<String, Object> connect = RedisClient.create(redisUri).connect(
  new RedisCodec<String, Object>() {
    private final ByteArrayCodec byteArrayCodec = new ByteArrayCodec();

    @Override
    public String decodeKey(ByteBuffer byteBuffer) {
      return Charset.defaultCharset().decode(byteBuffer).toString();
    }

    @Override
    public Object decodeValue(ByteBuffer bytes) {
      try (ObjectInputStream is = new ObjectInputStream(new ByteArrayInputStream(byteArrayCodec.decodeValue(bytes)))) {
        return is.readObject();
      } catch (Exception e) {
        throw new IllegalArgumentException(e);
      }
    }

    @Override
    public ByteBuffer encodeKey(String s) {
      return Charset.defaultCharset().encode(s);
    }

    @Override
    public ByteBuffer encodeValue(Object o) {
      try (ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(bos)) {
        os.writeObject(o);
        return byteArrayCodec.encodeValue(bos.toByteArray());
      } catch (Exception e) {
        throw new IllegalArgumentException(e);
      }
    }
  }
);
RedisCommands<String, Object> commands = connect.sync();
List<String> input = Arrays.asList("this", "is", "a", "test");
commands.set("test", input);
Object result = commands.get("test");
assert (result.equals(input));
yelliver
  • 5,648
  • 5
  • 34
  • 65