How to use Azure Redis Cache with Java using Lettuce


I was looking for an option of using Azure Redis cache with Java. I found the article: https://azure.microsoft.com/en-us/documentation/articles/cache-java-get-started/.

This uses the Java client called Jedis. Unfortunately, till the time of writing this blog post, Jedis doesn't have SSL option and my customer needs SSL. Hence, I had to find a different client and found Lettuce (http://redis.paluch.biz/download.html). A good no. of experts within Microsoft also recommends the same. We already implemented Redis cache using Java and Lettuce client. For other's benefit, here are the steps.

1. Set up Redis cache as recommended in the above mentioned article. Only remember, we will use SSL port (6380) in this case.

2. In your code you need to include following JAR files. You can download them from Maven repository:

lettuce-4.1.1.Final.jar

netty-buffer-4.0.34.Final.jar

netty-codec-4.0.34.Final.jar

netty-common-4.0.34.Final.jar

netty-transport-4.0.34.Final.jar

netty-transport-native-epoll-4.0.34.Final.jar

netty-handler-4.0.34.Final.jar

guava-17.0.jar

commons-pool2-2.4.2.jar

LatencyUtils-2.0.3.jar

rxjava-1.1.0.jar

HdrHistogram-2.1.4.jar

3. And here is the sample code:

import java.util.concurrent.TimeUnit;

import com.lambdaworks.redis.RedisClient;

import com.lambdaworks.redis.RedisFuture;

import com.lambdaworks.redis.RedisURI;

import com.lambdaworks.redis.api.StatefulRedisConnection;

import com.lambdaworks.redis.api.async.RedisAsyncCommands;

import com.lambdaworks.redis.api.sync.RedisCommands;

 

 

public class Test {

 

public static void main(String[] args) {

RedisURI redisURI = new RedisURI();

redisURI.setHost("your redis url");

redisURI.setPort(6380);

redisURI.setSsl(true);

redisURI.setPassword("<your password>");

RedisClient redisClient = RedisClient.create(redisURI);

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

System.out.println("Connected to Redis using SSL");

 

/*******************Sync options*****************************/

RedisCommands<String, String> syncCon = connection.sync();

syncCon.hset("fooTobar", "foo", "bar");

String value = syncCon.hget("fooTobar","foo");

System.out.println(value);

 

/************************************************************/

 

/*******************Async options*****************************/

RedisAsyncCommands<String, String> asyncCon = connection.async();

try {

RedisFuture<String> future = asyncCon.hget("fooTobar","foo");

String valueAsync = future.get(1, TimeUnit.MINUTES);

System.out.println(valueAsync);

} catch (Exception e) {

e.printStackTrace();

}

 

/************************************************************/

connection.close();

redisClient.shutdown();

}

}

 


Comments (0)

Skip to main content