redis series --Redis data type (c)

     Redis stored data, the value for type are the following key-value store by:

  • String
  • Hash type
  • List
  • Set
  • SortedSet(zset)

Description: In the redis command statement, commands are case insensitive, while the key is not case-insensitive.

A, String type

1, the command

  • Assignment

Syntax: SET key value

127.0.0.1:6379> set test 123
OK
  • The value

Syntax: GET key

127.0.0.1:6379> get test
"123“
  • Set / Get a plurality of keys

grammar:

MSET key value [key value …]

MGET key [key …]

127.0.0.1:6379> mset k1 v1 k2 v2 k3 v3
OK
127.0.0.1:6379> get k1
"v1"
127.0.0.1:6379> mget k1 k3
1) "v1"
2) "v3"
  • And assign values

Syntax: GETSET key value

127.0.0.1:6379> getset s2 222
"111"
127.0.0.1:6379> get s2
"222"
  • delete

Syntax: DEL key

127.0.0.1:6379> del test
(integer) 1
  • Incrementing number

        When the string is stored integer, Redis provides a practical command INCR, its role is to make the current key value is incremented, and returns the value after incrementing.

Syntax: INCR key

127.0.0.1:6379> incr num
(integer) 1
127.0.0.1:6379> incr num
(integer) 2
127.0.0.1:6379> incr num
(integer) 3
  • Increase specified by the integer

Syntax: INCRBY key increment

127.0.0.1:6379> incrby num 2
(integer) 5
127.0.0.1:6379> incrby num 2
(integer) 7
127.0.0.1:6379> incrby num 2
(integer) 9
  • Decreasing value

Syntax: DECR key

127.0.0.1:6379> decr num
(integer) 9
127.0.0.1:6379> decr num
(integer) 8
  • Reduction specified integer

Syntax: DECRBY key decrement

127.0.0.1:6379> decr num
(integer) 6
127.0.0.1:6379> decr num
(integer) 5
127.0.0.1:6379> decrby num 3
(integer) 2
127.0.0.1:6379> decrby num 3
(integer) -1
  • Added value to the tail

        APPEND key role is to append a value. The value of the key does not exist If key is value, which is equivalent to SET key value. The return value is the total length of the string after appended. 

Syntax: APPEND key value

127.0.0.1:6379> set str hello
OK
127.0.0.1:6379> append str " world!"
(integer) 12
127.0.0.1:6379> get str
"hello world!"
  • Get string length 

        STRLEN command returns the length of the key, if the key does not exist is returned to zero.

Syntax: STRLEN key

127.0.0.1:6379> strlen str
(integer) 0
127.0.0.1:6379> set str hello
OK
127.0.0.1:6379> strlen str
(integer) 5

2, application

  • Auto-increment primary keys

        Product number, order number using string of incremental generation digital features.

For example: Define Product Number key: items: id

192.168.101.3:7003> INCR items:id
(integer) 2
192.168.101.3:7003> INCR items:id
(integer) 3

Two, Hash type

1, the problem description

        Suppose User object stored in JSON serialized form to Redis in, User object has id, username, password, age, name and other attribute, stored as follows: save, update; User object à json (string) à redis if just update age on business property, other properties do not update how should I do? If you are still using the top of the transmission method, a waste of resources when dealing with, say below the hash can be a good solution to this problem.

2, redis hash introduction

        hash called hash type, which provides a mapping of fields and field values. Field value is a string type only, does not support other types of hash type, set type and the like. as follows:

 

3, command

1. Assignment

        HSET command does not distinguish between insert and update operations, when the insertion command returns an operation HSET, returns 0 when an update operation.

  • You can only set a field value

Syntax: HSET key field value

127.0.0.1:6379> hset user username zhangsan
(integer) 1
  • A plurality of field values ​​may be provided

语法:HMSET key field value [field value ...]

127.0.0.1:6379> hmset user age 20 username lisi
OK
  • When the field is not present assignment, HSET similar, except that if the field is present, the command does not perform any operation

Syntax: HSETNX key field value

127.0.0.1:6379> hsetnx user age 30 --如果user中没有age字段则设置age值为30,否则不做任何操作
(integer) 0

2. Value

  • You can only get a field value

Syntax: HGET key field

127.0.0.1:6379> hget user username
"zhangsan“
  • A plurality of field values ​​may be obtained

Syntax: HMGET key field [field ...]

127.0.0.1:6379> hmget user age username
1) "20"
2) "lisi"
  • Get all field values

Syntax: HGETALL key

127.0.0.1:6379> hgetall user
1) "age"
2) "20"
3) "username"
4) "lisi"

3. Delete field

        Can delete one or more fields, the return value is the number of fields deleted 

语法:HDEL key field [field ...]

127.0.0.1:6379> hdel user age
(integer) 1
127.0.0.1:6379> hdel user age name
(integer) 0
127.0.0.1:6379> hdel user age username
(integer) 1

4. Increase the numbers 

语法:HINCRBY key field increment

127.0.0.1:6379> hincrby user age 2 --将用户的年龄加2
(integer) 22
127.0.0.1:6379> hget user age --获取用户的年龄
"22“

5. Determine whether the field is present

语法:HEXISTS key field

127.0.0.1:6379> hexists user age 查看user中是否有age字段
(integer) 1
127.0.0.1:6379> hexists user name 查看user中是否有name字段
(integer) 0

6. Get the only field names or field values

grammar:

HKEYS key

whales key

127.0.0.1:6379> hmset user age 20 name lisi
OK
127.0.0.1:6379> hkeys user
1) "age"
2) "name"
127.0.0.1:6379> hvals user
1) "20"
2) "lisi"

7. Gets the number of fields 

Syntax: HLEN key

127.0.0.1:6379> hlen user
(integer) 2

4, Application

  • Store product information

Example: [commodity trade field id, product name, product description, product inventory, merchandise praise]. Merchandise information defined key, the key information 1001 Redis product in the range: [items: 1001]

  • Store product information
192.168.101.3:7003> HMSET items:1001 id 3 name apple price 999.9
OK
  • Obtain product information
192.168.101.3:7003> HGET items:1001 id
"3"
192.168.101.3:7003> HGETALL items:1001
1) "id"
2) "3"
3) "name"
4) "apple"
5) "price"
6) "999.9"

Three, List type

1, the difference between ArrayList and LinkedList

       ArrayList using arrays store data, according to the index to query the data so fast speed, but need to be designed to add or remove elements shift operation, so more slowly. 

       LinkedList stored data using a doubly linked list, each element before and after the record pointer elements, it is inserted, deleted data just before and after the change of a pointer to an element can be, very fast. You then need to start from scratch when the index by index query elements, it is slower, but after the first few elements or if the query several elements faster.

 

2, redis list Introduction

       List Type (list) can store an ordered list of strings, common operation is to add elements to the ends of the list, or to obtain a fragment of a list. Internal list type using a doubly linked list (double linked list) implemented, so adding to the ends of the list elements is the time complexity of 0 (1), at both ends of the elements closer to obtain faster. This means that even if there is a list of tens of millions of elements, obtaining 10 records the head or tail is also very fast.

3, command

1. add elements to the ends of the list

  • Add elements to the left of the list 

Syntax: LPUSH key value [value ...]

127.0.0.1:6379> lpush list:1 1 2 3
(integer) 3
  • Add elements to the list on the right

Syntax: RPUSH key value [value ...]

127.0.0.1:6379> rpush list:1 4 5 6
(integer) 3

2. View the list 

        LRANGE command is one of a list of the most commonly used type of command to get a list of segments, the return start, all the elements between the stop (containing the element ends), the index starts from 0. Indices may be negative, such as: "- 1" represents an element of the final edge.

Syntax: LRANGE key start stop

127.0.0.1:6379> lrange list:1 0 2
1) "2"
2) "1"
3) "4"

3. pop elements from both ends of the list 

       LPOP command pops up a list of elements from the left, two steps will be: The first step is to list the elements removed from the list on the left; the second step is the return value of the element is removed.

grammar:

LPOP key

RPOP key

127.0.0.1:6379> lpop list:1
"3“
127.0.0.1:6379> rpop list:1
"6“

4. Get the number of elements in this list 

Syntax: LLEN key

127.0.0.1:6379> llen list:1
(integer) 2

5. Delete the value specified in the list 

        LREM command to delete the list of the first count value is value elements, returns the number of elements that are actually deleted. Depending on the count value of the implementation of the order will be different: 

  • When the count> 0 Shi, LREM starts deleting from the list on the left. 
  • When the count <0 Shi, LREM removed from the list will start behind. 
  • When the count = 0, LREM remove all elements of the value of value. 

Syntax: LREM key count value

6. Get / Set element values ​​specified index 

       Obtain the specified index element values

Syntax: LINDEX key index

127.0.0.1:6379> lindex l:list 2
"1"

7. Set element value of the specified index

Syntax: LSET key index value

127.0.0.1:6379> lset l:list 2 2
OK
127.0.0.1:6379> lrange l:list 0 -1
1) "6"
2) "5"
3) "2"
4) "2"

8. The reservation list only the specified segment

        Consistent with the specified range and LRANGE 

Syntax: LTRIM key start stop

127.0.0.1:6379> lrange l:list 0 -1
1) "6"
2) "5"
3) "0"
4) "2"
127.0.0.1:6379> ltrim l:list 0 2
OK
127.0.0.1:6379> lrange l:list 0 -1
1) "6"
2) "5"
3) "0"

9. to insert elements into the list 

        The command will first look left to right pivot element value in the list, and in accordance with the second parameter is determined to BEFORE AFTER or inserted before or after the value of the element. 

语法:LINSERT key BEFORE|AFTER pivot value

127.0.0.1:6379> lrange list 0 -1
1) "3"
2) "2"
3) "1"
127.0.0.1:6379> linsert list after 3 4
(integer) 4
127.0.0.1:6379> lrange list 0 -1
1) "3"
2) "4"
3) "2"
4) "1"

10. The element from one list to another list 

Syntax: RPOPLPUSH source destination

127.0.0.1:6379> rpoplpush list newlist
"1"
127.0.0.1:6379> lrange newlist 0 -1
1) "1"
127.0.0.1:6379> lrange list 0 -1
1) "3"
2) "4"
3) "2"

4, Application

  • Reviews List

Ideas:

Create a list of product reviews in the Redis

Users to post product reviews, will be converted into json review information stored in the list.

User comments page query list, remove the json data to show a page from the redis.

Product Reviews defined list of key: Product No. 1001 Product Reviews [key items: comment: 1001]

192.168.101.3:7001> LPUSH items:comment:1001 '{"id":1,"name":"商品不错,很好!!","date":1430295077289}'

Four, Set types

1, redis set introduced

        Data set and no order is not repeated. A collection of types and list types of comparison:

       Collection types are commonly added to the collection operation or deleting elements, determines whether there is an element, etc., since the internal collection type of Redis use hash table is empty implemented, all the time complexity of these operations is 0 (1 ). Redis also provides a plurality of intersection between the set and the set, the set difference operation.

2, the command

1. Add / Remove elements 

Syntax: SADD key member [member ...]

127.0.0.1:6379> sadd set a b c
(integer) 3
127.0.0.1:6379> sadd set a
(integer) 0

Syntax: SREM key member [member ...]

127.0.0.1:6379> srem set c d
(integer) 1

2. Get all the elements in the collection 

Syntax: SMEMBERS key

127.0.0.1:6379> smembers set
1) "b"
2) "a”

3. determining whether the element in the collection

Syntax: SISMEMBER key member

127.0.0.1:6379> sismember set a
(integer) 1
127.0.0.1:6379> sismember set h
(integer) 0

3, the operation command

AB 1. difference set operation set

        It belongs to the set of elements A and B does not belong to the configuration. 

 

 Syntax: SDIFF key [key ...]

127.0.0.1:6379> sadd setA 1 2 3
(integer) 3
127.0.0.1:6379> sadd setB 2 3 4
(integer) 3
127.0.0.1:6379> sdiff setA setB
1) "1"
127.0.0.1:6379> sdiff setB setA
1) "4"

2. The set intersection operator A ∩ B

        A collection of elements belonging to the B and belongs to the configuration. 

 

Syntax: SINTER key [key ...]

127.0.0.1:6379> sinter setA setB
1) "2"
2) "3"

3. A ∪ B and set operation set

        A part of or belonging to a set of elements consisting of B

 

 Syntax: SUNION key [key ...]

127.0.0.1:6379> sunion setA setB
1) "1"
2) "2"
3) "3"
4) "4"

4, the number of elements in a set to obtain 

Syntax: SCARD key

127.0.0.1:6379> smembers setA
1) "1"
2) "2"
3) "3"
127.0.0.1:6379> scard setA
(integer) 3

5, a pop-up element from the collection

Syntax: SPOP key

127.0.0.1:6379> spop setA
"1“

Note: Since sets are unordered, all SPOP command randomly selected from a set of pop-up elements

Five, SortedSet type zset

1, redis sorted set introduced

       On the basis of the collection type, indexed collections for the collection of each element is associated with a score, which allows us not only to complete the insertion, deletion and determine whether there are elements in the collection, but also to the highest or lowest score before N elements, obtaining scores and other elements related to operation within a specified range of scores. In some respects ordered collection and list types is somewhat similar.

  • Both are ordered.
  • Both can get a range of elements.

However, the two are very different: 

  • List type is implemented by a linked list, obtaining data speeds close to both ends of the fast, and when the element increases, the speed will slow down access to the intermediate data. 
  • An ordered collection type implemented using a hash table, even if the reading of all the data in the middle portion quickly. 
  • The list can not simply adjust the position of an element, but can be ordered set (by changing the scores achieved) 
  • Ordered collection of more than a list of types of memory consumption. 

2, the command

1. Increase elements

       And adding an element to the score of the ordered set of elements if the element already exists will replace the old scores with the new score. The return value is newly added to the number of elements in the set, it does not contain the previously existing elements. 

语法:ZADD key score member [score member ...]

127.0.0.1:6379> zadd scoreboard 80 zhangsan 89 lisi 94 wangwu
(integer) 3
127.0.0.1:6379> zadd scoreboard 97 lisi
(integer) 0

2. Get scores element 

Syntax: ZSCORE key member

127.0.0.1:6379> zscore scoreboard lisi
"97"

3. Removing elements

        Remove the key ordered set of one or more members, there is no member will be ignored. When ordered set but not the type of key exists, it returns an error.

Syntax: ZREM key member [member ...]

127.0.0.1:6379> zrem scoreboard lisi
(integer) 1

4. get ranked list of elements in a range of

  • Element scores according to the ascending order of the index from start to return all of the elements between the stop (containing the element ends)

语法:ZRANGE key start stop [WITHSCORES]

127.0.0.1:6379> zrange scoreboard 0 2
1) "zhangsan"
2) "wangwu"
3) "lisi“
  • It returns the index of the element according to the score decreasing order from start to all of the elements between the stop (containing the element ends)

语法:ZREVRANGE key start stop [WITHSCORES]

127.0.0.1:6379> zrevrange scoreboard 0 2
1) " lisi "
2) "wangwu"
3) " zhangsan “
  • If you need to receive a score of elements can add WITHSCORES parameter in the command tail 
127.0.0.1:6379> zrange scoreboard 0 1 WITHSCORES
1) "zhangsan"
2) "80"
3) "wangwu"
4) "94"

The obtained element specified fraction range

语法:ZRANGEBYSCORE key min max [WITHSCORES] [LIMIT offset count]

127.0.0.1:6379> ZRANGEBYSCORE scoreboard 90 97 WITHSCORES
1) "wangwu"
2) "94"
3) "lisi"
4) "97"
127.0.0.1:6379> ZRANGEBYSCORE scoreboard 70 100 limit 1 2
1) "wangwu"
2) "lisi"

6. increase the score of an element

        The return value is a fraction of the changed 

Syntax: ZINCRBY key increment member

127.0.0.1:6379> ZINCRBY scoreboard 4 lisi
"101“

7. The number of elements in the set obtained 

Syntax: ZCARD key

127.0.0.1:6379> ZCARD scoreboard
(integer) 3

8. The number of elements is obtained within the specified range of scores 

Syntax: ZCOUNT key min max

127.0.0.1:6379> ZCOUNT scoreboard 80 90
(integer) 1

9. delete elements in accordance with the position range 

语法:ZREMRANGEBYRANK key start stop

127.0.0.1:6379> ZREMRANGEBYRANK scoreboard 0 1
(integer) 2
127.0.0.1:6379> ZRANGE scoreboard 0 -1
1) "lisi"

10. The element according to remove Score Range

Syntax: ZREMRANGEBYSCORE key min max

11. Take ranking elements 

  • From small to large

Syntax: ZRANK key member

127.0.0.1:6379> ZRANK scoreboard lisi
(integer) 0
  • Descending

Syntax: ZREVRANK key member

127.0.0.1:6379> ZREVRANK scoreboard zhangsan
(integer) 1

3. Application

  • Merchandise sales charts

Requirements: Top display of commodities under the Commodity sales

Ideas: the definition of merchandise sales charts (sorted set collection), Key to items: sellsort, a score of merchandise sales.

 

Sales of goods write:

  • Sales product number 1001 was 9, sales of product number 1002 10
192.168.101.3:7007> ZADD items:sellsort 9 1001 10 1002
  • 商品编号1001的销量加1
192.168.101.3:7001> ZINCRBY items:sellsort 1 1001
  • 商品销量前10名:
192.168.101.3:7001> ZRANGE items:sellsort 0 9 withscores

六、Keys命令

1、设置key的生存时间

        Redis在实际使用过程中更多的用作缓存,然而缓存的数据一般都是需要设置生存时间的,即:到期后数据销毁。

EXPIRE key seconds 设置key的生存时间(单位:秒)key在多少秒后会自动删除

TTL key  查看key生于的生存时间

PERSIST key 清除生存时间 

PEXPIRE key milliseconds 生存时间设置单位为:毫秒

 

例如:

  • 设置test的值为1
192.168.101.3:7002> set test 1
OK
  • 获取test的值
 
  1. 192.168.101.3:7002> get test
  2. "1"
  • 设置test的生存时间为5秒
192.168.101.3:7002> EXPIRE test 5
(integer) 1
  • 查看test的生于生成时间还有1秒删除
192.168.101.3:7002> TTL test
(integer) 1
192.168.101.3:7002> TTL test
(integer) -2
  • 获取test的值,已经删除
192.168.101.3:7002> get test
(nil)

2、其它命令

  • keys

        返回满足给定pattern 的所有key

redis 127.0.0.1:6379> keys mylist*
1) "mylist"
2) "mylist5"
3) "mylist6"
4) "mylist7"
5) "mylist8"
  • exists

        确认一个key 是否存在,如从结果来看,数据库中不存在HongWan 这个key,但是age 这个key 是存在的

redis 127.0.0.1:6379> exists HongWan
(integer) 0
redis 127.0.0.1:6379> exists age
(integer) 1
redis 127.0.0.1:6379>
  • del

        删除一个key

redis 127.0.0.1:6379> del age
(integer) 1
redis 127.0.0.1:6379> exists age
(integer) 0
  • rename

        重命名key,示例:age 成功的被我们改名为age_new 了

redis 127.0.0.1:6379[1]> keys *
1) "age"
redis 127.0.0.1:6379[1]> rename age age_new
OK
redis 127.0.0.1:6379[1]> keys *
1) "age_new"
redis 127.0.0.1:6379[1]>
  • type

        返回值的类型。示例:这个方法可以非常简单的判断出值的类型

redis 127.0.0.1:6379> type addr
string
redis 127.0.0.1:6379> type myzset2
zset
redis 127.0.0.1:6379> type mylist
list
redis 127.0.0.1:6379>

 

发布了107 篇原创文章 · 获赞 184 · 访问量 21万+

Guess you like

Origin blog.csdn.net/qq_22172133/article/details/84964616