How can i run Redis raw commands in Java Lettuce?

2.5k views Asked by At

I am building a Java application using lettuce as a Redis client.

One of the requirements is to run the redis commands from inside the application as i would run them from the command line redis-cli so instead of writing the implemented API method:

commands.set("key", "value");

I enter the actual raw command:

SET key value

and the command would run on the server. For example is there a method in the letuce api simmilar to this?

commands.runrawcommand("SET key value");

Thanks in Advance

2

There are 2 answers

0
mp911de On

That won't entirely work. Redis commands as used in a cli require parsing and result processing. Take a look at the wiki explaining Custom commands.

0
Sobhan On

Actually, it is possible and @mp911de's answer is not correct, although it has the correct reference link : Custom Commands

You can easily create an interface and by extending following io.lettuce.core.dynamic.Commands interface you can define your raw command as below:

public interface CustomCommands extends Commands {

    @Command("FCALL :functionName :keysCount :jobsKey :inboxRef :jobsRef :jobIdentity :frwrdMsg ")
    Object fcall_responseJob(@Param("functionName") byte[] functionName, @Param("keysCount") Integer keysCount,
                 @Param("jobsKey") byte[] jobsKey, @Param("inboxRef") byte[] inboxRef,
                 @Param("jobsRef") byte[] jobsRef, @Param("jobIdentity") byte[] jobIdentity,
                 @Param("frwrdMsg") byte[] frwrdMsg);

}

And for your usecase it could be like:

@Command("SET :key :value")
Object custom_set(@Param("key") String key, Param("value") String value); 

Then you can call it as below:

   RedisCommandFactory factory = new RedisCommandFactory(connection);
   CustomCommands commands = factory.getCommands(CustomCommands.class);
   Object obj = commands.csustom_set("YOUR_KEY".getBytes(StandardCharsets.UTF_8),
                                     "YOUR_VALUE".getBytes(StandardCharsets.UTF_8));