Installation
Before we start using Redis in Java, we need to make sure that we have the Redis service and the Java Redis driver installed and that Java is working properly on your machine. Java installation configuration can refer to our Java Development environment configuration next let's install the Java Redis driver:
- First you need to download the driver package, download the Jedis.jar, and make sure to download the latest driver package.
- Include the driver package in your classpath.
Connect to the Redis service
Import Redis.clients.jedis.jedis;public class Redisjava {public static void Main (string[] args) { //Connect local Redis Service Jedis Jedis = new Jedis ("localhost"); SYSTEM.OUT.PRINTLN ("Connection succeeded"); See if the service is running System.out.println ("Server is running:" +jedis.ping ());}}
Compile the above Java program to ensure that the path to the driver package is correct.
Connection Successful
Service is running: PONG
Redis Java String (string) instance
Import Redis.clients.jedis.Jedis;
public class Redisstringjava {public static void Main (string[] args) { //Connect local Redis service Jedis Jedis = new Jed Is ("localhost"); SYSTEM.OUT.PRINTLN ("Connection succeeded"); Set Redis string data jedis.set ("W3ckey", "www.w3cschool.cn"); Gets the stored data and outputs the System.out.println ("Redis stored string is:" + jedis.get ("W3ckey"));}}
Compile the above program.
Connection Successful
Redis Java list (list) instance
Import Java.util.List
public class Redislistjava {public static void Main (string[] args) { //Connect local Redis service Jedis Jedis = new Jedis ("localhost"); SYSTEM.OUT.PRINTLN ("Connection succeeded"); Store data into the list of Jedis.lpush ("Tutorial-list", "Redis"); Jedis.lpush ("Tutorial-list", "Mongodb"); Jedis.lpush ("Tutorial-list", "Mysql"); Get the stored data and output list<string> List = Jedis.lrange ("Tutorial-list", 0, 2); for (int i=0; i<list.size (); i++) {
SYSTEM.OUT.PRINTLN ("list item is:" +list.get (i));
}
Compile the above program.
The connection Success list item is: Redis list item: MONGODB list item: Mysql
Redis Java Keys Instance
Import Java.util.Iterator;
Import Java.util.Set;
public class Rediskeyjava {public static void Main (string[] args) { //Connect local Redis service Jedis Jedis = new Jedis ( "localhost"); SYSTEM.OUT.PRINTLN ("Connection succeeded"); Obtain data and output 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
W3ckey
Using Redis for Java