redis 資料庫操作命令

2021-08-22 15:19:08 字數 3232 閱讀 6133

redis的資料庫操作命令包括select命令和move命令.

redis select命令

redis select命令的格式為select index, 其含義是為當前客戶端選擇使用哪乙個全域性資料庫.redis伺服器預設有16個全域性資料庫,當新客戶端連線到redis伺服器時,使用的是第乙個(索引為0)全域性資料庫,更新資料和查詢資料都是在其選擇的資料庫中進行.select命令可以讓客戶端在全域性資料庫中切換.telnet的模擬操作為:

telnet 10.7

.7.132

6379

trying 10.7

.7.132

...connected to 10.7

.7.132.

escape character is '^]'.

select 1

+ok

redis select命令對應的處理函式為selectcommand,其實現為(redis.c):

1427

static

void selectcommand(redisclient *c) else

1435 }

首先將資料庫索引轉換為整數,呼叫函式selectdb為該客戶端選擇索引指定的全域性資料庫,如果索引值無效,向客戶端傳送錯誤提示字串,否則,傳送操作成功字串.函式selectdb的實現為(redis.c):

926

static

int selectdb(redisclient *c, int

id)

需要注意的是select命令是和客戶端物件繫結的,它只是切換當前客戶端的資料庫,對於其他已經連線到redis伺服器的客戶端並沒有影響,對於新連線到redis伺服器的客戶端,預設仍然選擇的是第乙個全域性資料庫.

redis move命令

redis move的格式為move key index,其含義是將當前資料庫中包含指定key的節點遷移到索引指定的目標資料庫.telnet的模擬操作為:

telnet 10.7

.7.132

6379

trying 10.7

.7.132

...connected to 10.7

.7.132.

escape character is '^]'.

set mykey 7

myvalue

+okmove mykey 1

+okget mykey

nil

redis move命令對應的處理函式為movecommand, 其實現為(redis.c):

1578 dictentry *de;

1579 sds *key;

1580 robj *o;

1581 dict *src, *dst;

1582

1583 /* obtain source and target db pointers */

1584 src = c->dict;

1585

if (selectdb(c,atoi(c->argv[2])) == redis_err)

1589 dst = c->dict;

1590 c->dict = src;

1591

1592 /* if the user is moving using as target the same

1593 * db as

the source db it

is probably an error. */

1594

if (src == dst)

1598

1599 /* check if

the element exists and

geta reference */

1600 de = dictfind(c->dict,c->argv[1]);

1601

if (!de)

1605

1606 /* try to add the element to

the target db */

1607 key = dictgetentrykey(de);

1608 o = dictgetentryval(de);

1609

if (dictadd(dst,key,o) == dict_err)

1613

1614 /* ok! key moved, free the entry in

the source db */

1615 dictdeletenofree(src,c->argv[1]);

1616 server.dirty++;

1617 addreply(c,shared.ok);

1618 }

line1583:1590獲得客戶端當前連線的資料庫和目標索引對應的資料庫.line1592:1597如果目標資料庫和客戶端當前連線資料庫相同,則向客戶端返回錯誤提示字串.line1599:1604檢查包含指定key的雜湊節點在當前資料庫中是否存在,如果不存在,向客戶端返回錯誤提示字串.line1606:1612將該雜湊節點儲存在目標資料庫中,這裡只是把節點的key進行雜湊對映,獲得在目標資料庫中的bucket索引,然後把該節點插入到目標資料庫的bucket索引的鍊錶中,並不涉及到記憶體拷貝,全是指標操作.line1614:1615呼叫函式dictdeletenofree在當前資料庫中(節點被移除的資料庫)刪除該節點,該函式的實現為(dict.c):

252

int dictdeletenofree(dict *ht, const

void *key)

呼叫函式dictgenericdelete在資料庫中刪除該雜湊節點,注意傳入的第三個引數為1,即不釋放該雜湊節點中key和value,因該key和value仍然儲存於另外乙個資料庫中.

回到函式movecommand, line1616更新資料庫更新次數.最後向客戶端傳送操作成功提示字串.

redis資料庫簡單的命令操作

redis是key value的資料結構,每條資料都是 個鍵值對 鍵的型別是字串 值的型別分為五種 1 字串string 2 雜湊hash 3 列表list 4 集合set 5 有序集合zset 1 string型別 字串型別是redis中最為基礎的資料儲存型別,它在redis中是二進位制安全的,這...

操作redis資料庫的基礎命令

啟動資料庫 服務端 redis server 啟動資料庫客戶端 redis cli 選擇要操作的資料庫 select 0 選擇資料庫0redis資料庫的型別有string,list,hash string型別資料的操作 set key values 元素key不存在則新新增,存在則修改key的值為v...

Redis資料庫操作

1.終端連線redis的命令redis cli h ip address linux系統下可通過ifconfig檢視ip address資訊2.在連線後選擇redis庫select number number是redis庫的編號3.檢視redis庫的keys資訊keys 4.減少redis庫連線次數...