個人認(rèn)為這個案例還是很經(jīng)典的
- 這個案例很好的實(shí)現(xiàn)了叙凡,如何記錄我關(guān)注了哪些人笆焰,哪些人關(guān)注了我
- 用set 結(jié)構(gòu)進(jìn)行去重, 關(guān)鍵是當(dāng)我關(guān)注別人的時候如何存儲
上代碼:
/**
* 關(guān)注別人
* @param userId 自己
* @param followUserId 你要關(guān)注的人
*/
public void follow(long userId, long followUserId){
//我關(guān)注了誰 需要在我關(guān)注的人的 集合中增加一條記錄
jedis.sadd("user::" + followUserId +"::followers",String.valueOf(userId));
//我關(guān)注人的集合
jedis.sadd("user::" +userId + "::follow_users",String.valueOf(followUserId));
}
- 以上代碼中一個方法內(nèi),存儲了兩個SET哎榴,那么這兩個set是干嘛的那
試想我們?nèi)绻挥胷edis,用數(shù)據(jù)庫存儲的話僵蛛,是不是需要設(shè)計數(shù)據(jù)庫表尚蝌,那么我們就會這樣設(shè)計,
一張是用戶表充尉,記錄用戶基礎(chǔ)信息
一張是用戶關(guān)注明細(xì)飘言,記錄誰關(guān)注了此用戶,字段為userId驼侠,follwUserId
我們在檢索的時候查詢 我被誰關(guān)注了 就直接select * from 關(guān)系表 where userId= 自己
那么檢索我關(guān)注了誰那姿鸿? 就是select * from 關(guān)系表 where follwUserId= 自己
是不是很簡單,但是這樣每次查庫性能是不行的倒源,所以我么要將這些數(shù)據(jù)提前聚合到緩存中:
- 也就出現(xiàn)了 上段代碼中的:兩個set
- 一個set用來存儲被關(guān)注的人的集合中插入誰關(guān)注了他苛预,誰那,就是我笋熬,key為我要關(guān)注的人的id热某,"user::" + followUserId +"::followers" value:為 自己
- 一個set用來存儲我關(guān)注了哪些人的集合, 那么key 為自己的id胳螟, value為你所關(guān)注的人
取消關(guān)注
/**
* 取消關(guān)注
* @param userId
* @param followUserId
*/
public void unfollow(long userId, long followUserId){
jedis.srem("user::" + followUserId +"::followers",String.valueOf(userId));
jedis.srem("user::" +userId + "::follow_users",String.valueOf(followUserId));
}
查看哪些人關(guān)注了我
/**
* 查看有哪些人關(guān)注了我
* @param userId
* @return
*/
public Set<String> getFollowers(long userId){
return jedis.smembers("user::" + userId +"::followers");
}
/**
* 查看我關(guān)注了哪些人
* @param userId
* @return
*/
public Set<String> getFollowUsers(long userId){
return jedis.smembers("user::" +userId + "::follow_users");
}
/**
* 查看自己關(guān)注的人數(shù)
* @param userId
* @return
*/
public long getFollowUsersCount(long userId) {
return jedis.scard("user::" + userId + "::follow_users");
}
/**
* 查看自己關(guān)注的人數(shù)
* @param userId
* @return
*/
public long getFollowersCount(long userId){
return jedis.scard("user::" +userId + "::follow_users");
}
/**
* 獲取用戶跟其他用戶之間共同關(guān)注的人有哪些
* @param userId
* @param otherUserId
* @return
*/
public Set<String> getSameFollowUsers(long userId, long otherUserId){
return jedis.sinter("user::" +userId + "::follow_users",
"user::" +otherUserId + "::follow_users");
}
/**
* 獲取給我推薦的可關(guān)注人
* 我關(guān)注的某個好友關(guān)注的一些人昔馋,我沒關(guān)注那些人,此時推薦那些人給我
* @param userId
* @param otherUserId
* @return
*/
public Set<String> getRecommendFollowUsers(long userId, long otherUserId){
return jedis.sdiff("user::" +userId + "::follow_users",
"user::" +otherUserId + "::follow_users");
}
很不錯的案例
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者