Advertisement
krot

rabbitmq_recv

Aug 23rd, 2020 (edited)
1,743
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.90 KB | None | 0 0
  1. <?php
  2. if(empty($argv[1]))exit(1);
  3. define('PROC_NAME', $argv[1]);
  4. define('LOCK_FILE', "/var/run/" . basename(PROC_NAME, ".php") . ".lock");
  5. if (!tryLock())die("Already running.\n");
  6. # remove the lock on exit (Control+C doesn't count as 'exit'?)
  7. register_shutdown_function('unlink', LOCK_FILE);
  8.  
  9.  
  10.  
  11. $pid = getmypid();
  12. if(!cli_set_process_title(PROC_NAME)){
  13.     echo "ERROR set_process_title::$pid...\n";
  14.     exit(1);
  15. }
  16.  
  17. require_once __DIR__ . '/vendor/autoload.php';
  18. use PhpAmqpLib\Connection\AMQPStreamConnection;
  19. use PhpAmqpLib\Message\AMQPMessage;
  20.  
  21. $queue_name='host:search1';
  22.  
  23.  
  24. $connection = new AMQPStreamConnection('host', 5672, 'guest', 'guest');
  25. $channel = $connection->channel();
  26.  
  27. $channel->queue_declare($queue_name, false, true, false, false);
  28.  
  29. echo " [*] Waiting for messages. To exit press CTRL+C\n";
  30.  
  31. $channel->basic_qos(null,1,null);
  32.                
  33.  
  34. $callback = function (AMQPMessage $msg) {
  35.   echo ' [x] Received ', $msg->body, "\n";
  36.    $msg->delivery_info['channel']->basic_ack($msg->delivery_info['delivery_tag']);
  37. };
  38.  
  39. $channel->basic_consume($queue_name, '',
  40. false,
  41. false, //подтвердить              
  42. false,
  43. false, $callback);
  44.  
  45. while ($channel->is_consuming()) {
  46. //while(count($channel->callbacks)) {
  47.     $channel->wait();
  48. }
  49.  
  50.  
  51.  
  52.  
  53. $channel->close();
  54. $connection->close();
  55.  
  56.  
  57.  
  58. #######################################
  59.  
  60. function tryLock()
  61. {
  62.     # If lock file exists, check if stale.  If exists and is not stale, return TRUE
  63.    # Else, create lock file and return FALSE.
  64.  
  65.     if (@symlink("/proc/" . getmypid(), LOCK_FILE) !== FALSE) # the @ in front of 'symlink' is to suppress the NOTICE you get if the LOCK_FILE exists
  66.        return true;
  67.  
  68.     # link already exists
  69.    # check if it's stale
  70.    if (is_link(LOCK_FILE) && !is_dir(LOCK_FILE))
  71.     {
  72.         unlink(LOCK_FILE);
  73.         # try to lock again
  74.        return tryLock();
  75.     }
  76.  
  77.     return false;
  78. }
  79.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement