加入收藏 | 设为首页 | 会员中心 | 我要投稿 湖南网 (https://www.hunanwang.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程 > 正文

Redis 多方法实现计数器成果

发布时间:2019-10-17 10:28:59 所属栏目:编程 来源:yanglbme
导读:计数器在许多网站中都举办了普及的应用,好比文章的点赞数、页面的赏识数、网站的访客数、视频的播放数等等。在这篇文章里,我会行使 Redis 的三种数据范例,来别离实现计数器的成果。 请跟从我一路来看看吧。 行使字符串键 下面代码演示了怎样操作 Redis
副问题[/!--empirenews.page--]

计数器在许多网站中都举办了普及的应用,好比文章的点赞数、页面的赏识数、网站的访客数、视频的播放数等等。在这篇文章里,我会行使 Redis 的三种数据范例,来别离实现计数器的成果。

请跟从我一路来看看吧。

Redis 多方法实现计数器成果

行使字符串键

下面代码演示了怎样操作 Redis 中的字符串键来实现计数器成果。个中,incr() 要领用于累加计数,get_cnt() 要领用于获取当前的计数值。

  1. from redis import Redis 
  2.  
  3. class Counter: 
  4.     def __init__(self, client: Redis, key: str): 
  5.         self.client = client 
  6.         self.key = key 
  7.  
  8.     def incr(self, amount=1): 
  9.         """计数累加""" 
  10.         self.client.incr(self.key, amount=amount) 
  11.  
  12.     def decr(self, amount=1): 
  13.         """计数累减""" 
  14.         self.client.decr(self.key, amount=amount) 
  15.  
  16.     def get_cnt(self): 
  17.         """获取当前计数的值""" 
  18.         return self.client.get(self.key) 
  19.  
  20.  
  21. if __name__ == '__main__': 
  22.     client = Redis(decode_responses=True) 
  23.     counter = Counter(client, 'page_view:12') 
  24.     counter.incr() 
  25.     counter.incr() 
  26.     print(counter.get_cnt())  # 2 

假设我们要统计 page_id 为 12 的页面的赏识数,那么我们可以设定 key 为 page_view:12,用户每一次赏识,就挪用一次 counter 的 incr() 要领举办计数。

行使哈希键

在上面的代码中,我们必要针对每个统计项,都单独配置一个字符串键。那么,下面我们来看看怎样通过 Redis 的哈希键,来对关联的统计项举办同一打点。

  1. from redis import Redis 
  2.  
  3. class Counter: 
  4.     def __init__(self, client: Redis, key: str, counter: str): 
  5.         self.client = client 
  6.         self.key = key 
  7.         self.counter = counter 
  8.  
  9.     def incr(self, amount=1): 
  10.         """计数累加""" 
  11.         self.client.hincrby(self.key, self.counter, amount=amount) 
  12.  
  13.     def decr(self, amount=1): 
  14.         """计数累减""" 
  15.         self.client.hincrby(self.key, self.counter, amount=-amount) 
  16.  
  17.     def get_cnt(self): 
  18.         """获取当前计数的值""" 
  19.         return self.client.hget(self.key, self.counter) 
  20.  
  21.  
  22. if __name__ == '__main__': 
  23.     client = Redis(decode_responses=True) 
  24.     counter = Counter(client, 'page_view', '66') 
  25.     counter.incr() 
  26.     counter.incr() 
  27.     print(counter.get_cnt())  # 2 

假如回收哈希键,那么,我们对付统一范例的计数,可以行使一个沟通的 key 来举办存储。好比,在上面例子中,我们行使 page_view 来统计页面的赏识数,对付 page_id 为 66 的页面,直接添加到 page_view 对应的字段中即可。

行使荟萃键

(编辑:湖南网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

热点阅读