从Redis队列中循环取出数据,并写入数据库

从Redis队列中循环取出数据,并写入数据库

connect('127.0.0.1', 6379);
    $redis_key='Barrage';

    //死循环写库
    while (1){
        if($redis->lLen($redis_key) > 0){
            sleep(1);
            $content=$redis->lPop($redis_key);//取出一个元素
            $new_content=json_decode($content);
            if(!empty($new_content)){
                $timeStemp=strtotime($new_content->timeStemp);
                $value="'{$new_content->open_id}','{$new_content->text}','{$content}','{$timeStemp}','{$new_content->wxact_id}'";
                $field='open_id,content_text,content_json,add_time,wxact_id';
                if(!empty($value)){
                    $conn=mysqlConnect();//连接数据库
                    if($conn){
                        $res=mysql_insert($conn,"lqwine_wxact_barrage",$field,$value);//写入数据库
                        if($res['bool'] == false){
                            echo $res['msg'].'
'; echo "失败!+".$content;//输出失败的内容 } } } } } } } /** * 连接数据库 */ function mysqlConnect(){ $servername = "127.0.0.1"; $username = "root"; $password = "XXXX.";//线上 $dbname = "XXXXX"; $conn = new mysqli($servername, $username, $password,$dbname); if($conn->connect_error){ die("连接失败: " . $conn->connect_error); } return $conn; } /** * 插入 * @param $conn 数据库对象 * @param $field 字段 * @param $table 数据表 * @param $value 数据 */ function mysql_insert($conn,$table,$field,$value){ $sql = "INSERT INTO {$table} ({$field})VALUES ({$value});"; $query=$conn->multi_query($sql); if($query){ $arr_info['bool']=true; $arr_info['msg']=$query; }else{ $arr_info['bool']=false; $arr_info['msg']=$conn->error; } return $arr_info; } getRedis();

 

你可能感兴趣的:(从Redis队列中循环取出数据,并写入数据库)