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:
Connect to the Redis service
Attention:
⊙ firewall off: UFW disable
⊙ip address settings: #bind 127.0.0.1
Class:redisjava
PackageRedisdemo;ImportRedis.clients.jedis.Jedis; Public classRedisjava { Public Static voidMain (string[] args) {//Connect to a local Redis serviceJedis Jedis =NewJedis ("192.168.3.22"); System.out.println ("Connection to Server sucessfully"); //See if the service is runningSystem.out.println ("Server is running:" +jedis.ping ()); }}
Console:
Connection to server Sucessfullyserver is Running:pong
Redis Java String (string) instance
Class:redisstringjava
PackageRedisdemo;ImportRedis.clients.jedis.Jedis; Public classRedisstringjava { Public Static voidMain (string[] args) {//Connect to a local Redis serviceJedis Jedis =NewJedis ("192.168.3.22"); System.out.println ("Connection to Server sucessfully"); //setting up Redis string DataJedis.set ("Lime", "Redis Tutorial"); //get the stored data and outputSystem.out.println ("Stored string in Redis::" + jedis.get ("lime")); }}
Console:
Connection to server sucessfullystored string in Redis:: Redis Tutorial
Redis Java list (list) instance
Class:
PackageRedisdemo;Importjava.util.List;ImportRedis.clients.jedis.Jedis; Public classRedislistjava { Public Static voidMain (string[] args) {//Connect to a local Redis serviceJedis Jedis =NewJedis ("192.168.3.22"); System.out.println ("Connection to Server sucessfully"); //storing data in a listJedis.lpush ("Tutorial-list", "lime"); Jedis.lpush ("Tutorial-list", "Oracle"); Jedis.lpush ("Tutorial-list", "Limeoracle"); //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)); } }}
Console:
Connection to server sucessfullystored string in Redis:: limeoraclestored string in Redis:: oraclestored string in Redis:: Lime
Redis Java Keys Instance
Class:
PackageRedisdemo;ImportJava.util.Iterator;ImportJava.util.Set;ImportRedis.clients.jedis.Jedis; Public classRediskeyjava { Public Static voidMain (string[] args) {//Connect to a local Redis serviceJedis Jedis =NewJedis ("192.168.3.22"); System.out.println ("Connection to Server sucessfully"); //get the data and outputset<string> keys = Jedis.keys ("*"); Iterator<String> it=Keys.iterator (); while(It.hasnext ()) {String key=It.next (); SYSTEM.OUT.PRINTLN (key); } }}
Console:
Connection to server sucessfullylilimekeytutorial-list
La La la
La La la
Using Redis for Java