Redis(二)-基本数据类型的使用

本文主要讲解redis的基本数据类型及其使用.

Strings

Redis strings store sequences of bytes, including text, serialized objects, and binary arrays. As such, strings are the most basic Redis data type. They’re often used for caching, but they support additional functionality that lets you implement counters and perform bitwise operations, too

string类型可以存储字节序列,文本,序列化对象和二进制数组。除此之外, 还可以实现计数器和执行位操作。
示例:

> SET user:1 salvatore
OK
> GET user:1
"salvatore"

# 值为序列化的json, 且过期时间设置为100秒
> SET ticket:27 "\"{'username': 'priya', 'ticket_id': 321}\"" EX 100

## 计数器
> INCR views:page:2
(integer) 1

# 指定递增的值
> INCRBY views:page:2 10
(integer) 11

限制:

By default, a single Redis string can be a maximum of 512 MB.

基本命令:

  • set 存储一个字符类型的值
  • setnx 存储一个字符类型的值, 仅key不存在的时候可以成功。通常用来实现分布式锁。
  • get 获取值
  • mget 获取多个key对应的值
  • incryby 计数器

性能:

Most string operations are O(1), which means they’re highly efficient. However, be careful with the SUBSTR, GETRANGE, and SETRANGE commands, which can be O(n). These random-access string commands may cause performance issues when dealing with large strings.

substr、 getrange、 setrange 是字符串截取相关的命令。

Lists

Redis lists are linked lists of string values. Redis lists are frequently used to:

  • Implement stacks and queues.
  • Build queue management for background worker systems.

可用于实现栈,队列以及队列管理。
示例:
实现队列的功能: 先进先出, 左近友出

> LPUSH work:queue:ids 101
(integer) 1
> LPUSH work:queue:ids 237
(integer) 2
> RPOP work:queue:ids
"101"
> RPOP work:queue:ids
"237"

实现栈的功能:先进后出, 左进左出

> LPUSH work:queue:ids 101
(integer) 1
> LPUSH work:queue:ids 237
(integer) 2
> LPOP work:queue:ids
"237"
> LPOP work:queue:ids
"101"

获取长度

> LLEN work:queue:ids
(integer) 0

将一个队列的最后一个值移动到另一个队列尾部

> LPUSH board:todo:ids 101
(integer) 1
> LPUSH board:todo:ids 273
(integer) 2
> LMOVE board:todo:ids board:in-progress:ids LEFT LEFT
"273"
> LRANGE board:todo:ids 0 -1
1) "101"
> LRANGE board:in-progress:ids 0 -1
1) "273"

修剪list

> LPUSH notifications:user:1 "You've got mail!"
(integer) 1
# 只保留前100个元素
> LTRIM notifications:user:1 0 99
OK
> LPUSH notifications:user:1 "Your package will be delivered at 12:01 today."
(integer) 2
> LTRIM notifications:user:1 0 99
OK

限制:

The max length of a Redis list is 2^32 - 1 (4,294,967,295) elements.

基本命令:

  • lpush
  • rpush
  • lrange
  • lpop
  • rpop
  • llen
  • lmove
  • ltrim

阻塞命令:

  • blpop: 从列表的头部删除并返回第一个元素。 如果列表为空, 则阻塞,直到列表不为空或者达到超时时间。
  • blmove: 移动一个元素到另一个list。若列表为空,则阻塞, 直到列表不为空。

性能:

List operations that access its head or tail are O(1), which means they’re highly efficient. However, commands that manipulate elements within a list are usually O(n). Examples of these include LINDEX, LINSERT, and LSET. Exercise caution when running these commands, mainly when operating on large lists.

Sets

A Redis set is an unordered collection of unique strings (members). You can use Redis sets to efficiently:

  • Track unique items (e.g., track all unique IP addresses accessing a given blog post).
  • Represent relations (e.g., the set of all users with a given role).
  • Perform common set operations such as intersection, unions, and differences.

元素不重复,与java中的set类似。

示例:
添加元素

> SADD user:123:favorites 347
(integer) 1
> SADD user:123:favorites 561
(integer) 1
> SADD user:123:favorites 742
(integer) 1
> SADD user:456:favorites 561
(integer) 1

检查元素是否存在

> SISMEMBER user:123:favorites 742
(integer) 1
> SISMEMBER user:123:favorites 299
(integer) 0

取两个集合中的交集

> SINTER user:123:favorites user:456:favorites
1) "561"

限制:

The max size of a Redis set is 2^32 - 1 (4,294,967,295) members.

常用命令:

  • sadd 添加元素
  • srem 移除指定元素
  • sismember 判断该元素是否需存在
  • sinter 取交集
  • scard 返回set的元素个数

替代方案:

Sets membership checks on large datasets (or on streaming data) can use a lot of memory. If you’re concerned about memory usage and don’t need perfect precision, consider a Bloom filter or Cuckoo filter as an alternative to a set.
Redis sets are frequently used as a kind of index. If you need to index and query your data, consider RediSearch and RedisJSON.

Hashes

存储键值对。
示例:

> HSET user:123 username martina firstName Martina lastName Elisa country GB
(integer) 4
> HGET user:123 username
"martina"
> HGETALL user:123
1) "username"
2) "martina"
3) "firstName"
4) "Martina"
5) "lastName"
6) "Elisa"
7) "country"
8) "GB"

计数

> HINCRBY device:777:stats pings 1
(integer) 1
> HINCRBY device:777:stats pings 1
(integer) 2
> HINCRBY device:777:stats pings 1
(integer) 3
> HINCRBY device:777:stats errors 1
(integer) 1
> HINCRBY device:777:stats requests 1
(integer) 1
> HGET device:777:stats pings
"3"
> HMGET device:777:stats requests errors
1) "1"
2) "1"

基本命令:

  • hset
  • hget
  • hmget
  • hincreby

性能:

Most Redis hash commands are O(1).
A few commands - such as HKEYS, HVALS, and HGETALL - are O(n), where n is the number of field-value pairs.

限制:
Every hash can store up to 4,294,967,295 (2^32 - 1) field-value pairs. In practice, your hashes are limited only by the overall memory on the VMs hosting your Redis deployment.

SortedSets

根据分数排序的set。用于排行榜, 滑动窗口等。

A Redis sorted set is a collection of unique strings (members) ordered by an associated score. When more than one string has the same score, the strings are ordered lexicographically. Some use cases for sorted sets include:

  • Leaderboards. For example, you can use sorted sets to easily maintain ordered lists of the highest scores in a massive online game.
  • Rate limiters. In particular, you can use a sorted set to build a sliding-window rate limiter to prevent excessive API requests.

示例:

> ZADD leaderboard:455 100 user:1
(integer) 1
> ZADD leaderboard:455 75 user:2
(integer) 1
> ZADD leaderboard:455 101 user:3
(integer) 1
> ZADD leaderboard:455 15 user:4
(integer) 1
> ZADD leaderboard:455 275 user:2
(integer) 

获取前三名

> ZRANGE leaderboard:455 0 2 REV WITHSCORES
1) "user:2"
2) "275"
3) "user:3"
4) "101"
5) "user:1"
6) "100"

获取指定元素的排名

> ZREVRANK leaderboard:455 user:2
(integer) 0

基本命令:

  • zadd
  • zrange
  • zrank
  • zrevrank

性能:

Most sorted set operations are O(log(n)), where n is the number of members.
Exercise some caution when running the ZRANGE command with large returns values (e.g., in the tens of thousands or more). This command’s time complexity is O(log(n) + m), where m is the number of results returned.

Streams

A Redis stream is a data structure that acts like an append-only log. You can use streams to record and simultaneously syndicate events in real time. Examples of Redis stream use cases include:

  • Event sourcing (e.g., tracking user actions, clicks, etc.)
  • Sensor monitoring (e.g., readings from devices in the field)
  • Notifications (e.g., storing a record of each user’s notifications in a separate stream)

redis为流中的每条数据生成一个Id, 该ID可用于检索或读取。
支持多种修剪策略和消费策略。
示例:

> XADD temperatures:us-ny:10007 * temp_f 87.2 pressure 29.69 humidity 46
"1658354918398-0"
> XADD temperatures:us-ny:10007 * temp_f 83.1 pressure 29.21 humidity 46.5
"1658354934941-0"
> XADD temperatures:us-ny:10007 * temp_f 81.9 pressure 28.37 humidity 43.7
"1658354957524-0"

从ID为1658354918398-0开始, 读取前两项

> XRANGE temperatures:us-ny:10007 1658354934941-0 + COUNT 2
1) 1) "1658354934941-0"
   2) 1) "temp_f"
      2) "83.1"
      3) "pressure"
      4) "29.21"
      5) "humidity"
      6) "46.5"
2) 1) "1658354957524-0"
   2) 1) "temp_f"
      2) "81.9"
      3) "pressure"
      4) "28.37"
      5) "humidity"
      6) "43.7"

读取最多100个新的流条目, 从流的末尾开始 。若无新的条目写入,阻塞最多300ms

> XREAD COUNT 100 BLOCK 300 STREAMS temperatures:us-ny:10007 $
(nil)

基本命令:

  • XADD adds a new entry to a stream.
  • XREAD reads one or more entries, starting at a given position and moving forward in time.
  • XRANGE returns a range of entries between two supplied entry IDs.
  • XLEN returns the length of a stream.

Geospatial

可以存储地理坐标并搜索。
示例:

> GEOADD locations:ca -122.27652 37.805186 station:1
(integer) 1
> GEOADD locations:ca -122.2674626 37.8062344 station:2
(integer) 1
> GEOADD locations:ca -122.2469854 37.8104049 station:3
(integer) 1

查找给定位置半径5公里内的所有位置,并返回到每个位置的距离。

> GEOSEARCH locations:ca FROMLONLAT -122.2612767 37.7936847 BYRADIUS 5 km WITHDIST
1) 1) "station:1"
   2) "1.8523"
2) 1) "station:2"
   2) "1.4979"
3) 1) "station:3"
   2) "2.2441"

基本命令:

  • GEOADD adds a location to a given geospatial index (note that longitude comes before latitude with this command).
  • GEOSEARCH returns locations with a given radius or a bounding box.

HyperLogLog

是一种估计集合基数的数据结构。

> PFADD members 123
(integer) 1
> PFADD members 500
(integer) 1
> PFADD members 12
(integer) 1

估算集合中的元素个数

> PFCOUNT members
(integer) 3

常用命令:

  • PFADD adds an item to a HyperLogLog.
  • PFCOUNT returns an estimate of the number of items in the set.
  • PFMERGE combines two or more HyperLogLogs into one.

性能:
Writing (PFADD) to and reading from (PFCOUNT) the HyperLogLog is done in constant time and space. Merging HLLs is O(n), where n is the number of sketches.

Bitmaps

位图是字符串类型的扩展, 可对一个或多个字符串执行按位操作;
示例:

> SETBIT pings:2024-01-01-00:00 123 1
(integer) 0
> GETBIT pings:2024-01-01-00:00 123
1

常用命令:

  • SETBIT sets a bit at the provided offset to 0 or 1.
  • GETBIT returns the value of a bit at a given offset.
  • BITOP lets you perform bitwise operations against one or more strings.
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一点博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值