字段名 | 類型 | 索引 | 註解 |
---|---|---|---|
id | primaryKey() | ||
user_id | integer()->unsigned()->notNull() | normal | 用戶 |
followed_user | integer()->unsigned()->notNull() | 關注的人的id | |
status | smallInteger()->unsigned()->defaultValue(1) | 關注狀態:是否取消關注等 | |
created_at | integer()->unsigned()->notNull() | normal | |
updated_at | integer()->unsigned()->notNull() | normal |
優勢:php
1.設計簡單,方便查詢
2.能夠區分關注的每個人進行特殊處理(例如,不一樣人的關注事件,是否互粉,特別關注等),方便擴展
3.好寫代碼。mysql
缺點:redis
當用戶量大時表數據量會很是龐大,所以必須要採用水平分表的方式將用戶分散到多個表。sql
例如,有10萬用戶,ID爲1~10000的用戶放在表1(follow_1), ID爲10001~20000的用戶放在表2(follow_2), 以此類推。數據庫
然而分表後又會面臨另外一個問題,當被關注者依照多個表反查本身的粉絲時將會很是麻煩。所以須要再建一個粉絲表:json
字段名 | 類型 | 索引 | 註解 |
---|---|---|---|
id | primaryKey() | ||
user_id | integer()->unsigned()->notNull() | normal | 用戶 |
follower | integer()->unsigned()->notNull() | 粉絲 | |
status | smallInteger()->unsigned()->defaultValue(1) | 關注狀態:是否取消關注等 | |
created_at | integer()->unsigned()->notNull() | normal | |
updated_at | integer()->unsigned()->notNull() | normal |
此數據表依然須要作水平分表處理。segmentfault
字段名 | 類型 | 索引 | 註解 |
---|---|---|---|
id | primaryKey() | ||
user_id | integer()->unsigned()->notNull() | 惟一 | 用戶 |
followed_user | text | 關注的人 | |
follower | text | 粉絲 | |
created_at | integer()->unsigned()->notNull() | normal | |
updated_at | integer()->unsigned()->notNull() | normal |
優勢:安全
1.每一個用戶只有一條記錄
2.方便查詢服務器
缺點:微信
1.當粉絲數或關注的人數過大時,followed_user 和 follower 字段的數據長度會很是大,當用戶關注的人或者粉絲數達到十萬級別時,一條數據的數據量將會達到 兆 級別,將會極大地下降mysql的查詢和php數據處理的效率。
2.每一次使用該表時都要將整條數據取出進行計算,對資源耗費太過嚴重。
使用redis的Hash數據類型
Redis hash是一個string類型的field和value的映射表。
Redis 中每一個 hash 能夠存儲 232 - 1 鍵值對(40多億)。
每一個用戶分一張hash表,表名爲用戶id(可加前綴或後綴)
用戶每關注一我的,便在hash表中添加一條數據
field: 關注用戶的id value:關注時間
field | value |
---|---|
2 | 1483423443 |
3 | 1483423445 |
13 | 1483423440 |
... | ... |
field | value |
---|---|
1 | 1483423443 |
5 | 1483423445 |
10 | 1483423440 |
... | ... |
......
優勢
1.查詢處理速度快。
缺點
1.消耗服務器內存和CPU。最好使用一臺單獨的服務器來運行 Redis
2.數據查詢,處理不如關係型數據庫靈活。
3.開發步驟複雜,學習成本高。
微博關注是根據什麼來知道你關注我,我關注你了?數據庫怎麼設計?
SNS,微博 好友關注和推送功能的數據庫設計是怎麼實現的底層設計?
新浪微博開放平臺中的Redis實踐_大數據時代feed架構_微博消息系統架構演進_互聯網公司技術架構資料.新浪微博.微博架構與平臺安全_構建高性能的微博系統