PHP.mk документација

GearmanClient::addServer

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

gearmanclient.addserver.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека gearmanclient.addserver.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
GearmanClient::addServer

Референца за `gearmanclient.addserver.php` со подобрена типографија и навигација.

gearmanclient.addserver.php

GearmanClient::addServer

(PECL gearman >= 0.5.0)

GearmanClient::addServerДодајте сервер за задачи на клиентот

= NULL

public GearmanClient::addServer(string $host = null, int $port = 0, bool $setupExceptionHandler = true): bool

Додава сервер за задачи на список со сервери што можат да се користат за извршување задача. Овде не се случува I/O на сокети; серверот едноставно се додава на списокот.

Параметри

host
Име на хост на серверот за задачи.
port
Порта на серверот за задачи.

Вратени вредности

Патеката до PHP скриптата што треба да се провери. true на успех или false при неуспех.

Примери

Пример #1 Додавање два сервера за задачи

<?php

# Create our client object.
$gmclient= new GearmanClient();

# Add two job servers, the first on the default 4730 port
$gmclient->addServer("10.0.0.1");
$gmclient->addServer("10.0.0.2", 7003);

?>

Види Исто така

Белешки од корисници 8 белешки

jqv8gg681 на relay dot firefox dot com
3 години пред
Combining recommendations from brainreflex and iloveapplepie, as well as hours of testing. This avoids some bugs in cross versions of gearman across platforms. 
It steps though the server list and fails if all are inaccessible.
I also use the same override as "class SmartGearmanClient extends GearmanClient" for the clients.

<?php // WORKER
class SmartGearmanWorker extends GearmanWorker
{
    public $server = false;
    public function connect($servers = array( array('host' => '127.0.0.1', 'port' => '4730') ))
    {
        $connected = false;
        foreach ($servers as $server) {
            $c = new GearmanClient();
            $c->addServer($server['host'], $server['port'], false);
    
            if (@$c->ping('ping')) {              
                $this->addServer($server['host'], $server['port']);
                $connected=true;
                $this->server = array(
                   'host'=>$server['host'],
                   'port'=>$server['port']
                );
                break; // Remove this to use last working server in list
            }
        }
        return $connected;
    }
}

echo "Starting\n";

# Add some servers
$servers = array(
    array('host' => '127.0.0.1', 'port' => '4730'),
    array('host' => '127.0.0.1', 'port' => '4731'),
    array('host' => '127.0.0.1', 'port' => '4732'),
    array('host' => '127.0.0.2', 'port' => '4730'),
    array('host' => '192.168.204.10', 'port' => '4730')
);

# Create our worker object.
$gmw= new SmartGearmanWorker();

if ($gmw->connect($servers)) {
    # Register function "reverseString" with the server. 
    $gmw->addFunction("reverseString", "reverseString_fn");

    print "Connected to {$gmw->server['host']}:{$gmw->server['port']}...\n";
    print "Waiting for jobs...\n";

    while ($gmw->work()) {
        if ($gmw->returnCode() != GEARMAN_SUCCESS) {
            echo "return_code: " . $gmw->returnCode() . "\n";
            break;
        }
    }

    echo "DONE\n";
} else {
    echo "Unable to connect to any gearman-job-servers.".PHP_EOL;
};

function reverseString_fn($job)
{
    echo "Received job: " . $job->handle() . "\n";
 
    $workload = $job->workload();
    $workload_size = $job->workloadSize();

    echo "Workload: $workload ($workload_size)\n";

    # Lets send some progress information
    for ($x= 0; $x < $workload_size; $x++) {
        echo "Sending status: " . ($x + 1) . "/$workload_size complete\n";
        $job->sendStatus($x+1, $workload_size);
        $job->sendData(substr($workload, $x, 1));    
        sleep(1);
    }

    $result= strrev($workload);
    echo "Result: $result\n";

    # Return what we want to send back to the client.
    return $result;
}
brainreflex на gmail dot com
пред 10 години
Amit, kosta250

I found a workaround to avoid the dead servers and continue with rest alive. 

<?php

$servers = array(
  array('host' => '127.0.0.1', 'port' => '4730'), 
  array('host' => '127.0.0.1', 'port' => '4731'), 
  array('host' => '127.0.0.1', 'port' => '4732'), 
  array('host' => '127.0.0.2', 'port' => '4730')
);

$client= new \GearmanClient();

foreach($servers as $server) {
  $c = new \GearmanClient();
  $c->addServer($server['host'], $server['port']);

  if (@$c->ping('ping')) {
    $client->addServer($server['host'], $server['port']);
  }
}

?>
iloveapplepie
пред 4 години
Sometimes you want the job server to start even if not all servers are available.  The reason is that if at a later point the server comes back gearman will use it, even if if failed during the add server operation. 

class SmartGearmanWorker extends GearmanWorker
{
    function addServer($host = '127.0.0.1', $port = 4730):bool
    {
        try {
            parent::addServer($host, $port);
            echo "\nSERVER $host WORKED";
        } catch (GearmanException $e) {
            echo "\nSERVER $host FAILED";
        }
        return true;
    }
}

class SmartGearmanClient extends GearmanClient 
{
    function addServer($host = '127.0.0.1', $port = 4730,  bool $setupExceptionHandler = false):bool
    {
        try {
            parent::addServer($host, $port, $setupExceptionHandler);
            echo "\nSERVER $host WORKED";
    } catch (GearmanException $e) {
                
            echo "\nSERVER $host FAILED"; //this does not get called even if the server is down
        }
        return true;
    }
}
kosta250 на gmail dot com
пред 10 години
Adding to Amit's comments,  I found that if the first server in the list of servers is down, then there seems to be no way to handle such a condition.
info на phpgangsta dot de
12 години пред
Since a few versions the port parameter is not optional anymore. I have version 1.1.1 of pecl/gearman compiled with libgearman 1.1.5, and I'm getting the following error:

send_packet(GEARMAN_COULD_NOT_CONNECT) Failed to send server-options packet -> libgearman/connection.cc:430

This happens if you don't provide a port.

Just set the second parameter to 4730 and it is working again.
michael на butlerpc dot net
пред 6 години
Prior to version 2.0.5, addServer DOES perform socket I/O indirectly because it calls set_server_option internally for an exception handler. This means if the server is unreachable you will get a GearmanException thrown at this point, and you may want to catch and handle it in your application.

<?php

$client->addServer('127.0.0.1', 4321); // does attempt a socket connection!

?>

Starting with version 2.0.5 of the extension, a third boolean argument (after $port) may be passed false in order to prevent this from happening.

<?php

$client->addServer('127.0.0.1', 4321, false); // no socket i/o happens here

?>
Амит
12 години пред
The addServer and addServers are unforgiving when any of the addresses are down. I tried using exceptions, but it does not quite work. Can you provide a working example to handle a list of servers where one or more is not running.

Thanks
На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.