redis+php实现微博(二)发布与关注功能详解

这篇文章主要介绍了redis+php实现微博发布与关注功能,结合实例形式分析了php结合redis实现微博的发布及关注相关操作技巧,需要的朋友可以参考下。

本文实例讲述了redis+php实现微博发布与关注功能,分享给大家供大家参考,具体如下:

数据结构:

set post:postid:3:time timestamp

set post:postid:3:userid 5

set post:postid:3:content 测试发布哈哈哈哈

incr global:postid

set post:postid:$postidcho "用户名密码不能够为空!";

关注微博

following:3

被关注(粉丝)

followed:3

把发布的微博推给自己的粉丝

recivepost:10 postid

微博的发布代码:

  1. include("function.php");
  2. include("header.php");
  3. $content = I('content');
  4. if(!$content){
  5. error('内容不能够为空');
  6. }
  7. $user = isLogin();
  8. if($user==false){
  9. header("location:index.php");
  10. exit();
  11. }
  12. $r = redis_connect();
  13. $postid = $r->incr('global:postid');
  14. //$r->set("post:postid:".$postid.":time",time());
  15. //$r->set("post:postid:".$postid.":userid",$user['userid']);
  16. //$r->set("post:postid:".$postid.":content",$content);
  17. $r->hmset("post:postid:".$postid,array('userid'=>$user['userid'],'username'=>$user['username'],'time'=>time(),'content'=>$content));
  18. //把微博推给自己的粉丝
  19. $fans = $r->smembers("followed:".$user['userid']);
  20. $fans[] = $user['userid'];
  21. foreach($fans as $fansid){
  22. $r->lpush('recivepost:'.$fansid,$postid);
  23. }
  24. //单独累计个人发布的信息
  25. $r->lpush('userpostid:'.$user['userid'],$postid);
  26. header("location:home.php");
  27. exit;
  28. include("bottom.php");

微博的关注代码:

  1. include("function.php");
  2. include("header.php");
  3. if(isLogin()==false){
  4. header("location:index.php");
  5. exit;
  6. }
  7. $user = isLogin();
  8. $uid = trim($_GET['uid']);
  9. $f = trim($_GET['f']);
  10. $r = redis_connect();
  11. if($f==0){
  12. //将关注与被关注的数据结构存入redis
  13. $r->sadd("following:".$user['userid'],$uid);
  14. $r->sadd("followed:".$uid,$user['userid']);
  15. }else{
  16. //取消关注
  17. $r->srem("following:".$user['userid'],$uid);
  18. $r->srem("followed:".$uid,$user['userid']);
  19. }
  20. //根据传递过来的userid查找username
  21. $uname = $r->get("user:userid:".$uid.":username");
  22. header("location:profile.php?u=".$uname);
  23. include("bottom.php");