Lettuce is a very efficient and extensible Redis client for Java. Lettuce is interesting for many reasons but one of the big ones is the fact that provides an Observable / Flux API. So you can very efficient reactive programming with RxJava or Reactive-Streams power by Reactor. I’m using lettuce in production in the last 2 years and have been really great. For this blog post, I will how to dispatch custom commands to redis-modules via Lettuce.
Lettuce Features — Why Lettuce?
Lettuce is maintained by Pivotal and has many great features like:
- Non-Blocking IO
- Java 8 types: Flux | Mono
- Dynamic Commands
- Redis-Modules Support
- Cloud Ready
Building a Custom Redis Module
Some time ago I show how to build a simple redis-module using C. If you did not read the previous post please read it here. We will need that custom redis module in order to send our commands in Lettuce. There are 2 options EVAL and DISPATCH.
Sending Custom Commands via Lettuce Dispatch
EVAL is a simple way, we basically sensing some simple Lua Script returning the command and this will be run inside Redis. Let’s take a look at the code:
So what do we have here? We basically create a simple connection to Redis. We are creating RedisAsyncCommands in order to leverage async and non-blocking IO. Them we do the EVAL with this: return redis.call(‘dp.DATE’) .This means “dp.DATE” is the name of the command and we are just calling the command and get whatever it will return — for this case it will be the current date. This is fine considering that the Lua Script just call the command so the overhead is pretty minimal. The main advantage of this approach is that EVAL support is old in Redis — since 2.6 version. There is a better approach but not all clients / eco-system is ready for it. So let’s look 2 and best option. Second Option is to use DISPATCH so we can send custom protocol(Which means raw encoded command) and a list of arguments. This will be sent straight to Redis without Lua Script. Let’s take a look at the code:
So basically here we need to define a ProtocolKeyword with is pretty much the encoding of the command. Them we can get the Async command and just DISPATCH. Keep in mind this is done in Async fashion. I’m also not passing any parameters but we could if we need.
Redis-Modules are getting more popular and this is the right way to customize Redis. Lettuce proved to be very efficient and flexible client in production for Java. Now you can wrap this EVALs or DISPATCH under some java Interfaces and have a very nice extended driver for your use cases.
You can get the full code on my GitHub here.
Originally published at diego-pacheco.blogspot.com.