W3Cschool
恭喜您成為首批注冊(cè)用戶
獲得88經(jīng)驗(yàn)值獎(jiǎng)勵(lì)
下面是Redis適用的一些場(chǎng)景:
比如典型的取你網(wǎng)站的最新文章,通過(guò)下面方式,我們可以將最新的 5000條評(píng)論的ID放在Redis的List集合中,并將超出集合部分從數(shù)據(jù)庫(kù)獲取。
使用LPUSH latest.comments命令,向 list集合中插入數(shù)據(jù) 插入完成后再用 LTRIM latest.comments 0 5000 命令使其永遠(yuǎn)只保存最近5000個(gè) ID 然后我們?cè)诳蛻舳双@取某一頁(yè)評(píng)論時(shí)可以用下面的邏輯
FUNCTION get_latest_comments(start,num_items):
id_list = redis.lrange("latest.comments",start,start+num_items-1)
IF id_list.length < num_items
id_list = SQL_DB("SELECT ... ORDER BY time LIMIT ...")
END
RETURN id_list
END
如果你還有不同的篩選維度,比如某個(gè)分類的最新 N 條,那么你可以再建一個(gè)按此分類的List,只存ID的話,Redis是非常高效的。
這個(gè)需求與上面需求的不同之處在于,前面操作以時(shí)間為權(quán)重,這個(gè)是以某個(gè)條件為權(quán)重,比如按頂?shù)拇螖?shù)排序,這時(shí)候就需要我們的 sorted set出馬了,將你要排序的值設(shè)置成 sorted set的score,將具體的數(shù)據(jù)設(shè)置成相應(yīng)的 value,每次只需要執(zhí)行一條ZADD命令即可。
127.0.0.1:6379> zdd topapp 1 weixin
(error) ERR unknown command 'zdd'
127.0.0.1:6379> zadd topapp 1 weixin
(integer) 1
127.0.0.1:6379> zadd topapp 1 QQ
(integer) 1
127.0.0.1:6379> zadd topapp 2 meituan
(integer) 1
127.0.0.1:6379> zincrby topapp 1 meituan
"3"
127.0.0.1:6379> zincrby topapp 1 QQ
"2"
127.0.0.1:6379> zrank topapp QQ
(integer) 1
3) "meituan"
127.0.0.1:6379> zrank topapp weixin
(integer) 0
127.0.0.1:6379> zrange topapp 0 -1
1) "weixin"
2) "QQ"
比如你可以把上面說(shuō)到的 sorted set 的 score 值設(shè)置成過(guò)期時(shí)間的時(shí)間戳,那么就可以簡(jiǎn)單地通過(guò)過(guò)期時(shí)間排序,定時(shí)清除過(guò)期數(shù)據(jù)了,不僅是清除 Redis中的過(guò)期數(shù)據(jù),你完全可以把 Redis 里這個(gè)過(guò)期時(shí)間當(dāng)成是對(duì)數(shù)據(jù)庫(kù)中數(shù)據(jù)的索引,用 Redis 來(lái)找出哪些數(shù)據(jù)需要過(guò)期刪除,然后再精準(zhǔn)地從數(shù)據(jù)庫(kù)中刪除相應(yīng)的記錄。
Redis的命令都是原子性的,你可以輕松地利用 INCR,DECR 命令來(lái)構(gòu)建計(jì)數(shù)器系統(tǒng)。
這個(gè)使用Redis的 set數(shù)據(jù)結(jié)構(gòu)最合適了,只需要不斷地將數(shù)據(jù)往 set中扔就行了,set意為集合,所以會(huì)自動(dòng)排重。
通過(guò)上面說(shuō)到的 set功能,你可以知道一個(gè)終端用戶是否進(jìn)行了某個(gè)操作,可以找到其操作的集合并進(jìn)行分析統(tǒng)計(jì)對(duì)比等。
Redis 的 Pub/Sub 系統(tǒng)可以構(gòu)建實(shí)時(shí)的消息系統(tǒng),比如很多用 Pub/Sub 構(gòu)建的實(shí)時(shí)聊天系統(tǒng)的例子。
使用list可以構(gòu)建隊(duì)列系統(tǒng),使用 sorted set甚至可以構(gòu)建有優(yōu)先級(jí)的隊(duì)列系統(tǒng)。
性能優(yōu)于Memcached,數(shù)據(jù)結(jié)構(gòu)更多樣化。作為RDBMS的前端擋箭牌,redis可以對(duì)一些使用頻率極高的sql操作進(jìn)行cache,比如,我們可以根據(jù)sql的hash進(jìn)行SQL結(jié)果的緩存:
def get_results(sql):
hash = md5.new(sql).digest()
result = redis.get(hash)
if result is None:
result = db.execute(sql)
redis.set(hash, result)
# or use redis.setex to set a TTL for the key
return result
下邊的例子是記錄UV
#!/usr/bin/python
import redis
from bitarray import bitarray
from datetime import date
r=redis.Redis(host='localhost', port=6379, db=0)
today=date.today().strftime('%Y-%m-%d')
def bitcount(n):
len(bin(n)-2)
def setup():
r.delete('user:'+today)
r.setbit('user:'+today,100,0)
def setuniquser(uid):
r.setbit('user:'+today,uid,1)
def countuniquser():
a = bitarray()
a.frombytes(r.get('user:'+today),)
print a
print a.count()
if __name__=='__main__':
setup()
setuniquser(uid=0)
countuniquser()
使用set進(jìn)行是否為好友關(guān)系,共同好友等操作
使用有序集合保存輸入結(jié)果:
ZADD word:a 0 apple 0 application 0 acfun 0 adobe
ZADD word:ap 0 apple 0 application
ZADD word:app 0 apple 0 application
ZADD word:appl 0 apple 0 application
ZADD word:apple 0 apple
ZADD word:appli 0 application
再使用一個(gè)有序集合保存熱度:
ZADD word_scores 100 apple 80 adobe 70 application 60 acfun
取結(jié)果時(shí)采用交集操作:
ZINTERSTORE word_result 2 word_scores word:a WEIGHTS 1 1
ZRANGE word_result 0 -1 withscores
? UUIDs as Surrogate Keys Our strategy spreads information about the state of an item in the queue across a number of Redis data structures, requiring the use of a per-item surrogate key to tie them together. The UUID is a good choice here because 1) they are quick to generate, and 2) can be generated by the clients in a decentralized manner. ? Pending List The Pending List holds the generated UUIDs for the items that have been enqueued(), and are ready to be processed. It is a RedisList, presenting the generated UUIDs in FIFO order. ? Values Hash The Values Hash holds the actual items that have been enqueued. It is a Redis Hash, mapping the generated UUID to the binary form of the the item. This is the only representation of the original item that will appear in any of the data structures. ? Stats Hash The Stats Hash records some timestamps and counts for each of the items. Specifically: ? enqueue time ? last dequeue time ? dequeue count ? last requeue time ? last requeue count. It is a Redis Hash, mapping the generated UUID to a custom data structure that holds this data in a packed, binary form. Why keep stats on a per-item basis? We find it really useful for debugging (e.g. do we have a bad apple item that is being continuously requeued?), and for understanding how far behind we are if queues start to back up. Furthermore, the cost is only ~40 bytes per item, much smaller than our typical queued items. ? Working Set The Working Set holds the set of UUIDs that have been dequeued(), and are currently being processed. It is a Redis Sorted Set, and scores each of the UUIDs by a pre-calculated, millisecond timestamp. Any object that has exceeded its assigned timeout is considered abandoned, and is available to be reclaimed. ? Delay Set The Delay Set holds the set of UUIDs that have been requeued() with a per-item deferment. It is a Redis Sorted Set, and scores each of the UUIDs by a pre-calculated, millisecond timestamp. Once the deferment timestamp has expired, the item will be returned to the Pending List. Why support per-item deferment? We have a number of use cases where we might want to backoff specific pieces of work — maybe an underlying resource is too busy — without backing off the entire queue. Per-item deferment lets us say, “requeue this item, but don’t make it available for dequeue for another n seconds.”
Copyright©2021 w3cschool編程獅|閩ICP備15016281號(hào)-3|閩公網(wǎng)安備35020302033924號(hào)
違法和不良信息舉報(bào)電話:173-0602-2364|舉報(bào)郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號(hào)
聯(lián)系方式:
更多建議: