第一部分 安裝首先訪問redis.io下載最新穩定版2.2.12,接著按照下面步驟進行操作0,tar -xvzf redis-2.2.12.tar.gz
1,cd redis-2.2.12
2,make
3,edit redis/redis.conf,set maxmemory 100mb (here,we just for test,so this size is set to 100mb)
4,sudo sysctl vm.overcommit_memory=1
5,src/redis-server redis.conf (start up server)
6,src/redis-cli (start up the client)
7,test on redis:
mingyuan@mingyuan-laptop:/opt/redis-2.2.12$ src/redis-cli
redis 127.0.0.1:6379> set m 1
OK
redis 127.0.0.1:6379> get m
"1"
redis 127.0.0.1:6379> exit
mingyuan@mingyuan-laptop:/opt/redis-2.2.12$第二部分 使用jedis操作redis廢話不說,直接上代碼:package cn.mingyuan.redis;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import redis.clients.jedis.Jedis;
public class Test {
/**
* @param args
* @throws IOException
* @throws ClassNotFoundException
*/
public static void main(String[] args) throws IOException,
ClassNotFoundException {
Jedis redis = new Jedis("localhost");
//connect可以不要,因為在執行set操作的時候會先進行判斷用戶端是否於伺服器端建立了串連,若無,則啟動串連過程
redis.connect();
String set = redis.set("mingyuan", "1");
System.out.println(" set result \t" + set);
redis.incr("mingyuan");
String string = redis.get("mingyuan");
System.out.println(" get result of key 'mingyuan' \t" + string);
//下面是對對象進行儲存的測試代碼
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
Person person = new Person();
person.setAge(1);
person.setName("mingyuan");
oos.writeObject(person);
byte[] byteArray = bos.toByteArray();
oos.close();
bos.close();
String setObjectRet = redis.set("mingyuan".getBytes(), byteArray);
System.out.println(" set object return \t" + setObjectRet);
byte[] bs = redis.get("mingyuan".getBytes());
ByteArrayInputStream bis = new ByteArrayInputStream(bs);
ObjectInputStream inputStream = new ObjectInputStream(bis);
Person readObject = (Person) inputStream.readObject();
System.out.println(" read object \t" + readObject.toString());
inputStream.close();
bis.close();
redis.disconnect();
}
}person類:package cn.mingyuan.redis;
import java.io.Serializable;
/**
* 測試用pojo,實現了Serializable,以便進行系列化操作
* @author mingyuan
*
*/
public class Person implements Serializable {
private static final long serialVersionUID = -3562550857760039655L;
@Override
public String toString() {
return "Person [name=" + name + ", age=" + age + "]";
}
private String name;
private int age;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}輸出結果: set result OK
get result of key 'mingyuan' 2
set object return OK
read object Person [name=mingyuan, age=1]第三部分 總結redis作為一個比較流行的k/v資料庫操作簡單,部署方便,且有好用的java用戶端(jedis),後面有許多值得發掘的東西,會一一分享出來。