Search code examples
javaredislettuce

Lettuce multiple reactive Redis stores and transactions across stores


I'm learning Redis for Java is something that I think I'm really missing about the Redis api.
Say we have the following code for creating a connection:

RedisClient redisClient = RedisClient
  .create("redis://password@localhost:6379/");
StatefulRedisConnection<String, String> connection
 = redisClient.connect();

This defines a client for key type String and value type String.
Now what do I do when I need to handle multiple Redis objects, like not only String/String, but for example multiple sets with different types?
Should I create a different connection for each?
I have tried to use the reactive templates but get into the same problem i that I would create multiple instances with different types.

When dealing with transactions I don't understand how to use a transaction across a single template.
For example, I want to insert a serialized post into a Redis store like:

Key postId | Value <post> 

But in one transaction, I also want to add the postId in a set that represents a feed:

Key topic | Value <set with post Id's>

All examples that I found perform transactions on the same template, but I have no idea how to continue with this.
Pointers are appreciated.


Solution

  • The String, String part while defining a StatefulRedisConnection is applicable only to the codec being used. When you define:

    StatefulRedisConnection<String, String> connection = redisClient.connect();
    

    a predefined StringCodec is used by RedisClient to transfer data between java client and Redis.

    You can use your custom codec here if you want to change how keys and values are encoded and decoded while transferring data to and fro between Redis and Client. More detail about RedisCodec here.

    For the purpose of your problem. You still should be able to use same connection for different types of operations, provided the key and value(s) are all Strings. For keys and values which are of Object type, you should serialize them and pass the serialized results to above connection.

    Here is an example snippet (didn't run/test this).

    RedisClient redisClient = RedisClient.create("redis://password@localhost:6379/0");
    StatefulRedisConnection<String, String> connection = redisClient.connect();
    RedisCommands<String, String> syncCommands = connection.sync();
    syncCommands.multi();
    syncCommands.sadd("topics", "value1", "value2", "value3"); // Puts topics in the set
    syncCommands.set("posts", "serialized post"); // Puts serialized post
    syncCommands.exec();
    

    Hope this helps.