Ticket.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace PhpLife\Frame\Library;
  3. /**
  4. * 发号器类
  5. */
  6. class Ticket extends \PhpLife\Frame\Library
  7. {
  8. const TICKET_START_TIME = 1262275200; // 2010-1-1 00:00:00
  9. const DEFAULT_SERVER_ID = 9; //使用微秒发出去的id编号
  10. const TICKET_KEY_PREFIX = 'id_';
  11. /**
  12. * 获取发号
  13. * @param $businessId
  14. * @return mixed
  15. * @throws \Exception
  16. */
  17. public static function getTicket($businessId = 0)
  18. {
  19. // for ($i = 0; $i < 10; $i++) {
  20. // $result = self::getFromRemote($businessId);
  21. // if ($result) {
  22. // return $result;
  23. // }
  24. // }
  25. // \PhpLife\Frame\Logger::crit('ticket error', 'ticket');
  26. $result = self::getTicketFromTimestamp();
  27. return $result;
  28. }
  29. /**
  30. * 从发号器获取号码
  31. * @param $businessId
  32. * @return mixed
  33. */
  34. protected static function getFromRemote($businessId = 0)
  35. {
  36. $configClass = 'Memcache\\Ticket';
  37. $memcached = new Memcache($configClass);
  38. $connection = $memcached->getConnection();
  39. $key = self::TICKET_KEY_PREFIX . intval($businessId);
  40. $result = $connection->get($key);
  41. return $result;
  42. }
  43. /**
  44. * 获取发号
  45. * @return int
  46. */
  47. protected static function getTicketFromTimestamp()
  48. {
  49. $time = self::getTimestamp();
  50. $time[0] = $time[0] - self::TICKET_START_TIME;
  51. $time = implode('', $time);
  52. $rand = sprintf('%03d', rand(0, 999));
  53. $code = $time . $rand . self::DEFAULT_SERVER_ID;
  54. return $code;
  55. }
  56. /**
  57. * 获取时间戳信息,
  58. * 返回值分别是秒,毫秒,微秒
  59. * @return array
  60. */
  61. protected static function getTimestamp()
  62. {
  63. list($microTime, $seconds) = explode(" ", microtime());
  64. $microTime = intval($microTime * 1000000);
  65. $timeStamp = array(
  66. 0 => $seconds,
  67. 1 => substr($microTime, 0, 3),
  68. 2 => substr($microTime, 3, 3),
  69. );
  70. return $timeStamp;
  71. }
  72. }