subscriber.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Created by PhpStorm.
  5. * User: stanley-king
  6. * Date: 2017/2/24
  7. * Time: 下午5:04
  8. */
  9. namespace message;
  10. use Thread;
  11. use Log;
  12. use Redis;
  13. use Exception;
  14. use StatesHelper;
  15. class subscriber extends Thread
  16. {
  17. private $mConfig;
  18. private $mStates;
  19. public function __construct($states)
  20. {
  21. $this->mConfig = C('redis');
  22. $this->mStates = $states;
  23. }
  24. function run()
  25. {
  26. @date_default_timezone_set('Asia/Shanghai');
  27. while (true)
  28. {
  29. try
  30. {
  31. $redis = new Redis; //多线程版本不能定义为类成员变量,可能和redis库的设计有关。
  32. $ret = $redis->pconnect($this->mConfig['master']['host'], $this->mConfig['master']['port']);
  33. $redis->setOption(Redis::OPT_READ_TIMEOUT, 3600);
  34. if($ret == false) {
  35. Log::record("redis 连接失败.",Log::ERR);
  36. } else {
  37. Log::record("redis 连接成功.",Log::DEBUG);
  38. }
  39. Log::record("Message thread start run....",Log::DEBUG);
  40. $redis->subscribe(all_channels(), function ($redis,$chan,$msg)
  41. {
  42. $this->synchronized(function() use ($redis,$chan,$msg)
  43. {
  44. handler_redis($redis,$chan,$msg);
  45. });
  46. });
  47. Log::record("Message thread quit....",Log::DEBUG);
  48. }
  49. catch (Exception $ex)
  50. {
  51. Log::record("subscriber quit err={$ex->getMessage()} code={$ex->getCode()}");
  52. }
  53. }
  54. }
  55. public function dispatch($channel,$msg)
  56. {
  57. Log::record("subscriber dispatch ch={$channel} msg={$msg}",Log::DEBUG);
  58. if(empty($msg)) return false;
  59. $msg = unserialize($msg);
  60. if($msg == false || !is_array($msg)) {
  61. return false;
  62. }
  63. $ret = true;
  64. if($channel == 'ch_index') {
  65. StatesHelper::onIndex($this->mStates,$msg);
  66. } elseif($channel == 'searcher') {
  67. StatesHelper::onSearcher($this->mStates,$msg);
  68. } elseif($channel == 'activity') {
  69. StatesHelper::onActivity($this->mStates,$msg);
  70. } elseif($channel == 'goods') {
  71. StatesHelper::onGoods($this->mStates,$msg);
  72. } else {
  73. $ret = false;
  74. }
  75. return $ret;
  76. }
  77. }