副问题[/!--empirenews.page--]
计数器在许多网站中都举办了普及的应用,好比文章的点赞数、页面的赏识数、网站的访客数、视频的播放数等等。在这篇文章里,我会行使 Redis 的三种数据范例,来别离实现计数器的成果。
请跟从我一路来看看吧。

行使字符串键
下面代码演示了怎样操作 Redis 中的字符串键来实现计数器成果。个中,incr() 要领用于累加计数,get_cnt() 要领用于获取当前的计数值。
- from redis import Redis
-
- class Counter:
- def __init__(self, client: Redis, key: str):
- self.client = client
- self.key = key
-
- def incr(self, amount=1):
- """计数累加"""
- self.client.incr(self.key, amount=amount)
-
- def decr(self, amount=1):
- """计数累减"""
- self.client.decr(self.key, amount=amount)
-
- def get_cnt(self):
- """获取当前计数的值"""
- return self.client.get(self.key)
-
-
- if __name__ == '__main__':
- client = Redis(decode_responses=True)
- counter = Counter(client, 'page_view:12')
- counter.incr()
- counter.incr()
- print(counter.get_cnt()) # 2
假设我们要统计 page_id 为 12 的页面的赏识数,那么我们可以设定 key 为 page_view:12,用户每一次赏识,就挪用一次 counter 的 incr() 要领举办计数。
行使哈希键
在上面的代码中,我们必要针对每个统计项,都单独配置一个字符串键。那么,下面我们来看看怎样通过 Redis 的哈希键,来对关联的统计项举办同一打点。
- from redis import Redis
-
- class Counter:
- def __init__(self, client: Redis, key: str, counter: str):
- self.client = client
- self.key = key
- self.counter = counter
-
- def incr(self, amount=1):
- """计数累加"""
- self.client.hincrby(self.key, self.counter, amount=amount)
-
- def decr(self, amount=1):
- """计数累减"""
- self.client.hincrby(self.key, self.counter, amount=-amount)
-
- def get_cnt(self):
- """获取当前计数的值"""
- return self.client.hget(self.key, self.counter)
-
-
- if __name__ == '__main__':
- client = Redis(decode_responses=True)
- counter = Counter(client, 'page_view', '66')
- counter.incr()
- counter.incr()
- print(counter.get_cnt()) # 2
假如回收哈希键,那么,我们对付统一范例的计数,可以行使一个沟通的 key 来举办存储。好比,在上面例子中,我们行使 page_view 来统计页面的赏识数,对付 page_id 为 66 的页面,直接添加到 page_view 对应的字段中即可。
行使荟萃键
(编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|