| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- <?php
- require_once __DIR__ . '/../Lib/StatisticProtocol.php';
- /**
- * 统计客户端
- * @author workerman.net
- */
- class StatisticClient
- {
- /**
- * [module=>[interface=>time_start, interface=>time_start ...], module=>[interface=>time_start ..], ... ]
- * @var array
- */
- protected static $timeMap = array();
-
- /**
- * 模块接口上报消耗时间记时
- * @param string $module
- * @param string $interface
- * @return void
- */
- public static function tick($module = '', $interface = '')
- {
- return self::$timeMap[$module][$interface] = microtime(true);
- }
-
- /**
- * 上报统计数据
- * @param string $module
- * @param string $interface
- * @param bool $success
- * @param int $code
- * @param string $msg
- * @param string $report_address
- * @return boolean
- */
- public static function report($module, $interface, $success, $code, $msg, $report_address = '')
- {
- $report_address = $report_address ? $report_address : 'udp://127.0.0.1:55656';
- if(isset(self::$timeMap[$module][$interface]) && self::$timeMap[$module][$interface] > 0)
- {
- $time_start = self::$timeMap[$module][$interface];
- self::$timeMap[$module][$interface] = 0;
- }
- else if(isset(self::$timeMap['']['']) && self::$timeMap[''][''] > 0)
- {
- $time_start = self::$timeMap[''][''];
- self::$timeMap[''][''] = 0;
- }
- else
- {
- $time_start = microtime(true);
- }
-
- $cost_time = microtime(true) - $time_start;
-
- $bin_data = StatisticProtocol::encode($module, $interface, $cost_time, $success, $code, $msg);
-
- return self::sendData($report_address, $bin_data);
- }
-
- /**
- * 发送数据给统计系统
- * @param string $address
- * @param string $buffer
- * @return boolean
- */
- public static function sendData($address, $buffer)
- {
- $socket = stream_socket_client($address);
- if(!$socket)
- {
- return false;
- }
- return stream_socket_sendto($socket, $buffer) == strlen($buffer);
- }
-
- }
- if(PHP_SAPI == 'cli' && isset($argv[0]) && $argv[0] == basename(__FILE__))
- {
- StatisticClient::tick("TestModule", 'TestInterface');
- usleep(rand(10000, 600000));
- $success = rand(0,1);
- $code = rand(300, 400);
- $msg = '这个是测试消息';
- var_export(StatisticClient::report('TestModule', 'TestInterface', $success, $code, $msg));;
- }
|