Object-proxy是一个简单的远程对象代理。
用法
use ObjectProxy\ObjectProxy;use ObjectProxy\ObjectProxyService;$objectName = \SomeClass::class;// 要实例化的对象名称$constructArgs = [];// 构造函数的参数$proxyObject = new ObjectProxy($objectName, $constructArgs);// $proxyObject是SomeClass对象的代理。$virtualReturnObject = $proxyObject->someObjectMethod();// 这个 $virtualReturnObject 可以序列化后给到远程服务器。$return = new ObjectProxyService($virtualReturnObject);// 实例一个对象代理服务类处理操作代理对象$result = $return->getResult();if ($result instanceof \Exception) { echo $result->getMessage(); // 调用发生异常,显示错误消息。} else { var_dump($result); // SomeClass::someObjectMethod的返回结果。}示例
通过Swoole做一个PDO对象代理。
bin/swoole_client.phpuse Swoole\Client;use ObjectProxy\ObjectProxy;use ObjectProxy\Transporter;require __DIR__.'/../src/Loader.php';for ($i = 0;$i <= 20000;++$i) { $pdo = new ObjectProxy(\PDO::class, array('mysql:host=127.0.0.1;dbname=test', 'user', 'password', [\PDO::ATTR_PERSISTENT => true])); $stat = $pdo->prepare('SELECT * FROM test WHERE id = ?'); $id = 2; $stat->execute([$id]); $virtualObject = $stat->fetch(); $client = new Client(SWOOLE_SOCK_TCP); $client->connect('127.0.0.1', 9509); $client->send(Transporter::encode($virtualObject)); $data = $client->recv(); $client->close(); $r = Transporter::decode($data); if ($r instanceof \Exception) { echo 'Bad: '.$i.' '.$r->getMessage()."\n"; } else { echo 'OK: '.$i.':'.$r['id']."\n"; }}bin/swoole_server.phpuse Swoole\Server;use ObjectProxy\Transporter;use ObjectProxy\ObjectProxyService;require __DIR__.'/../src/Loader.php';class SwooleObjectProxyServer{ public function run() { echo 'Server: start.Swoole version is ['.SWOOLE_VERSION."]\n"; $serv = new Server('127.0.0.1', 9509); $serv->set(array( 'worker_num' => 20, //worker process num 'task_worker_num' => 10, //Object Pool Size //'backlog' => 128, //listen backlog //'open_tcp_keepalive' => 1, //'log_file' => '/tmp/swoole.log', //swoole error log )); $serv->on('WorkerStart', array($this, 'onStart')); $serv->on('Receive', array($this, 'onReceive')); $serv->on('Close', array($this, 'onClose')); $serv->on('Task', array($this, 'onTask')); $serv->on('Finish', array($this, 'onFinish')); $serv->on('WorkerStop', array($this, 'onShutdown')); $serv->start(); } public function onTask($serv, $task_id, $from_id, $data) { $service = new ObjectProxyService(Transporter::decode($data)); $serv->finish(Transporter::encode($service->getResult())); } public function onReceive($serv, $fd, $from_id, $data) { $result = $serv->taskwait($data); $serv->send($fd, $result); echo "onReceive\n"; } public function onClose($serv, $fd, $from_id) { echo "onClose\n"; } public function onStart($serv) { } public function onFinish($serv, $data) { } public function onShutdown($serv) { }}$serv = new SwooleObjectProxyServer();$serv->run();
评论