R和redis的聯合使用
redis作為強大的Key-Value服務,如何和R進行結合,這里做一些簡單的記錄
redis安裝
redis安裝非常簡單,幾乎不用管什么依賴關系:
wget http://download.redis.io/releases/redis-x.x.x.tar.gz
tar xzf redis-x.x.x.tar.gz
cd redis-x.x.x
make
make-test
sudo make install
官網 上有足夠的資料介紹。安裝完畢后,生成redis-server、redis-cli、redis-benchmark、redis-stat。
- redis-server:服務啟動程序
- redis-cli:Redis命令行操作工具
- redis-benchmark:Redis性能測試工具
- redis-stat:Redis狀態檢測工具
在Terminal中執行 redis-server 即可啟動服務。
簡單的試用一下redis,打開新的Terminal,執行redis-cli進入命令行:
sunbjt@ubuntu:~$ redis-cli 127.0.0.1:6379> set y 10 OK 127.0.0.1:6379> get y "10" 127.0.0.1:6379> EXPIRE y 10 (integer) 1 127.0.0.1:6379> get y "10" 127.0.0.1:6379> get y (nil)
上面的意思是設置了Key y的Value 為10,并獲取;設置過期時間10秒,看y的值有,10秒后y為空。
使用rredis
在R中直接執行
install.packages('rredis')
即可安裝完畢。這個包適配性很強,在所有的R環境中均可使用,包括經常出問題的Microsoft WIndows。
假定我們在client端已經啟動了R
> library(rredis)
> redisConnect('192.168.226.128') # ip為redis服務地址
> x <- rnorm(5)
> x
[1] -0.8542932 0.2279106 -2.6222566 -0.1386406 -1.2380619
> redisSet('x', x)
[1] "OK"
> redisGet('x')
[1] -0.8542932 0.2279106 -2.6222566 -0.1386406 -1.2380619
多變量傳輸:
redisMSet(list(x=pi,y=runif(5),z=sqrt(2)))
redisMGet(c("x","y","z"))
redisExpire("z",1)
Sys.sleep(1)
redisGet("z")
可能在redis-cli上看R傳輸過去的都是亂碼,解決辦法就是 encode 一下
redisSet('z', charToRaw('10'))
以及更加底層的,可以使用任意有效redis函數的R函數:
redisCmd('get', 'x')
rredis pipelining
redis的wiki上有以下描述:
A Request/Response server can be implemented so that it is able to process new requests even if the client didn't already read the old responses. This way it is possible to send multiple commands to the server without waiting for the replies at all, and nally read the replies in a single step.
因此,只需要在rredis環境下首先聲明 redisSetPipeline(TRUE),而后所有指令傳遞過去之后,并不直接返回到R,而是緩存在redis服務端,再通過一個顯式的函數(redisGetResponse)獲得執行。
redisSetPipeline(TRUE)
t1 <- proc.time()
for(j in 1:100) redisSet(paste('x', j, sep = ''), charToRaw(as.character(j)))
resp <- redisGetResponse()
proc.time() - t1
redisConnect('192.168.226.128') # 連接被關閉,需重新打開redis連接
redisGet('x1')
redis這么牛掰的KV服務器能做的事情肯定不止這么多,以上僅僅是一個簡單的介紹。如果有合適的小型項目,再看看能不能做出點有意思的東西來。