2 字符串String

2.1 简单动态字符串

Redis没有直接使用C语言传统的字符串表示,而是自己构建了一种名为简单动态字符串(SDS)的抽象类型,并将SDS用作Redis的默认字符串表示。在Redis的数据库里面,包含字符串的键值对在底层都是由SDS实现的。

例如创建命令:

> set msg “hello world” 
OK

Redis将在数据库中创建一个新的键值对,其中:

  • 键值对的键是一个字符串对象,对象的底层实现是一个保存着字符串“msg”的SDS。
  • 键值对的值也是一个字符串对象,对象的底层实现是一个保存着字符串“hello world”的SDS。

我们来看一下SDS的定义:

struct sdshdr{

//记录buf数组中已使用字节的数量
//等于SDS所保存字符串的长度
int len;

//记录buf数组未使用字节的数量
int free;

//字节数组
char buf[];

};

                                                                                                                                                           

2.2String常用命令

> set hello world //设置键为hello,值为world
OK

> get hello         //获取键为hello的值
"world"

> getset hello xiaolin //获取键为hello的值,并重新定义值为xiaolin
"world"
> get hello         //重新获取键为hello的值
"xiaolin"            //此时已经变成了xiaolin

> del hello        //删除
(integer) 1
> get hello
(nil)

>incr num      //对一个值做加1操作,若该值之前没有定义,则先初始化为0,之后加1
(integer) 1
>get num
"1"
>incr hello    //若被增的值不是字符串,则会报错
(error) ERR value is not an integer or out of range

>decr num1  //减一操作,若先初始化为0,则会得到-1
(integer) -1

>incrby num2  5  // 可以指定要增加的值
(integer) 5

>decrby num2  3  // 可以指定要减小的值
(integer) 2

>set hello xiaolin
OK
>append hello nihao   //连接字符串操作
(integer) 12
>get hello
"xiaolinnihao"

猜你喜欢

转载自www.cnblogs.com/xlzfdddd/p/10343974.html
今日推荐