Redis筆記(4)redis五大資料型別1----string(字串)

海碼cc發表於2020-12-04

string(字串)

string型別使用場景

  • 計數器
  • 統計數量
  • 物件儲存
append key value    字串追加,返回字串長度
strlen key      	返回字串長度
127.0.0.1:6379> set key1 abc  //設定
OK
127.0.0.1:6379> get key1
"abc"
127.0.0.1:6379> append key1 ddd
(integer) 6
127.0.0.1:6379> get key1
"abcddd"
127.0.0.1:6379> strlen key1
(integer) 6
incr key     自增1
decr key     自減1
incrby    	 步長增加
decrby       步長減少
127.0.0.1:6379> set num 0
OK
127.0.0.1:6379> incr num
(integer) 1
127.0.0.1:6379> incr num
(integer) 2
127.0.0.1:6379> get num
"2"
127.0.0.1:6379> decr num
(integer) 1
127.0.0.1:6379> incrby num 10
(integer) 11
127.0.0.1:6379> decrby num 5
(integer) 6
GETRANGE  key start end     字串擷取,下標開始和結束,-1相當於get key
SETRANGE key offset value   字串替換,開始的下標,替換的字串
127.0.0.1:6379> get key1
"abcddd"
127.0.0.1:6379> GETRANGE key1 0 2
"abc"
127.0.0.1:6379> GETRANGE key1 0 -1
"abcddd"
127.0.0.1:6379> SETRANGE key1 1 xx
(integer) 6
127.0.0.1:6379> get key1
"axxddd"
setex key seconds value   設定一個值多少秒過期
setnx key value           如果key不存在就設定,存在會設定失敗
127.0.0.1:6379> setex key2 30 hello
OK
127.0.0.1:6379> ttl key2  //檢視剩餘時間
(integer) 25
127.0.0.1:6379> setnx key3 redis
(integer) 1
127.0.0.1:6379> get key3
"redis"
127.0.0.1:6379> setnx key3 mongodb
(integer) 0
127.0.0.1:6379> get key3
"redis"
127.0.0.1:6379> 
mset key value [key ···]   批量設定
mget key [key ···]    	   批量獲取
msetnx key value [key ···] 批量檢測設定,一個失敗即全部失敗
127.0.0.1:6379> mset k1 v1 k2 v2 k3 v3
OK
127.0.0.1:6379> keys * 
1) "k1"
2) "k3"
3) "k2"
127.0.0.1:6379> mget k1 k2 k3
1) "v1"
2) "v2"
3) "v3"
127.0.0.1:6379> msetnx k1 123 k4 456
(integer) 0
127.0.0.1:6379> keys *
1) "k1"
2) "k3"
3) "k2"
127.0.0.1:6379> mset user:1:name zhangsan user:1:age 16 //可用作儲存物件
OK
127.0.0.1:6379> mget user:1:name user:1:age
1) "zhangsan"
2) "16"
getset key value   先拿值,在設值
127.0.0.1:6379> keys *
(empty array)
127.0.0.1:6379> getset key1 123
(nil)
127.0.0.1:6379> get key1
"123"
127.0.0.1:6379> getset key1 456
"123"
127.0.0.1:6379> get key1
"456"

相關文章