问题
What is the purpose of getSocket(type,persistence_id,callback) in zeromq?
Will it create a new socket if one doesn't exist with the same persistence_id in the context?
This is my client
function newSocket(ZMQSocket $soc, $pid) {
echo $pid;
}
$context = new ZMQContext();
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'mysocket', 'newSocket');
$socket->setSockOpt(ZMQ::SOCKOPT_HWM,5);
$socket->connect("tcp://172.16.136.59:5555");
for($i=0;$i<10;$i++)
{
var_dump($socket->send("hai",ZMQ::MODE_NOBLOCK));
sleep(2);
}
How many ever times I run this client simultaneously[nth client after n-1th client started], the callback is getting executed. Is this the desired behavior? What are all the situations, where the socket structure will be reused?
回答1:
What persistance does is signal the memory allocator to use the persistent memory allocation functions, which will alloc the context (and if you ask, any sockets) in a way that wont go away at the end of the request, but will last the lifetime of a PHP process. It sort of works the same way as some of the connection pooling libs, if that makes sense. The callback will be used on the first time the socket is created. Persistance needs to be set in the context, for example:
<?php
function newSocket(ZMQSocket $soc, $pid) {
echo "Creating New Socket \n", $pid, "\n";
}
echo "=========Creating without persistence ==========\n";
$context = new ZMQContext(1, false);
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'mysocket', 'newSocket');
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'mysocket', 'newSocket');
echo "========Creating with persistence ==========\n";
$context = new ZMQContext(1, true);
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'mysocket', 'newSocket');
$socket = $context->getSocket(ZMQ::SOCKET_PUSH, 'mysocket', 'newSocket');
Will give you
# php -dextension=zmq.so test.php
=========Creating without persistence ==========
Creating New Socket
mysocket
Creating New Socket
mysocket
========Creating with persistence ==========
Creating New Socket
mysocket
In the first instance, with false to persistance, the socket is recreated each time, and the callback fired. In the second, with persistance on, the socket is just returned, and the callback not triggered.
来源:https://stackoverflow.com/questions/7952209/zmq-getsocket-method