怎么在PHP中使用redis實現拉模型?很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。
拉模型
拉模型就是展示微博的時候,獲取自己的所有關注的人,然后從關注的人中拉取新微博。
微博項目數據結構設計
user表設計
注冊的時候將user數據寫入redis中,key如下:
user數據的key
用戶名=user:uesrid:$uesrid:username
密碼=user:userid:$userid:password
還需要這樣寫一份,因為需要靠用戶名來登錄,這樣就可以根據用戶名來查詢用戶id。
user:username:userid:$userid
關注的人和粉絲設計
每個用戶在產生關注的動作后,在redis中維護兩個無序集合set,一個是following,一個是follower,following集合保存的是我關注的人,follower集合保存的是我的粉絲。注意是每個用戶都要維護這樣的兩個集合,用userid來區別。
單條微博表設計
每條微博的信息用hash結構來存儲,根據不同的微博id來區分,每條微博有如下信息:發布人id,發布人昵稱,發布時間,微博內容。
拉取關注者微博表 設計
每個用戶發布微博后,維護20條新微博,并保存到有序集合sorted set中,用不同的userid來區分。
注意:有序集合的score用微博id,集合保存的也是微博id。
個人微博表
每個用戶維護自己的微博,保存到鏈表中,只保存1000條,redis中只保存1000條微博數據,如果想查詢更多,去數據庫中查詢。
個人已拉取表設計
每個用戶在拉取微博后,將微博保存到已經拉取的表中,這個表是一個鏈表結構,最多保存1000條微博。
發布微博
首先將微博保存成hash結構,然后將微博保存到拉取表,還保存到個人微博表。
//1、保存微博 $conn = connredis(); $postid = $conn->incr('global:postid'); $conn->hmset('post:postid:'.$postid,['userid'=>$user['userid'],'username'=>$user['username'],'time'=>time(),'content'=>$content]); //2、每個人維護20條新微博,保存到有序集合中 $conn->zadd('starpost:userid:'.$user['userid'],$postid,$postid); if($conn->zcard('starpost:userid:'.$user['userid']) > 20){ $conn->zremrangebyrank('starpost:userid:'.$user['userid'],0,0); } //3、維護個人的1000條微博,保存到鏈表中 $conn->lpush('mypost:userid:'.$user['userid'],$postid); if($conn->llen('mypost:userid:'.$user['userid']) > 1000){ $conn->rpoplpush('mypost:userid:'.$user['userid'],'global:post'); }
展示微博
首先獲取所有關注的人,獲取上次拉取微博的位置,根據上次拉取的微博位置來拉取數據。然后給微博排序,設置新的拉取的位置,寫入到已拉取表中,獲取微博的詳細內容,最后獲取粉絲和關注數。進行展示即可。
//1、獲取拉取對象 $stars = $conn->smembers('following:'.$user['userid']);//獲取所有關注的人 $stars[] = $user['userid'];//需要拉取自己的微博 //2、獲取上次拉取的位置 $lastpull = $conn->get('lastpull:userid:'.$user['userid']); if(!$lastpull){ $lastpull = 0; } //3、拉取微博 $latest = []; foreach($stars as $star){ $latest = array_merge($latest,$conn->zrangebyscore('starpost:userid:'.$star,$lastpull+1,1<<32-1)); } //4、給微博排序 sort($latest,SORT_NUMERIC); //5、設置拉取的位置 if(!empty($latest)){ $conn->set('lastpull:userid:'.$user['userid'],end($latest)); } //6、寫入到已拉取表中 foreach($latest as $l){ $conn->lpush('receivepost:'.$user['userid'],$l); } $conn->ltrim('receivepost:'.$user['userid'],0,999);//至多顯示1000條微博 //7、獲取微博的詳細內容 $postids = $conn->sort('receivepost:'.$user['userid'],['sort'=>'desc']); $posts = []; foreach($postids as $postid){ $posts[] = $conn->hmget('post:postid:'.$postid,['userid','username','time','content']); } //8、獲取粉絲和關注數 $fansnum = $conn->scard('follower:'.$user['userid']); $follownum = $conn->scard('following:'.$user['userid']);
看完上述內容是否對您有幫助呢?如果還想對相關知識有進一步的了解或閱讀更多相關文章,請關注創新互聯行業資訊頻道,感謝您對創新互聯網站建設公司,的支持。
當前標題:怎么在PHP中使用redis實現拉模型-創新互聯
URL地址:http://www.2m8n56k.cn/article8/gjpop.html
成都網站建設公司_創新互聯,為您提供品牌網站制作、服務器托管、電子商務、關鍵詞優化、虛擬主機、做網站
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:[email protected]。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯