Using Redis with Java
Installation
Before you start using Redis in Java, ensure that you have the Redis service and the Java Redis driver installed, and that Java is properly set up on your machine. For Java installation and configuration, refer to our Java Development Environment Setup. Next, let's install the Java Redis driver:
First, download the driver package Download jedis.jar, ensuring you get the latest driver package.
Include the driver package in your classpath.
This site provides the 2.9.0 jar version for download: jedis-2.9.0.jar
Connecting to Redis Service
Example
import redis.clients.jedis.Jedis;
public class RedisJava {
public static void main(String[] args) {
// Connect to the local Redis service
Jedis jedis = new Jedis("localhost");
// If Redis service has a password, use the following line, otherwise omit it
// jedis.auth("123456");
System.out.println("Connection successful");
// Check if the service is running
System.out.println("Service is running: " + jedis.ping());
}
}
Compile the above Java program, ensuring the driver package path is correct.
Connection successful
Service is running: PONG
Redis Java String Example
Example
import redis.clients.jedis.Jedis;
public class RedisStringJava {
public static void main(String[] args) {
// Connect to the local Redis service
Jedis jedis = new Jedis("localhost");
System.out.println("Connection successful");
// Set Redis string data
jedis.set("tutorialprokey", "www.tutorialpro.org");
// Get stored data and print it
System.out.println("Stored string in redis: " + jedis.get("tutorialprokey"));
}
}
Compile the above program.
Connection successful
Stored string in redis: www.tutorialpro.org
Redis Java List Example
Example
import java.util.List;
import redis.clients.jedis.Jedis;
public class RedisListJava {
public static void main(String[] args) {
// Connect to the local Redis service
Jedis jedis = new Jedis("localhost");
System.out.println("Connection successful");
// Store data in list
jedis.lpush("site-list", "tutorialpro");
jedis.lpush("site-list", "Google");
jedis.lpush("site-list", "Taobao");
// Get stored data and print it
List<String> list = jedis.lrange("site-list", 0, 2);
for (int i = 0; i < list.size(); i++) {
System.out.println("List item: " + list.get(i));
}
}
}
Compile the above program.
Connection successful
List item: Taobao
List item: Google
List item: tutorialpro
Redis Java Keys Example
Example
import java.util.Iterator;
import java.util.Set;
import redis.clients.jedis.Jedis;
public class RedisKeyJava {
public static void main(String[] args) {
// Connect to local Redis server
Jedis jedis = new Jedis("localhost");
System.out.println("Connection successful");
// Retrieve data and print
Set<String> keys = jedis.keys("*");
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
System.out.println(key);
}
}
}
Compile the above program.
Connection successful
tutorialprokey
site-list