用户发内容储存到redis,redis再存入mysql数据库
/**
* reids 连接函数
* @return Redis
* @throws Exception
*/
function redis(){
static $redis;
//获取配置文件
$cfg = \dcr\Base::getConfig('redis');
if( is_null($redis) ){
//连接redis 如果出现 redsis server went away 先检查防火墙是否开启了端口,再检查redis配置文件是否只bind了 127.0.0.1这个ip
$redis = new \Redis();
$redis->connect($cfg['host'],$cfg['port']);
if( $cfg['auth'] ) $redis->auth('redis520');
if( $redis->ping() !=='+PONG' ){
throw new Exception('redis 连接失败');
}
};
return $redis;
}
class IndexController{
/**
*使用redis储存数据
*/
function index(){
$redis = redis();
pr( $redis->lRange('user:content',0,-1) );
if( !empty($_POST) ){
$time = time();
$info = array(
'user_id' => $_POST['user'],
'content' => $_POST['content'],
'create_time' => $time
);
$info = json_encode($info);
$status = $redis->lPush('user:content',$info);
if( !$status ){
exit('提交成功<script>self.location=document.referrer;</script>');
}
exit('提交成功<script>self.location=document.referrer;</script>');
}
$userid = mt_rand(1,999999);
include $this->show();
}
/**
* 从mysql中写入mysql中
* @throws \Exception
*/
function redisToMysql(){
$redis = redis();
$model = new Model();
$i = 0;
if( $redis->lSize('user:content') > 0 ){
while (true){
++$i;
echo '插入地'.$i.'条记录<br/>';
$info = $redis->rPop('user:content');
$info = json_decode($info,true);
$model->db->insert('weibo',$info);
}
} else {
sleep(1);
}
$redis->close();
}
}这里仅仅只是展示思维逻辑,上面的具体代码不能通用。
Dcr163的博客
http://dcr163.cn/220.html(转载时请注明本文出处及文章链接)