Redis微博系统发布与关注功能概述
本示例详细解析了使用Redis结合PHP开发微博系统中关于内容发布与用户关注的核心逻辑,供开发者参考实践。
首先明确底层采用的数据模型设计。
set post:postid:3:time timestamp set post:postid:3:userid 5 set post:postid:3:content 测试发布哈哈哈哈
在发布流程中,系统通过incr命令自增全局计数器global:postid以生成唯一微博ID,若输入校验失败则提示用户名或密码不能为空。
接下来处理用户间的社交关系,即关注操作。
使用键名following:3来标识当前用户的关注列表。
同时维护被关注者(即粉丝)的视角。
通过键名followed:3来记录谁关注了该用户。
当新用户发布微博后,系统需执行推送逻辑,将该微博ID分发给所有关注者。
推送目标为每个粉丝的个人收件箱,键名格式如recivepost:10,用于存储微博ID列表。
以下是微博发布功能的具体PHP代码实现。
include("function.php");
include("header.php");
$content = I('content');
if(!$content){
error('内容不能够为空');
}
$user = isLogin();
if($user==false){
header("location:index.php");
exit();
}
$r = redis_connect();
$postid = $r->incr('global:postid');
//$r->set("post:postid:".$postid.":time",time());
//$r->set("post:postid:".$postid.":userid",$user['userid']);
//$r->set("post:postid:".$postid.":content",$content);
$r->hmset("post:postid:".$postid,array('userid'=>$user['userid'],'username'=>$user['username'],'time'=>time(),'content'=>$content));
//把微博推给自己的粉丝
$fans = $r->smembers("followed:".$user['userid']);
$fans[] = $user['userid'];
foreach($fans as $fansid){
$r->lpush('recivepost:'.$fansid,$postid);
}
//单独累计个人发布的信息
$r->lpush('userpostid:'.$user['userid'],$postid);
header("location:home.php");
exit;
include("bottom.php");
以下是处理关注与取消关注功能的PHP代码实现。
include("function.php");
include("header.php");
if(isLogin()==false){
header("location:index.php");
exit;
}
$user = isLogin();
$uid = trim($_GET['uid']);
$f = trim($_GET['f']);
$r = redis_connect();
if($f==0){
//将关注与被关注的数据结构存入redis
$r->sadd("following:".$user['userid'],$uid);
$r->sadd("followed:".$uid,$user['userid']);
}else{
//取消关注
$r->srem("following:".$user['userid'],$uid);
$r->srem("followed:".$uid,$user['userid']);
}
//根据传递过来的userid查找username
$uname = $r->get("user:userid:".$uid.":username");
header("location:profile.php?u=".$uname);
include("bottom.php");
期望上述关于PHP程序设计的分享能为读者提供有益的帮助。