StatisticClient.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. <?php
  2. require_once __DIR__ . '/../Lib/StatisticProtocol.php';
  3. /**
  4. * 统计客户端
  5. * @author workerman.net
  6. */
  7. class StatisticClient
  8. {
  9. /**
  10. * [module=>[interface=>time_start, interface=>time_start ...], module=>[interface=>time_start ..], ... ]
  11. * @var array
  12. */
  13. protected static $timeMap = array();
  14. /**
  15. * 模块接口上报消耗时间记时
  16. * @param string $module
  17. * @param string $interface
  18. * @return void
  19. */
  20. public static function tick($module = '', $interface = '')
  21. {
  22. return self::$timeMap[$module][$interface] = microtime(true);
  23. }
  24. /**
  25. * 上报统计数据
  26. * @param string $module
  27. * @param string $interface
  28. * @param bool $success
  29. * @param int $code
  30. * @param string $msg
  31. * @param string $report_address
  32. * @return boolean
  33. */
  34. public static function report($module, $interface, $success, $code, $msg, $report_address = '')
  35. {
  36. $report_address = $report_address ? $report_address : 'udp://127.0.0.1:55656';
  37. if(isset(self::$timeMap[$module][$interface]) && self::$timeMap[$module][$interface] > 0)
  38. {
  39. $time_start = self::$timeMap[$module][$interface];
  40. self::$timeMap[$module][$interface] = 0;
  41. }
  42. else if(isset(self::$timeMap['']['']) && self::$timeMap[''][''] > 0)
  43. {
  44. $time_start = self::$timeMap[''][''];
  45. self::$timeMap[''][''] = 0;
  46. }
  47. else
  48. {
  49. $time_start = microtime(true);
  50. }
  51. $cost_time = microtime(true) - $time_start;
  52. $bin_data = StatisticProtocol::encode($module, $interface, $cost_time, $success, $code, $msg);
  53. return self::sendData($report_address, $bin_data);
  54. }
  55. /**
  56. * 发送数据给统计系统
  57. * @param string $address
  58. * @param string $buffer
  59. * @return boolean
  60. */
  61. public static function sendData($address, $buffer)
  62. {
  63. $socket = stream_socket_client($address);
  64. if(!$socket)
  65. {
  66. return false;
  67. }
  68. return stream_socket_sendto($socket, $buffer) == strlen($buffer);
  69. }
  70. }
  71. if(PHP_SAPI == 'cli' && isset($argv[0]) && $argv[0] == basename(__FILE__))
  72. {
  73. StatisticClient::tick("TestModule", 'TestInterface');
  74. usleep(rand(10000, 600000));
  75. $success = rand(0,1);
  76. $code = rand(300, 400);
  77. $msg = '这个是测试消息';
  78. var_export(StatisticClient::report('TestModule', 'TestInterface', $success, $code, $msg));;
  79. }