Similarly, we can write client applications using Java to interact and work with Redis. The easiest way to do so is with the Jedis Java driver for Redis, via Apache Maven. To accomplish this, I'll create a new Maven project with the following entries in the pom.xml:
<dependencies>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.9.0</version>
<type>jar</type>
<scope>compile</scope>
</dependency>
</dependencies>
Once that is done, we will write our Java code (similar to the previous Python example) to get, set, and output a welcome message from the Redis server. We will start by writing a Java class to handle all of our interactions with Redis, and name it RedisConnection:
import redis.clients.jedis.Jedis;
public class RedisConnection {
private Jedis redisConn;
We will create two constructors: one without arguments, and one that accepts a node and a password:
public RedisConnection() {
}
public RedisConnection(String node, String pwd) {
connect(node,pwd);
}
Then we'll create a public void connect method that takes an endpoint and our password and connects to our Redis server:
public void connect(String node, String pwd) {
redisConn = new Jedis(node);
redisConn.auth(pwd);
}
We will also create methods to query and update the data, as well as to close the connection to Redis (returning it to the connection pool):
public String get(String strKey) {
return redisConn.get(strKey);
}
public void set(String strKey, String strValue) {
redisConn.set(strKey, strValue);
}
public void close() {
redisConn.close();
}
Finally, we will create a short main class to connect to our server, query the value stored at the packt:welcome key, change the message, and return the new message as output:
public class RedisHelloWorld {
public static void main(String[] args) {
RedisConnection conn = new RedisConnection("127.0.0.1",
"currentHorseBatteryStaple");
System.out.println("Connected to Redis");
String key = "packt:welcome";
String newMessage = "Hello world from Java!";
This section queries the current value stored at our packt:welcome key:
//GET value stored in packt:welcome
System.out.println("Displaying current welcome message...");
String message = conn.get("packt:welcome");
System.out.println(message);
Here, we set the key's value to store the new welcome message:
//SET new value packt:welcome
System.out.println("Writing \"" + newMessage + "\" to Redis...");
conn.set(key,newMessage);
Here, we will query the key's value one more time, and display the current welcome message. When finished, we will invoke our RedisConnection's close() method:
//GET value stored in packt:welcome
System.out.println("Displaying the new welcome message...");
message = conn.get("packt:welcome");
System.out.println(message);
conn.close();
}
}
When running this code in my Integrated Developer Environment (IDE), I get the following results:
Connected to Redis Displaying current welcome message... Hello world from Python! Writing "Hello world from Java!" to Redis... Displaying the new welcome message... Hello world from Java!
The preceding code was meant to show the basic get/set methods of Redis/Jedis. It could be further optimized (reducing a network trip) by implementing the use of the getset command in the RedisConnection class:
public String getSet(String strKey, String strValue) {
return redisConn.getSet(strKey, strValue);
}
Now that we have a simple hello world app working with Java and Redis, we will switch back to our recent login tracking use case. We will use the same RedisConnection class, with three new methods.
The first new method will be the getList method. Simply put, this will take a key as a parameter, and return the associated list of values as a List<String>. We are forcing a start index of 0 (zero) and an ending index of -1, to ensure that the list is returned in its entirety:
public List<String>getList(String strKey) {
return redisConn.lrange(strKey, 0, -1);
}
Next, we need a method to add a new value to a list. This method will execute a lpush (left push) to add our new value to the left-most position in the list:
public void pushToList(String strKey, String strValue) {
redisConn.lpush(strKey, strValue);
}
As with our previous implementation of this functionality in Python, our business requirements dictate that we only need to keep track of a finite number of user logins. This method will execute a ltrim (only keep N number of items, starting from the left) on the list, and allows us to specify the number of entries that we want it to contain:
public void capList(String strKey, intintLen) {
redisConn.ltrim(strKey, 0, intLen - 1);
}
Now we will write a new main class to create our connection to Redis, insert a new entry to the packt:logins list, and then return the list as output. For this implementation, we will need a few more Java imports:
import java.util.List;
import java.text.SimpleDateFormat;
import java.util.Date;
public class RedisQueryUser {
public static void main(String[] args) {
RedisConnection conn = new
RedisConnection("127.0.0.1","currentHorseBatteryStaple");
System.out.println("Connected to Redis");
Here, we will pre-define local variables with their necessary values, and assemble the value that we want to push out to the packt:logins list:
String key = "packt:logins";
String userid = System.getProperty("user.name");
//get ip address as the lone command line argument
String ip = args[0];
String strTime = new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss.SSS").format(new Date());
String value = userid + " " + ip + " " + strTime;
With that complete, we can push our new value to Redis:
//log user
conn.pushToList(key, value);
With the new item in the list, we will next want to ensure that it only tracks the three most recent logins:
//keep list to a max of 3
conn.capList(key, 3);
Next, we will read the packt:logins list and output its contents:
//read login list
List<String> logins = conn.getList(key);
//output login list
for (String user : logins) {
System.out.println(user);
}
Finally, we will invoke our RedisConnection close() method:
conn.close();
}
}
When running the preceding code (passing in 10.0.0.4 as a parameter), I see the following output:
Connected to Redis aploetz 10.0.0.4 2017-07-01 10:21:43.196 aploetz 10.0.0.9 2017-06-26 23:00:19.104434 aploetz 10.0.0.9 2017-06-24 16:43:49.958260