如何安裝Redis?
Redis的官方下載站是http://redis.io/download,可以去上面下載最新的安裝程序下來,我寫此文章時的的穩定版本是2.2.12。
怎麼安裝 Redis數據庫呢?下面將介紹Linux版本的安裝方法:
步驟一: 下載Redis
下載安裝包:wget http://redis.googlecode.com/files/redis-2.2.12.tar.gz
--19:06:56-- http://redis.googlecode.com/files/redis-2.2.12.tar.gz
正在解析主機 redis.googlecode.com... 74.125.71.82
Connecting to redis.googlecode.com|74.125.71.82|:80... 已連接。
已發出 HTTP 請求,正在等待迴應... 200 OK
長度:455240 (445K) [application/x-gzip]
Saving to: `redis-2.2.12.tar.gz'
100%[==========================================>]455,24034.8K/sin 13s
19:07:16 (34.8 KB/s) - `redis-2.2.12.tar.gz' saved [455240/455240]
[root@localhost 4setup]#
步驟二: 編譯源程序
總計 29168
-rw-r--r--1 root root 4552402011-07-22 redis-2.2.12.tar.gz
[root@localhost 4setup]# tar xzf redis-2.2.12.tar.gz
[root@localhost 4setup]# cd redis-2.2.12
[root@localhost redis-2.2.12]# make
cd src && make all
make[1]: Entering directory `/root/4setup/redis-2.2.12/src'
步驟三: 啓動Redis服務
[root@localhost redis-2.2.12]# src/redis-server
[6246] 05 Aug 19:17:22 # Warning: no config file specified, using the default config. In order to specify a config file use'redis-server /path/to/redis.conf'
[6246] 05 Aug 19:17:22* Server started, Redis version 2.2.12
[6246] 05 Aug 19:17:22 # WARNING overcommit_memory issetto0! Background save may fail under low memory condition.Tofix this issue add'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
[6246] 05 Aug 19:17:22* The server isnow readyto accept connectionson port 6379
[6246] 05 Aug 19:17:22-0 clients connected (0 slaves),539544 bytes in use
Redis 服務端的默認連接端口是 6379。
步驟四: 將Redis作爲 Linux 服務隨機啓動
vi /etc/rc.local, 使用vi編輯器打開隨機啓動配置文件,並在其中加入下面一行代碼。
步驟五: 客戶端連接驗證
新打開一個Session輸入:src/redis-cli,如果出現下面提示,那麼您就可以開始Redis之旅了。
redis 127.0.0.1:6379>
步驟六: 查看Redis日誌
查看服務器端session,即可對Redis的運行狀況進行查看或分析了。
[6246] 05 Aug 19:24:37- Accepted 127.0.0.1:51381
[6246] 05 Aug 19:24:38-1 clients connected (0 slaves),547372 bytes in use
以上的幾個步驟就OK了!!這樣一個簡單的Redis數據庫就可以暢通無阻地運行起來了。
步驟七: 停止Redis實例
最簡單的方法是在啓動實例的session中,直接使用Control-C來將實例停止。
我們還可以用客戶端來停止服務,如可以用shutdown來停止Redis實例, 具體如下:
如何配置Redis?
如果是一個專業的DBA,那麼實例啓動時會加很多的參數以便使系統運行的非常穩定,這樣就可能會在啓動時在Redis後面加一個參數,以指定配置文件的路徑,就象mysql一樣的讀取啓動配置文件的方式來啓動數據庫。源碼編譯完成後,在redis-2.2.12目錄下有一個redis.conf文件,這個文件即是Redis的配置文件,用配置文件來啓動Redis的方法如下:
[6353] 05 Aug 19:36:45* Server started, Redis version 2.2.12
[6353] 05 Aug 19:36:45 # WARNING overcommit_memory issetto0! Background save may fail under low memory condition.Tofix this issue add'vm.overcommit_memory = 1' to /etc/sysctl.conf and then reboot or run the command 'sysctl vm.overcommit_memory=1' for this to take effect.
[6353] 05 Aug 19:36:45* The server isnow readyto accept connectionson port 6379
[6353] 05 Aug 19:36:45-0 clients connected (0 slaves),539540 bytes in use
Redis支持很多的參數,但都有默認值。
●daemonize:
默認情況下,redis不是在後臺運行的,如果需要在後臺運行,把該項的值更改爲yes。
●pidfile
當Redis在後臺運行的時候,Redis默認會把pid文件放在/var/run/redis.pid,你可以配置到其他地址。當運行多個redis服務時,需要指定不同的pid文件和端口。
●bind
指定Redis只接收來自於該IP地址的請求,如果不進行設置,那麼將處理所有請求,在生產環境中最好設置該項。
●port
監聽端口,默認爲6379。
●timeout
設置客戶端連接時的超時時間,單位爲秒。當客戶端在這段時間內沒有發出任何指令,那麼關閉該連接。
●loglevel
log等級分爲4級,debug, verbose, notice, 和warning。生產環境下一般開啓notice。
●logfile
配置log文件地址,默認使用標準輸出,即打印在命令行終端的窗口上。
●databases
設置數據庫的個數,可以使用SELECT 命令來切換數據庫。默認使用的數據庫是0。
●save
設置Redis進行數據庫鏡像的頻率。
if(在60秒之內有10000個keys發生變化時){
進行鏡像備份
}else if(在300秒之內有10個keys發生了變化){
進行鏡像備份
}else if(在900秒之內有1個keys發生了變化){
進行鏡像備份
}
●rdbcompression
在進行鏡像備份時,是否進行壓縮。
●dbfilename
鏡像備份文件的文件名。
●dir
數據庫鏡像備份的文件放置的路徑。這裏的路徑跟文件名要分開配置是因爲Redis在進行備份時,先會將當前數據庫的狀態寫入到一個臨時文件中,等備份完成時,再把該該臨時文件替換爲上面所指定的文件,而這裏的臨時文件和上面所配置的備份文件都會放在這個指定的路徑當中。
●slaveof
設置該數據庫爲其他數據庫的從數據庫。
●masterauth
當主數據庫連接需要密碼驗證時,在這裏指定。
●requirepass
設置客戶端連接後進行任何其他指定前需要使用的密碼。警告:因爲redis速度相當快,所以在一臺比較好的服務器下,一個外部的用戶可以在一秒鐘進行150K次的密碼嘗試,這意味着你需要指定非常非常強大的密碼來防止暴力破解。
●maxclients
限制同時連接的客戶數量。當連接數超過這個值時,redis將不再接收其他連接請求,客戶端嘗試連接時將收到error信息。
●maxmemory
設置redis能夠使用的最大內存。當內存滿了的時候,如果還接收到set命令,redis將先嚐試剔除設置過expire信息的key,而不管該key的過期時間還沒有到達。在刪除時,將按照過期時間進行刪除,最早將要被過期的key將最先被刪除。如果帶有expire信息的key都刪光了,那麼將返回錯誤。這樣,redis將不再接收寫請求,只接收get請求。maxmemory的設置比較適合於把redis當作於類似memcached的緩存來使用。
●appendonly
默認情況下,redis會在後臺異步的把數據庫鏡像備份到磁盤,但是該備份是非常耗時的,而且備份也不能很頻繁,如果發生諸如拉閘限電、拔插頭等狀況,那麼將造成比較大範圍的數據丟失。所以redis提供了另外一種更加高效的數據庫備份及災難恢復方式。開啓append only模式之後,redis會把所接收到的每一次寫操作請求都追加到appendonly.aof文件中,當redis重新啓動時,會從該文件恢復出之前的狀態。但是這樣會造成appendonly.aof文件過大,所以redis還支持了BGREWRITEAOF指令,對appendonly.aof進行重新整理。所以我認爲推薦生產環境下的做法爲關閉鏡像,開啓appendonly.aof,同時可以選擇在訪問較少的時間每天對appendonly.aof進行重寫一次。
●appendfsync
設置對appendonly.aof文件進行同步的頻率。always表示每次有寫操作都進行同步,everysec表示對寫操作進行累積,每秒同步一次。這個需要根據實際業務場景進行配置。
●vm-enabled
是否開啓虛擬內存支持。因爲redis是一個內存數據庫,而且當內存滿的時候,無法接收新的寫請求,所以在redis 2.0中,提供了虛擬內存的支持。但是需要注意的是,redis中,所有的key都會放在內存中,在內存不夠時,只會把value值放入交換區。這樣保證了雖然使用虛擬內存,但性能基本不受影響,同時,你需要注意的是你要把vm-max-memory設置到足夠來放下你的所有的key。
●vm-swap-file
設置虛擬內存的交換文件路徑。
●vm-max-memory
這裏設置開啓虛擬內存之後,redis將使用的最大物理內存的大小。默認爲0,redis將把他所有的能放到交換文件的都放到交換文件中,以儘量少的使用物理內存。在生產環境下,需要根據實際情況設置該值,最好不要使用默認的0。
●vm-page-size
設置虛擬內存的頁大小,如果你的value值比較大,比如說你要在value中放置博客、新聞之類的所有文章內容,就設大一點,如果要放置的都是很小的內容,那就設小一點。
●vm-pages
設置交換文件的總的page數量,需要注意的是,page table信息會放在物理內存中,每8個page就會佔據RAM中的1個byte。總的虛擬內存大小 = vm-page-size * vm-pages。
●vm-max-threads
設置VM IO同時使用的線程數量。因爲在進行內存交換時,對數據有編碼和解碼的過程,所以儘管IO設備在硬件上本上不能支持很多的併發讀寫,但是還是如果你所保存的vlaue值比較大,將該值設大一些,還是能夠提升性能的。
●glueoutputbuf
把小的輸出緩存放在一起,以便能夠在一個TCP packet中爲客戶端發送多個響應,具體原理和真實效果我不是很清楚。所以根據註釋,你不是很確定的時候就設置成yes。
●hash-max-zipmap-entries
在redis 2.0中引入了hash數據結構。當hash中包含超過指定元素個數並且最大的元素沒有超過臨界時,hash將以一種特殊的編碼方式(大大減少內存使用)來存儲,這裏可以設置這兩個臨界值。
●activerehashing
開啓之後,redis將在每100毫秒時使用1毫秒的CPU時間來對redis的hash表進行重新hash,可以降低內存的使用。當你的使用場景中,有非常嚴格的實時性需要,不能夠接受Redis時不時的對請求有2毫秒的延遲的話,把這項配置爲no。如果沒有這麼嚴格的實時性要求,可以設置爲yes,以便能夠儘可能快的釋放內存。
操作Redis數據庫
下面我們來簡單的操作一下數據庫。
1、插入數據
OK
設置一個key-value對。
2、查詢數據
"wwl"
取出key所對應的value。
3、刪除鍵值
刪除這個key及對應的value。
4、驗證鍵是否存在
(integer)0
其中0,代表此key不存在;1代表存在。
redis客戶端(C語言)
上面介紹了redis 安裝和簡單使用操作,下面,我們來介紹一下redis client端的編寫。
[root@localhost hiredis]# make
cc -c -std=c99 -pedantic -O3 -fPIC -Wall -W -Wwrite-strings -g -ggdb net.c
cc -c -std=c99 -pedantic -O3 -fPIC -Wall -W -Wwrite-strings -g -ggdb hiredis.c
cc -c -std=c99 -pedantic -O3 -fPIC -Wall -W -Wwrite-strings -g -ggdb sds.c
cc -c -std=c99 -pedantic -O3 -fPIC -Wall -W -Wwrite-strings -g -ggdb async.c
gcc -shared -Wl,-soname,libhiredis.so -o libhiredis.so net.o hiredis.o sds.o async.o
cc -c -std=c99 -pedantic -O3 -fPIC -Wall -W -Wwrite-strings -g -ggdb example.c
cc -o hiredis-example -std=c99 -pedantic -O3 -fPIC -Wall -W -Wwrite-strings -lm -pthread -g -ggdb -L. -Wl,-rpath,. -lhiredis example.o
cc -c -std=c99 -pedantic -O3 -fPIC -Wall -W -Wwrite-strings -g -ggdb test.c
cc -o hiredis-test -std=c99 -pedantic -O3 -fPIC -Wall -W -Wwrite-strings -lm -pthread -g -ggdb -L. -Wl,-rpath,. -lhiredis test.o
[root@localhost hiredis]# make install
ar rcs libhiredis.a net.o hiredis.o sds.o async.o
mkdir -p /usr/local/include/hiredis /usr/local/lib
cp -a hiredis.h async.h adapters /usr/local/include/hiredis
cp -a libhiredis.so libhiredis.a /usr/local/lib
這種方式安裝的安裝庫,沒有到達默認目錄,需要我們:
[root@localhost hiredis] cp libhiredis.so /usr/lib64 /usr/lib (若是32系統只需要運行 cp libhiredis.so /usr/lib)
[root@localhost hiredis]# gcc test.c -o test -lhiredis
[root@loaclhost hiredis]# ./test
#01 Format command without interpolation: PASSED
#02 Format command with %s string interpolation: PASSED
#03 Format command with %s and an empty string: PASSED
#04 Format command with %b string interpolation: PASSED
#05 Format command with %b and an empty string: PASSED
#06 Format command with literal %: PASSED
#07 Format command with printf-delegation (long long): PASSED
#08 Format command with printf-delegation (float): PASSED
#09 Format command with printf-delegation and extra interpolation: PASSED
#10 Format command with wrong printf format and extra interpolation: PASSED
#11 Format command by passing argc/argv without lengths: PASSED
#12 Format command by passing argc/argv with lengths: PASSED
#13 Returns error when host cannot be resolved: FAILED
#14 Returns error when the port is not open: PASSED
#15 Is able to deliver commands: PASSED
#16 Is a able to send commands verbatim: PASSED
#17 %s String interpolation works: PASSED
#18 %b String interpolation works: PASSED
#19 Binary reply length is correct: PASSED
#20 Can parse nil replies: PASSED
#21 Can parse integer replies: PASSED
#22 Can parse multi bulk replies: PASSED
#23 Can handle nested multi bulk replies: PASSED
#24 Returns I/O error when the connection is lost: PASSED
#25 Error handling in reply parser: PASSED
#26 Memory cleanup in reply parser: PASSED
#27 Set error on nested multi bulks with depth > 1: FAILED
#28 Works with NULL functions for reply: PASSED
#29 Works when a single newline (\r\n) covers two calls to feed: PASSED
#30 Throughput:
(1000x PING: 0.04s)
(1000x LRANGE with 500 elements: 0.16s)
*** 2 TESTS FAILED ***
不需要關注上面的兩個FAILED,當然你也可以查資料修補。
[root@localhost hiredis]# gcc example.c -o example -lhiredis
[root@localhost hiredis]# ./example
PING: PONG
SET: OK
SET (binary API): OK
GET foo: hello world
INCR counter: 3
INCR counter: 4
0) element-9
1) element-8
2) element-7
3) element-6
4) element-5
5) element-4
6) element-3
7) element-2
8) element-1
9) element-0
編程時,可以參照example.c 的實例即可
自己編寫的程序
在下面的代碼示例中,將給出兩種最爲常用的Redis命令操作方式,既普通調用方式和基於管線的調用方式。
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdarg.h>
#include <string.h>
#include <assert.h>
#include <hiredis/hiredis.h>
void doTest()
{
int timeout = 10000;
struct timeval tv;
tv.tv_sec = timeout / 1000;
tv.tv_usec = timeout * 1000;
//以帶有超時的方式鏈接Redis服務器,同時獲取與Redis連接的上下文對象。
//該對象將用於其後所有與Redis操作的函數。
redisContext* c = redisConnect((char*)"127.0.0.1", 6379);
if (c->err) {
redisFree(c);
return;
}
const char* command1 = "set stest1 value9";
redisReply* r = (redisReply*)redisCommand(c,command1);
//需要注意的是,如果返回的對象是NULL,則表示客戶端和服務器之間出現嚴重錯誤,必須重新鏈接。
//這裏只是舉例說明,簡便起見,後面的命令就不再做這樣的判斷了。
if (NULL == r) {
redisFree(c);
return;
}
//不同的Redis命令返回的數據類型不同,在獲取之前需要先判斷它的實際類型。
//至於各種命令的返回值信息,可以參考Redis的官方文檔,或者查看該系列博客的前幾篇
//有關Redis各種數據類型的博客。:)
//字符串類型的set命令的返回值的類型是REDIS_REPLY_STATUS,然後只有當返回信息是"OK"
//時,才表示該命令執行成功。後面的例子以此類推,就不再過多贅述了。
if (!(r->type == REDIS_REPLY_STATUS && strcasecmp(r->str,"OK") == 0)) {
printf("Failed to execute command[%s].\n",command1);
freeReplyObject(r);
redisFree(c);
return;
}
//由於後面重複使用該變量,所以需要提前釋放,否則內存泄漏。
freeReplyObject(r);
printf("Succeed to execute command[%s].\n",command1);
const char* command2 = "strlen stest1";
r = (redisReply*)redisCommand(c,command2);
if (r->type != REDIS_REPLY_INTEGER) {
printf("Failed to execute command[%s].\n",command2);
freeReplyObject(r);
redisFree(c);
return;
}
int length = r->integer;
freeReplyObject(r);
printf("The length of 'stest1' is %d.\n",length);
printf("Succeed to execute command[%s].\n",command2);
const char* command3 = "get stest1";
r = (redisReply*)redisCommand(c,command3);
if (r->type != REDIS_REPLY_STRING) {
printf("Failed to execute command[%s].\n",command3);
freeReplyObject(r);
redisFree(c);
return;
}
printf("The value of 'stest1' is %s.\n",r->str);
freeReplyObject(r);
printf("Succeed to execute command[%s].\n",command3);
const char* command4 = "get stest2";
r = (redisReply*)redisCommand(c,command4);
//這裏需要先說明一下,由於stest2鍵並不存在,因此Redis會返回空結果,這裏只是爲了演示。
if (r->type != REDIS_REPLY_NIL) {
printf("Failed to execute command[%s].\n",command4);
freeReplyObject(r);
redisFree(c);
return;
}
freeReplyObject(r);
printf("Succeed to execute command[%s].\n",command4);
const char* command5 = "mget stest1 stest2";
r = (redisReply*)redisCommand(c,command5);
//不論stest2存在與否,Redis都會給出結果,只是第二個值爲nil。
//由於有多個值返回,因爲返回應答的類型是數組類型。
if (r->type != REDIS_REPLY_ARRAY) {
printf("Failed to execute command[%s].\n",command5);
freeReplyObject(r);
redisFree(c);
//r->elements表示子元素的數量,不管請求的key是否存在,該值都等於請求是鍵的數量。
assert(2 == r->elements);
return;
}
int i;
for (i = 0; i < r->elements; ++i) {
redisReply* childReply = r->element[i];
//之前已經介紹過,get命令返回的數據類型是string。
//對於不存在key的返回值,其類型爲REDIS_REPLY_NIL。
if (childReply->type == REDIS_REPLY_STRING)
printf("The value is %s.\n",childReply->str);
}
//對於每一個子應答,無需使用者單獨釋放,只需釋放最外部的redisReply即可。
freeReplyObject(r);
printf("Succeed to execute command[%s].\n",command5);
printf("Begin to test pipeline.\n");
//該命令只是將待發送的命令寫入到上下文對象的輸出緩衝區中,直到調用後面的
//redisGetReply命令纔會批量將緩衝區中的命令寫出到Redis服務器。這樣可以
//有效的減少客戶端與服務器之間的同步等候時間,以及網絡IO引起的延遲。
//至於管線的具體性能優勢,可以考慮該系列博客中的管線主題。
/* if (REDIS_OK != redisAppendCommand(c,command1)
|| REDIS_OK != redisAppendCommand(c,command2)
|| REDIS_OK != redisAppendCommand(c,command3)
|| REDIS_OK != redisAppendCommand(c,command4)
|| REDIS_OK != redisAppendCommand(c,command5)) {
redisFree(c);
return;
}
*/
redisAppendCommand(c,command1);
redisAppendCommand(c,command2);
redisAppendCommand(c,command3);
redisAppendCommand(c,command4);
redisAppendCommand(c,command5);
redisReply* reply = NULL;
//對pipeline返回結果的處理方式,和前面代碼的處理方式完全一直,這裏就不再重複給出了。
if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
printf("Failed to execute command[%s] with Pipeline.\n",command1);
freeReplyObject(reply);
redisFree(c);
}
freeReplyObject(reply);
printf("Succeed to execute command[%s] with Pipeline.\n",command1);
if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
printf("Failed to execute command[%s] with Pipeline.\n",command2);
freeReplyObject(reply);
redisFree(c);
}
freeReplyObject(reply);
printf("Succeed to execute command[%s] with Pipeline.\n",command2);
if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
printf("Failed to execute command[%s] with Pipeline.\n",command3);
freeReplyObject(reply);
redisFree(c);
}
freeReplyObject(reply);
printf("Succeed to execute command[%s] with Pipeline.\n",command3);
if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
printf("Failed to execute command[%s] with Pipeline.\n",command4);
freeReplyObject(reply);
redisFree(c);
}
freeReplyObject(reply);
printf("Succeed to execute command[%s] with Pipeline.\n",command4);
if (REDIS_OK != redisGetReply(c,(void**)&reply)) {
printf("Failed to execute command[%s] with Pipeline.\n",command5);
freeReplyObject(reply);
redisFree(c);
}
freeReplyObject(reply);
printf("Succeed to execute command[%s] with Pipeline.\n",command5);
//由於所有通過pipeline提交的命令結果均已爲返回,如果此時繼續調用redisGetReply,
//將會導致該函數阻塞並掛起當前線程,直到有新的通過管線提交的命令結果返回。
//最後不要忘記在退出前釋放當前連接的上下文對象。
redisFree(c);
return;
}
int main()
{
doTest();
return 0;
}
述文件命名爲:mytest.c
[root@localhost hj]# ./mytest
Succeed to execute command[set stest1 value9].
The length of 'stest1' is 6.
Succeed to execute command[strlen stest1].
The value of 'stest1' is value9.
Succeed to execute command[get stest1].
Succeed to execute command[get stest2].
The value is value9.
Succeed to execute command[mget stest1 stest2].
Begin to test pipeline.
Succeed to execute command[set stest1 value9] with Pipeline.
Succeed to execute command[strlen stest1] with Pipeline.
Succeed to execute command[get stest1] with Pipeline.
Succeed to execute command[get stest2] with Pipeline.
Succeed to execute command[mget stest1 stest2] with Pipeline.
參考網址:
http://tech.it168.com/a2011/0830/1239/000001239923_all.shtml
http://www.cnblogs.com/stephen-liu74/category/354125.html