1. Before you start using Redis in Java, we need to make sure that the Redis service and the Java Redis Driver are installed and that Java is used properly on your machine.
- First you need to download the driver package, download the Jedis.jar, and make sure to download the latest driver package. (also Common-pool2...jar, see Jedis.jar's dependent jar package)
- Include the driver package in your classpath.
2. Connect to the Redis service
import Redis.clients.jedis.Jedis; public class Redisjava { static void main (string[] args) { // Jedis Jedis =
new
Jedis ("localhost" ); System.out.println ( Connection to server sucessfully ); // See if the service is running System.out.println ( "Server is running:" +jedis.ping ());}}
This is often an error, refer to the Java connection operation Redis Errors
Compile the above Java program to ensure that the path to the driver package is correct.
$javac Redisjava.java $java redisjava // taking command-line examples
Connection to server Sucessfullyserver is Running:pong
3. Redis Java String (string) instance
ImportRedis.clients.jedis.Jedis; Public classRedisstringjava { Public Static voidMain (string[] args) {//Connect to a local Redis serviceJedis Jedis =NewJedis ("localhost"); System.out.println ("Connection to Server sucessfully"); //setting up Redis string DataJedis.set ("Runoobkey", "Redis Tutorial"); //get the stored data and outputSystem.out.println ("Stored string in Redis::" + jedis.get ("Runoobkey")); }}
4. Redis Java list (list) instance
ImportRedis.clients.jedis.Jedis; Public classRedislistjava { Public Static voidMain (string[] args) {//Connect to a local Redis serviceJedis Jedis =NewJedis ("localhost"); System.out.println ("Connection to Server sucessfully"); //storing data in a listJedis.lpush ("Tutorial-list", "Redis"); Jedis.lpush ("Tutorial-list", "Mongodb"); Jedis.lpush ("Tutorial-list", "Mysql"); //get the stored data and outputlist<string> list = Jedis.lrange ("Tutorial-list", 0, 5); for(inti=0; I<list.size (); i++) {System.out.println ("Stored string in Redis::" +List.get (i)); } }}
5. Redis Java Keys Instance
ImportRedis.clients.jedis.Jedis; Public classRediskeyjava { Public Static voidMain (string[] args) {//Connect to a local Redis serviceJedis Jedis =NewJedis ("localhost"); System.out.println ("Connection to Server sucessfully"); //get the data and outputlist<string> list = Jedis.keys ("*"); for(inti=0; I<list.size (); i++) {System.out.println ("List of stored keys::" +List.get (i)); } }}
Using Redis for Java connections