PHP code example of cat-sys / swoole-etcd

1. Go to this page and download the library: Download cat-sys/swoole-etcd 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/ */

    

cat-sys / swoole-etcd example snippets


// 连接到etcd服务器
$client = new KVClient('127.0.0.1:2379', []);
$client->connect(3, function($cli, $errCode) use ($client) {
    if($errCode != 0)
    {
        return;
    }
    $request = new PutRequest();
    $request->setKey("Hello");
    $request->setValue("test");
    $request->setPrevKv(true);
    $call = $client->Put($request);
    if($call)
    {
        $call->wait(function($result) use ($client){
            list($reply, $status) = $result;
            if($status != 200)
            {
                var_dump("Error");
                return;
            }
            if($reply instanceof \Etcdserverpb\PutResponse)
            {
                $item = $reply->getPrevKv();
                echo sprintf("update key[%s] success, pre value = %s\n", $item->getKey(), $item->getValue());
            }
        });
    } else {
        echo "request failed! Client closed\n";
    }
});

// 连接到etcd服务器
$watch_client = new WatchClient('127.0.0.1:2379', []);
$watch_client->connect(3, function(WatchClient $client, $errCode) {
    if($errCode != 0)
    {
        return;
    }
    $call = $client->Watch();
    $call->waiting(function($result) use ($call, $client){
        list($response, $status) = $result;
        if($response->getCreated() || $response->getCanceled())
        {
            return;
        }
        foreach ($response->getEvents() as $event)
        {
            $type = $event->getType();
            switch($type)
            {
                case 0:
                {
                    $kv = $event->getKv();
                    echo sprintf("Put key[%s] = %s\n",  $kv->getKey(), $kv->getValue());

                    break;
                }
                case 1:
                {
                    break;
                }
            }
        }
        $call->close();
    });
    $request = new \Etcdserverpb\WatchRequest();
    $create = new \Etcdserverpb\WatchCreateRequest();
    $create->setKey("Hello");
    $request->setCreateRequest($create);
    $call->push($request);
});