mongo easy swoole 最终版

15 篇文章 0 订阅
<?php
/**
 * 直播间浏览记录
 */
namespace App\HttpController\Wx;
use App\Common\StatusCode;
use App\HttpController\Base;
use App\Logic\Common\CodeException;
use App\Logic\Common\RoomInfo;
use App\Logic\Common\Tools;
use App\Logic\Common\WechatUser;
use App\Utility\Driver\MongoClientDriver;
use App\Utility\MongoClient;
use App\Utility\RedisClient;

class RoomBrowseRecordManage extends Base
{
    public $wechat_user_space_id;
    private $userinfo;
    public function onRequest(?string $action): bool
    {
        if (!parent::onRequest($action)) {
            return false;
        }
        try {
            $this->jwtInit();
        }catch (CodeException $exception)
        {
            return $this->responseJson($exception->getErrorCode(), $exception->getErrorMessage());
        }

        $this->wechat_user_space_id = $this->jwtInfo()->crypted_info['userinfo']['wechat_user_space_id'];
        $this->userinfo = $this->jwtInfo()->crypted_userinfo;

        return true;
    }


    private function _getPipeline($wechat_user_space_id,$curentPage,$pageNum){
        $skip=intval(($curentPage-1)*$pageNum);
        $pipeline = [
            [
                '$match' => [
                    'wechat_user_space_id' => intval($wechat_user_space_id)
                ]
            ],
            [
                '$project' => [
                    'room_id'    => '$room_id',
                    'room_name'    => '$room_name',
                    'room_desc'    => '$room_desc',
                    'room_pic'    => '$room_pic',
                    'create_time'    => '$create_time',
                ]
            ],
            [
                '$group' => [
                    '_id'       => ['room_id' => '$room_id'],
                    'create_time'     => ['$max' => '$create_time'],
                    'count'     => ['$sum' => 1],
                    'room_name'     => ['$last' => '$room_name'],
                    'room_desc'     => ['$last' => '$room_desc'],
                    'room_pic'     => ['$last' => '$room_pic'],
                    'room_id'     => ['$last' => '$room_id'],
                    'id'     => ['$last' => '$_id'],

                ]
            ],
            [
                '$sort' => ['create_time' => -1]
            ],
            [
                '$skip' =>$skip
            ],
            [
                '$limit' =>intval($pageNum)
            ]
        ];
        return $pipeline;
    }
    private function _getOptions($wechat_user_space_id,$curentPage,$pageNum){
        $options = [
            'aggregate' =>'ny_room_browse_record',
            'pipeline'  =>  $this->_getPipeline($wechat_user_space_id,$curentPage,$pageNum),
            'cursor'    => new \stdClass(),
        ];
        return $options;
    }
    /**
     * @api {get} /Wx/RoomBrowseRecordManage/recordList   浏览记录列表
     * @apiDescription      token中需要传wechat_user_space_id
     * @apiName recordList
     * @apiGroup RoomBrowseRecordManage
     * @apiParam {Number} [page=1]          分页页码
     * @apiParam {Number} [page_size=6]     分页步长
     * @apiSuccessExample success-示例:
    {
    "code": 200,
    "msg": "success",
    "data": {
    "totalNum": 2,
    "lists": [
    {
    "id":1,
    "room_id": 65806,
    "room_name": "分销统计早数据",
    "room_pic": "http://console.nuoyun.tv/Public/Home/Images/cover.jpg",
    "room_desc": ""
    },
    {
    "id":1,
    "room_id": 65807,
    "room_name": "1",
    "room_pic": "http://console.nuoyun.tv/Public/Home/Images/cover.jpg",
    "room_desc": ""
    }
    ]
    }
    }
     * @apiUse ParamError
     */

    public function recordList(){
        $params = $this->request()->getRequestParam();

        $curentPage=$params['curentPage']??1;
        $pageNum=$params['pageNum']??10;

        $options=$this->_getOptions($this->wechat_user_space_id,$curentPage,$pageNum);

        $key = 'es3_room_browse_record_'.$this->wechat_user_space_id."_".$curentPage."_".$pageNum;
        $result= RedisClient::getWxDataWithLock($key,15,function ()use($options){
            return $this->_getRecordListFromMongo($options);
        });

        $this->writeJsonSelf(['code' => StatusCode::success,'msg' => 'success','data' => $result]);
    }
    private function _getRecordListFromMongo($options){
        $result= MongoClient::getInstance()->client()->callback(function (MongoClientDriver $driver) use($options){
            $driver->getDb();
            $driver->collection = 'ny_room_browse_record';
            $list = $driver->executeCommandMongo($options);
            $listNew=[];
            foreach ($list as $k=>$v){
                $listNew[$k]['room_name']=$v->room_name;
                $listNew[$k]['room_desc']=$v->room_desc;
                $listNew[$k]['room_pic']=$v->room_pic;
                $listNew[$k]['id']=json_decode(json_encode($v->id),true)['$oid'];
            }
            return $listNew;
        });
        return $result??[];
    }

    /**
     * @api {get} /Wx/RoomBrowseRecordManage/addRecord   添加浏览记录
     * @apiDescription      token中需要传wechat_user_space_id
     * @apiName addRecord
     * @apiParam {String} room_id           直播间id
     * @apiParam {String} terminal           设备号
     * @apiGroup RoomBrowseRecordManage
     * @apiSuccessExample success-示例:
    {
    "code": 200,
    "msg": "success",
    "data": []
    }
     * @apiUse ParamError
     */
    public function addRecord(){
        $rules = ['room_id'=>'require','terminal'=>'require'];
        $params = $this->checkRequestParam($rules);
        if($params === false)
        {
            $this->writeJsonSelf(['code' =>StatusCode::param_error,'msg' => 'param error','data'=>array()]);
            return false;
        }

        $this->_addUserRoomRelation($params);

        $redis_boj = RedisClient::getInstance();
        $app_row = RoomInfo::appRow($params['room_id']);
        $res = $redis_boj->lpush('k8s_queue',serialize([
            'type' => 'func_job',
            'func' => 'roomBrowseRecordAdd',
            'data' => [
                'room_id'=>$params['room_id'],
                'wechat_user_space_id' => $this->wechat_user_space_id,
                'terminal' => $params['terminal'],
                'room_name' =>$app_row['push_app_nick'],
                'room_pic' => $app_row['app_cover'] ? spliceImageUrl($app_row['app_cover']) : RoomInfo::getThemeCover($app_row['theme_type']),
                'room_desc' =>$app_row['desc'],
                'is_delete' =>2,
                'create_time' =>time(),
            ]
        ]));
        if (!$res){
            $this->writeJsonSelf(['code' =>StatusCode::fail,'msg' => '操作失败','data'=>array()]);
            return false;
        }
        $this->writeJsonSelf(['code' => StatusCode::success,'msg' => 'success','data' => []]);
    }


    /**
     * use for: 记录微信用户与直播间关系
     * auth: Joql
     * @param $params
     * @return bool
     * date:2020-11-06 11:24
     */
    protected function _addUserRoomRelation($params)
    {
        $save['app_id'] = $params['room_id'];
        $save['ip']= getRealIP($this->request());
        $save['device'] = Tools::deviceType($this->request()->getHeaderLine('user-agent'));

        $logic = new WechatUser();
        $logic->addUserRoomRelation($this->userinfo['wechat_user_space_id'], $save);
        return true;
    }

    /**
     * @api {post} /Wx/RoomBrowseRecordManage/delRecord   删除浏览记录
     * @apiDescription      token中需要传wechat_user_space_id
     * @apiName delRecord
     * @apiGroup RoomBrowseRecordManage
     * @apiSuccessExample success-示例:
    {
    "code": 200,
    "msg": "success",
    "data": []
    }
     * @apiUse ParamError
     */
    public function delRecord(){
        if (!$this->wechat_user_space_id){
            $this->writeJsonSelf(['code' =>StatusCode::param_error,'msg' => '您不能删除浏览记录','data'=>array()]);
            return false;
        }

        $wechat_user_space_id=$this->wechat_user_space_id;
        $res= MongoClient::getInstance()->client()->callback(function (MongoClientDriver $driver) use($wechat_user_space_id){

            $driver->getDb();
            $driver->collection = 'ny_room_browse_record';
            $ret = $driver->delete(['wechat_user_space_id'=>$wechat_user_space_id]);
            return $ret;
        });

        if (!$res){
            $this->writeJsonSelf(['code' =>StatusCode::fail,'msg' => '操作失败','data'=>array()]);
            return false;
        }
        $this->writeJsonSelf(['code' => StatusCode::success,'msg' => 'success','data' => []]);

    }

    /**
     * @api {get} /Wx/RoomBrowseRecordManage/delOneRecord   删除单条浏览记录
     * @apiDescription      删除单条浏览记录
     * @apiName delOneRecord
     * @apiGroup RoomBrowseRecordManage
     * @apiParam {Number} room_browse_record_id     直播间浏览记录id
     * @apiSuccessExample success-示例:
    {
    "code": 200,
    "msg": "success",
    "data": []
    }
     * @apiUse ParamError
     */
    public function delOneRecord(){
        $rules = ['room_browse_record_id'=>'require'];
        $params = $this->checkRequestParam($rules);
        if($params === false)
        {
            $this->writeJsonSelf(['code' =>StatusCode::param_error,'msg' => 'param error','data'=>array()]);
            return false;
        }

        $room_browse_record_id=$params['room_browse_record_id'];
        $res= MongoClient::getInstance()->client()->callback(function (MongoClientDriver $driver) use($room_browse_record_id){


            $driver->getDb();
            $driver->collection = 'ny_room_browse_record';
//            $ret = $driver->delete(['_id.$oid'=>$room_browse_record_id]);
            $ret = $driver->delete(['_id'=>new \MongoDB\BSON\ObjectID($room_browse_record_id)]);
            return $ret;
        });

        if (!$res){
            $this->writeJsonSelf(['code' =>StatusCode::fail,'msg' => '操作失败','data'=>array()]);
            return false;
        }
        $this->writeJsonSelf(['code' => StatusCode::success,'msg' => 'success','data' => []]);
    }

}
<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/8/8
 * Time: 9:33
 */

namespace App\Utility\Driver;

use EasySwoole\EasySwoole\Config;
use EasySwoole\EasySwoole\Trigger;
use EasySwoole\SyncInvoker\AbstractInvoker;
use MongoDB\Driver\BulkWrite;
use MongoDB\Driver\Command;
use MongoDB\Driver\Manager;
use MongoDB\Driver\Query;
use MongoDB\Driver\WriteConcern;


class MongoClientDriver extends AbstractInvoker
{
    protected $db;
    protected $database;
    public $collection;
    protected $bulk;
    protected $writeConcern;
    protected $defaultConfig;

    function getDb($config = []):Manager
    {
        if($this->db == null){
            $this->defaultConfig = Config::getInstance()->getConf('MONGO');
            $config = array_merge($this->defaultConfig, $config);
            $mongoServer = "mongodb://";
            if ($config['username']) {
                $mongoServer .= $config['username'] . ':' . $config['password'] . '@';
            }
            $mongoServer .= $config['hostname'];
            if ($config['port']) {
                $mongoServer .= ':' . $config['port'];
            }
            $mongoServer .= '/' . $config['database'];
            if(isset($config['uri'])){
                $mongoServer = $config['uri'];
            }
            $this->db = new Manager($mongoServer);
            $this->database = $config['database'];
            isset($config['collection']) && $this->collection = $config['collection'];
        }
        $this->bulk = new BulkWrite();
        $this->writeConcern = new WriteConcern(WriteConcern::MAJORITY, 100);
        return $this->db;
    }

    protected function onException(\Throwable $throwable)
    {
        Trigger::getInstance()->throwable($throwable);
        return null;
    }

    public function executeCommandMongo($options) {
        $command = new Command($options);
        $result = $this->db->executeCommand($this->database, $command);
        $res = $result->toArray();
        return $res;
    }
    /**
     * use for: 统计总数
     * auth: Joql
     * @param array $where
     * @return int
     * date:2020-05-15 17:08
     */
    public function count($where = []) {
        $command = new Command(['count' => $this->collection, 'query' => $where]);
        $result = $this->db->executeCommand($this->database, $command);
        $res = $result->toArray();
        $count = 0;
        if ($res) {
            $count = $res[0]->n;
        }
        return $count;
    }

    /**
     * use for: 查询
     * auth: Joql
     * @param array $where
     * @param array $option
     * @return string
     * date:2020-05-15 17:09
     */
    public function query($where = [], $option = []) {
        $query = new Query($where, $option);
        $result = $this->db->executeQuery("$this->database.$this->collection", $query);

        $ret = [];
        foreach ($result as $document) {
            $ret[] = (array)$document;
        }
        return $ret;
    }

    public function update($where = [], $update = [], $multi = false, $upsert = false) {
        $this->bulk->update($where, ['$set' => $update], ['multi' => $multi, 'upsert' => $upsert]);
        $result = $this->db->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);

        return $result->getModifiedCount();
    }

    public function insert($data = []) {
        $this->bulk->insert($data);
        $result = $this->db->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);

        return $result->getInsertedCount();
    }

    public function delete($where = [], $limit = 1) {
        $this->bulk->delete($where, ['limit' => $limit]);
        $result = $this->db->executeBulkWrite("$this->database.$this->collection", $this->bulk, $this->writeConcern);

        return $result->getDeletedCount();
    }

    public function mongoId($id){
       return new \MongoId($id);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值