您好,登錄后才能下訂單哦!
要在Java程序中使用使用操作Redis,需要確保有Redis的Java驅動程序和Java設置在機器上。現在,讓我們來看看如何設置Redis的Java驅動程序。
連接到Redis服務器
import redis.clients.jedis.Jedis; public class RedisJava { public static void main(String[] args) { //Connecting to Redis server on localhost Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //check whether server is running or not System.out.println("Server is running: "+jedis.ping()); } }
現在,讓我們來編譯和運行上面的程序來測試連接Redis服務器。你可以根據實際情況改變路徑。這里假設jedis.jar的當前版本在當前路徑中可用
$javac RedisJava.java $java RedisJava Connection to server sucessfully Server is running: PONG
Redis和Java字符串實例
import redis.clients.jedis.Jedis; public class RedisStringJava { public static void main(String[] args) { //Connecting to Redis server on localhost Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //set the data in redis string jedis.set("tutorial-name", "Redis tutorial"); // Get the stored data and print it System.out.println("Stored string in redis:: "+ jedis.get("tutorial-name")); } }
現在,讓我們編譯并運行上述程序。
$javac RedisStringJava.java $java RedisStringJava Connection to server sucessfully Stored string in redis:: Redis tutorial
Redis和Java列表示例
import redis.clients.jedis.Jedis; public class RedisListJava { public static void main(String[] args) { //Connecting to Redis server on localhost Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //store data in redis list jedis.lpush("tutorial-list", "Redis"); jedis.lpush("tutorial-list", "Mongodb"); jedis.lpush("tutorial-list", "Mysql"); // Get the stored data and print it List<String> list = jedis.lrange("tutorial-list", 0 ,5); for(int i=0; i<list.size(); i++) { System.out.println("Stored string in redis:: "+list.get(i)); } } }
現在,讓我們編譯并運行上述程序。
$javac RedisListJava.java $java RedisListJava Connection to server sucessfully Stored string in redis:: Redis Stored string in redis:: Mongodb Stored string in redis:: Mysql
Redis和Java的鍵實例
import redis.clients.jedis.Jedis; public class RedisKeyJava { public static void main(String[] args) { //Connecting to Redis server on localhost Jedis jedis = new Jedis("localhost"); System.out.println("Connection to server sucessfully"); //store data in redis list // Get the stored data and print it List<String> list = jedis.keys("*"); for(int i=0; i<list.size(); i++) { System.out.println("List of stored keys:: "+list.get(i)); } } }
現在,讓我們編譯并運行上述程序。
$javac RedisKeyJava.java $java RedisKeyJava Connection to server sucessfully List of stored keys:: tutorial-name List of stored keys:: tutorial-list
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。