位置:首頁 > 數據庫 > Redis教學 > Redis Java連接操作

Redis Java連接操作

安裝

要在Java程序中使用使用操作Redis,需要確保有Redis的Java驅動程序和Java設置在機器上。可以檢查看Java教學-學習如何在機器上安裝Java。現在,讓我們來看看如何設置Redis的Java驅動程序。

  • 需要下載jedis.jar。請一定要下載它的最新版本。
  • 需要包括jedis.jar到你的類路徑中。

連接到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