Java鏈接Redis

在Java程序中使用Redis以前,須要確保在機器上安裝了Redis的Java驅動程序和Java環境。html

1、安裝Redisjava

sudo apt-get install redis-serverredis

2、配置Redis Java驅動程序sql

  下載最新版本jedis Java驅動eclipse

wget http://central.maven.org/maven2/redis/clients/jedis/2.9.0/jedis-2.9.0.jarmaven

將jedis包含到類路徑中。(如eclipse中的配置路徑加上給文件)spa

3、代碼code

package www.zjptcc.wxw.jdbctest;
import java.util.List;
import redis.clients.jedis.Jedis;

public class RedisJava {

	private static Jedis jedis;

	public static void main(String[] args) {
		jedis = new Jedis("localhost",6379);   //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"));
		

	      //store data in redis list 
	      jedis.lpush("tutorial-list", "Redis"); 
	      jedis.lpush("tutorial-list", "Mongodb"); 
	      jedis.lpush("tutorial-list", "Mysql"); 
	      jedis.lpush("tutorial-list", "Postgres"); 
	      // 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)); 
	      } 
	}

}

運行結果:server

Connection to server sucessfully
Stored string in redis:: Redis tutorial
Stored string in redis:: Postgres
Stored string in redis:: Mysql
Stored string in redis:: Mongodb
Stored string in redis:: Redis
Stored string in redis:: Postgres
Stored string in redis:: Mysql

4、jedis客戶端htm

上面的java程序運行三次後有12條數據存入tutorial-list,下面的命令刪除其中的8條

$ redis-cli 
127.0.0.1:6379> lrange tutorial-list 0 100
 1) "Postgres"
 2) "Mysql"
 3) "Mongodb"
 4) "Redis"
 5) "Postgres"
 6) "Mysql"
 7) "Mongodb"
 8) "Redis"
 9) "Postgres"
10) "Mysql"
11) "Mongodb"
12) "Redis"
127.0.0.1:6379> rpop tutorial-list
"Redis"
127.0.0.1:6379> rpop tutorial-list
"Mongodb"
127.0.0.1:6379> rpop tutorial-list
"Mysql"
127.0.0.1:6379> rpop tutorial-list
"Postgres"
127.0.0.1:6379> rpop tutorial-list
"Redis"
127.0.0.1:6379> rpop tutorial-list
"Mongodb"
127.0.0.1:6379> rpop tutorial-list
"Mysql"
127.0.0.1:6379> rpop tutorial-list
"Postgres"
127.0.0.1:6379> lrange tutorial-list 0 100
1) "Postgres"
2) "Mysql"
3) "Mongodb"
4) "Redis"
127.0.0.1:6379>

參考:

Redis 列表(List)

http://www.runoob.com/redis/redis-lists.html

相關文章
相關標籤/搜索