日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 人文社科 > 生活经验 >内容正文

生活经验

Redis 笔记(03)— string类型(设置key、获取key、设置过期时间、批量设置获取key、对key进行加减、对key值进行追加、获取value子串)

發布時間:2023/11/28 生活经验 22 豆豆

字符串 stringRedis 最簡單的數據結構。Redis 所有的數據結構都是以唯一的 key 字符串作為名稱,然后通過這個唯一 key 值來獲取相應的 value 數據。不同類型的數據結構的差異就在于 value 的結構不一樣。

Redis 的字符串是動態字符串,是可以修改的字符串,內部結構實現上類似于 JavaArrayList,采用預分配冗余空間的方式來減少內存的頻繁分配,

如圖中所示,內部為當前字符串實際分配的空間 capacity 一般要高于實際字符串長度 len。當字符串長度小于 1M 時,擴容都是加倍現有的空間,如果超過 1M,擴容時一次只會多擴 1M 的空間。需要注意的是字符串最大長度為 512M。

1. string 類型相關命令

命令說明
set key value設置key對應值為string類型的value
setex key seconds value設置key對應值為string類型的value,增加到期時間
mset key1 value1…keyN valueN一次設置多個key的值
mget key1 …keyN一次獲取多個key的值
incr key對key的值++操作,并返回新值
decr key同上,但是做的是–操作
incrby key integer同incr,加指定值
decrby key integer同desr,減指定值
incrbyfloat key increment對key的值增加一個浮點數
append key value給指定key的字符串追加value
substr key start end返回截取過的key的字符串值
getrange key start end獲取存儲在key上的值的一個子字符串
setrange key offset value將從start偏移量開始的子串設置指定的值

2. 使用示例

  • 鍵值對

可以對 key 設置過期時間,到點自動刪除,這個功能常用來控制緩存的失效時間。

127.0.0.1:6379> ping
PONG
127.0.0.1:6379> keys *
(empty list or set)
127.0.0.1:6379> set a "this is a string type"
OK
127.0.0.1:6379> setex tmp 5 "tmp"
OK
127.0.0.1:6379> ttl tmp
(integer) 1
127.0.0.1:6379> ttl tmp
(integer) -2
127.0.0.1:6379> ttl tmp
(integer) -2
127.0.0.1:6379> keys *
1) "a"
  • 批量鍵值對,節省網絡耗時開銷
127.0.0.1:6379> mset b "this is second string" c "third string" d "fourth string"
OK
127.0.0.1:6379> keys *
1) "c"
2) "b"
3) "a"
4) "d"
127.0.0.1:6379> mget a b c d 
1) "this is a string type"
2) "this is second string"
3) "third string"
4) "fourth string"
  • 計數
    如果 value 值是一個整數,還可以對它進行自增操作。自增是有范圍的,它的范圍是 signed long 的最大最小值,超過了這個值,Redis 會報錯。
127.0.0.1:6379> incr a
(error) ERR value is not an integer or out of range
127.0.0.1:6379> set num 1
OK
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> get num
"1"
127.0.0.1:6379> incrby num 10
(integer) 11
127.0.0.1:6379> get num
"11"
127.0.0.1:6379> decrby num 2
(integer) 9
127.0.0.1:6379> get num
"9"
127.0.0.1:6379> incrbyfloat num 0.2
"9.2"
127.0.0.1:6379> get num
"9.2"
127.0.0.1:6379> get a
"this is a string type"
127.0.0.1:6379> append a ", first string"
(integer) 35
127.0.0.1:6379> get a
"this is a string type, first string"
127.0.0.1:6379> substr a 23 -1
"first string"
127.0.0.1:6379> getrange a 23 -1
"first string"
127.0.0.1:6379> get d
"fourth string"
127.0.0.1:6379> setrange d 7 "china"
(integer) 13
127.0.0.1:6379> get d
"fourth chinag"
127.0.0.1:6379> setrange d 7 "chinese"
(integer) 14
127.0.0.1:6379> get d
"fourth chinese"
127.0.0.1:6379> 

總結

以上是生活随笔為你收集整理的Redis 笔记(03)— string类型(设置key、获取key、设置过期时间、批量设置获取key、对key进行加减、对key值进行追加、获取value子串)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。