Redis-03, common data types: string, hash, list

Redis supports five data types: string (string), hash (hash), list (list), set (set) and zset (sorted set: ordered set). Corresponding in Java: String, HashMap, LinkedList, HashSet, TreeSet

String

String is the most basic type of redis, you can understand it as the same type as Memcached, one key corresponds to one value.

The string type is binary safe. This means that the redis string can contain any data. Such as jpg pictures or serialized objects.

The string type is the most basic data type of Redis, and the value of the string type can store up to 512MB.

  • Stored data: single data, the simplest data storage type, and the most commonly used data storage type
  • Format of stored data: one storage space holds one data
  • Store content: usually use string

string as a numeric operation

  • The string stored in redis is a string by default, and it will be converted to a numeric type for calculation when it encounters incr and decr operations.
  • All operations of redis are atomic, and all services are processed in a single thread. The commands are executed one by one, so there is no need to consider
    the impact of data caused by concurrency .
  • Note: If the original data cannot be converted to a numeric value or exceeds the upper limit of redis numeric data, an error will be reported.
    9223372036854775807 (maximum value of long data in Java, Long.MAX_VALUE)

Basic commands

command Features
set key value Add / modify data, set the existing key to overwrite and modify
get key retrieve data
of the key delete data
mset key1 value1 key2 value2 … Add / modify multiple data
mget key1 key2 … Get multiple data
strlen key Get the number of data characters (string length)
append key value Append the message to the back of the original message (if the original message exists, append it, otherwise create a new one)
>SET username chenheng
OK
>get username
"chenheng"
>del username
(integer) 1

>mset a 1 b 2 c 3
OK
>mget a b c
1) "1"
2) "2"
3) "3"

>strlen username
(integer) 8

>append a BCDE
(integer) 5			//追加成功,返回字符总个数

In single set / get and multiple set / get, when there are many data, it is recommended to use mset, mget

Extended Command 1

Extended commands Features
incr key Numerical data increment by 1
incrby key increment Set the numeric data to increase the value of the specified range
incrbyfloat key increment Set the numeric data to increase the decimal value of the specified range
decr key Numerical data decrement by 1
decrby key increment Set the numeric data to reduce the value of the specified range
//b=2
>incr b
(integer) 3

>incrby b 10
(integer) 13

>incrbyfloat b 0.5
"13.5"

Extended Command 2

command Features
setex key seconds value Set the value of the data, and is set in seconds keysurvival time
psetex key milliseconds value Set the value of the data, and set in milliseconds keysurvival time
setnx key value The keyvalue is set value, if and only if keydoes not exist. If given keyalready exists, SETNX do nothing.
>setex a 5 name
OK
>get a
(nil)

Note: During the survival of the time-sensitive data, the common data of the set with the same name will be eliminated.

Application scenario

Business scenario 1 In
large-scale enterprise-level applications, table splitting is a basic operation. Multiple tables are used to store the same type of data, but the corresponding primary key id must be unified
and cannot be repeated. The Oracle database has sequence settings to solve this problem, but the MySQL database does not have a similar
mechanism, so how to solve it?

Solution : Set key increment and decrement

Business scenario 2

"The strongest girls" start the sea election voting, which can only be voted through WeChat, and each WeChat can only vote 1 every 4 hours.
E-commerce merchants open hot product recommendation, hot products can not always be in the hot period, the hot period of each product is maintained for 3 days, after 3 days to automatically cancel the hot.
Hot news will appear on news websites. The biggest feature of hot news is timeliness. How to automatically control the timeliness of hot news?

Solution : Set the data to have a specified life cycle

Business scenario 3

High frequency access information display control on the homepage, such as Sina Weibo DaV homepage shows the number of fans and the number of Weibo

solution

Set user information for big V users in redis, using the user's primary key and attribute value as the key, and set a regular refresh strategy
user:id:3506728370:fans → 12210947
user:id:3506728370:blogs → 6164
user:id:3506728370:focuss → 83
in the background. Store big V user information in redis in json format and refresh regularly (you can also use the hash type)
user:id:3506728370 → {"id":3506728370,"name":"春晚","fans":12210862,"blogs":6164, "focus":83}

Application of string

  • Redis is used to control the primary key id of the database table, provide a generation strategy for the primary key of the database table, and ensure the uniqueness of the primary key of the database table.
    This solution is applicable to all databases and supports database clusters.
  • Redis controls the life cycle of data, controls business behavior through data failure, and applies to all operations with time-limited control
  • Redis applies to various structured and unstructured high-heat data access acceleration
  • Redis is used for service control of time-based pay-per-view settlement

hash

Redis hash is a set of key-value (key => value) pairs.
Redis hash is a mapping table of field and value of type string. Hash is especially suitable for storing objects.
The storage of object data will be cumbersome if it has more frequent update requirements:

image-20200412114504577

  • New storage requirements: grouping a series of stored data for easy management, typical application storage object information
  • Required storage structure: one storage space holds multiple key-value data
  • Hash type: the bottom layer uses a hash table structure to implement data storage
  • Hash storage structure optimization
    • If the number of fields is small, the storage structure is optimized to an array-like structure
    • If the number of fields is large, the storage structure uses the HashMap structure

Basic commands

command Features
hset key field value Add / modify the data of a field
hget key field Get the data of a field
hgetall key Get all keys and values
hdel key field1 [field2...] Delete key
hmset key field1 value1 [field2 value2 …] Add / modify multiple field data
hmget key field1 [field2 …] Get multiple data
select key Get the number of fields in the hash table
hexists key field Gets whether the specified field exists in the hash table
>  hset user name zhangsan
(integer) 1
>  hget user name
"zhangsan"
>  hset user age 12
(integer) 1
> hset user grade 3
(integer) 1

>  hget user name
"zhangsan"

> hgetall user
1) "name"
2) "zhangsan"
3) "age"
4) "12"
5) "grade"
6) "3"

>  hdel user grade
(integer) 1

> hmset user grade 3 class 2
OK

> hmget user grade class
1) "3"
2) "2"

> hlen user
(integer) 4

> hexists user class
(integer) 1

Extended commands

command Features
hkeys key Get all the field names in the hash table
whale key Get all the field values ​​in the hash table
hincrby key field increment Set the numeric data of the specified field to increase the value of the specified range
hincrbyfloat key field increment Set the numeric data of the specified field to increase the value of the specified range
hsetnx key field value Add without specifying a field
> hkeys user
1) "name"
2) "age"
3) "grade"
4) "class"

> hvals user
1) "zhangsan"
2) "12"
3) "3"
4) "2"

> hincrby user grade 4
(integer) 7

> hincrbyfloat user age 0.5
"12.5"

> hsetnx user age 10
(integer) 0
> hset user house 100
(integer) 1

Precautions

  • The value under the hash type can only store character strings, it is not allowed to store other data types, and there is no nesting phenomenon. If the data is not obtained, the
    corresponding value is (nil)
  • Each hash can store 232-1 key-value pair
  • hash类型十分贴近对象的数据存储形式,并且可以灵活添加删除对象属性。但hash设计初衷不是为了存
    储大量对象而设计的,切记不可滥用,更不可以将hash作为对象列表使用
  • hgetall 操作可以获取全部属性,如果内部field过多,遍历整体数据效率就很会低,有可能成为数据访问
    瓶颈

应用场景

业务场景1

电商网站购物车设计与实现

业务分析

分析购物车的redis存储模型,添加、浏览、更改数量、删除、清空

解决方案

  • 以客户id作为key,每位客户创建一个hash存储结构存储对应的购物车信息
  • 将商品编号作为field,购买数量作为value进行存储
  • 添加商品:追加全新的field与value
  • 浏览:遍历hash
  • 更改数量:自增/自减,设置value值
  • 删除商品:删除field
  • 清空:删除key

为了加速了购物车商品信息的呈现

  • 每条购物车中的商品记录保存成两条field

  • field1专用于保存购买数量
    命名格式:商品id:nums
    保存数据:数值

  • field2专用于保存购物车中显示的信息,包含文字描述,图片地址,所属商家信息等
    命名格式:商品id:info
    保存数据: json

    该字段的数据从一个商品信息独立hash中读取

    使用hsetnx key field value动态创建和扩展独立hash

业务场景2

双11活动日,销售手机充值卡的商家对移动、联通、电信的30元、 50元、 100元商品推出抢购活动,每种商
品抢购上限1000张

解决方案

  • 以商家id作为key
  • 将参与抢购的商品id作为field
  • 将参与抢购的商品数量作为对应的value
  • 抢购时使用降值的方式控制产品数量

hash的应用

  • redis 应用于购物车数据存储设计
  • redis 应用于抢购,限购类、限量发放优惠卷、激活码等业务的数据存储设计

hash和string的比较

string存储:整体性,数据要么一次刚更新,要么一次性读取,主要用户呈现数据
hash: 更新灵活

list

Redis 列表是简单的字符串列表,按照插入顺序排序。你可以添加一个元素到列表的头部(左边)或者尾部(右边)。

  • 数据存储需求:存储多个数据,并对数据进入存储空间的顺序进行区分
  • 需要的存储结构:一个存储空间保存多个数据,且通过数据可以体现进入顺序
  • list类型:保存多个数据,底层使用双向链表存储结构实现
image-20200412131751107 image-20200412131835596

基本命令

命令 功能
lpush key value1 [value2] …… 从左边添加/修改数据
rpush key value1 [value2] …… 从右边添加/修改数据
lrange key start stop 获取指定范围的列表数据
lindex key index 获取指定下标的列表元素
llen key 获取列表的长度
lpop key 从左侧获取并移除一个数据
rpop key 从右侧获取并移除一个数据
> lpush students zhangsan lisi wangwu
(integer) 3

> lrange students 0 -1
1) "wangwu"
2) "lisi"
3) "zhangsan"

> lindex students 1
"lisi"

> llen students
(integer) 3

> lpop students
"wangwu"
> rpop students
"zhangsan"

扩展命令1

命令 功能
blpop key1 [key2] timeout 规定时间内从左侧获取并移除一个数据
brpop key1 [key2] timeout 规定时间内从右侧获取并移除一个数据
brpoplpush source destination timeout 从列表中取出最后一个元素,并插入到另外一个列表的头部; 如果列表没有元素会阻塞列表直到等待超时或发现可弹出元素为止
> blpop students 5
1) "students"
2) "lisi"

lrange list1 0 -1
1) "d"
2) "c"
3) "b"
4) "a"
5) "300"
6) "200"
7) "100"
> lpush list2 d e f g
(integer) 4
> brpoplpush list1 list2 5
"100"
> lrange list2 0 -1
1) "100"
2) "g"
3) "f"
4) "e"
5) "d"

扩展命令2

命令 功能
lrem key count value 从左侧移除指定数量的指定数据
> lrem list1 1 200
(integer) 1

应用场景

业务场景1

微信朋友圈点赞,要求按照点赞顺序显示点赞好友信息,如果取消点赞,移除对应好友信息

解决方案

移除指定数据

业务场景2

The follow-up lists of individual users in twitter, Sina Weibo, and Tencent Weibo need to be displayed in the order of user attention, and the fan list needs to list the fans who have recently followed in the front.
How do news and information websites display the latest news or information in chronological order?
During the operation of an enterprise, the system will generate a large amount of operation data. How to ensure the unified output of operation logs of multiple servers?

solution

  • List-dependent data has the characteristics of order to manage information
  • Use the queue model to solve the problem of multi-channel information aggregation
  • Use the stack model to solve the latest news

application of list

  • redis applies to data control with sequence of operations
  • redis applied to the latest news display

Precautions

  • The data stored in the list are all of type string, and the total data capacity is limited, up to 232-1 element (4294967295).
  • List has the concept of index, but when operating data, it is usually in the form of a queue to perform enqueuing and dequeuing operations, or in the form of a stack.
  • Get all data operation end index is set to -1
  • list can perform paging operations on the data, usually the first page of information comes from the list, the second page and more information is loaded in the form of a database
  • redis should be used for data operations based on time sequence, without paying attention to specific time

Guess you like

Origin www.cnblogs.com/sout-ch233/p/12721526.html