PHP code example of lishelun / nsq

1. Go to this page and download the library: Download lishelun/nsq library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

lishelun / nsq example snippets


use Nsq\Producer;

$producer = Producer::create(address: 'tcp://nsqd:4150');

// Publish a message to a topic
$producer->publish('topic', 'Simple message');

// Publish multiple messages to a topic (atomically) 
$producer->publish('topic', [
    'Message one',
    'Message two',
]);

// Publish a deferred message to a topic
$producer->publish('topic', 'Deferred message', delay: 5000);

use Nsq\Consumer;
use Nsq\Message;

$consumer = Consumer::create(
    address: 'tcp://nsqd:4150', 
    topic: 'topic',
    channel: 'channel',
    onMessage: static function (Message $message): Generator {
        yield $message->touch(); // Reset the timeout for an in-flight message        
        yield $message->requeue(timeout: 5000); // Re-queue a message (indicate failure to process)        
        yield $message->finish(); // Finish a message (indicate successful processing)        
    },
);

use Nsq\Lookup;
use Nsq\Message;

$lookup = new Lookup('http://nsqlookupd0:4161');
$lookup = new Lookup(['http://nsqlookupd0:4161', 'http://nsqlookupd1:4161', 'http://nsqlookupd2:4161']);

$callable = static function (Message $message): Generator {
    yield $message->touch(); // Reset the timeout for an in-flight message        
    yield $message->requeue(timeout: 5000); // Re-queue a message (indicate failure to process)        
    yield $message->finish(); // Finish a message (indicate successful processing)        
};

$lookup->subscribe(topic: 'topic', channel: 'channel', onMessage: $callable);  
$lookup->subscribe(topic: 'anotherTopic', channel: 'channel', onMessage: $callable);

$lookup->unsubscribe(topic: 'local', channel: 'channel');
$lookup->stop(); // unsubscribe all