php zookeeper 观察器不工作

php zookeeper watcher doesn't work

我正在尝试在 php 应用程序中使用 zookeeper,并且我已经完成了 get($path)/set($path, $value)/getChildren($path) 之后的大部分功能 https://github.com/andreiz/php-zookeeper,除了 watch_callback 功能不起作用。

我的 php 版本是 5.6.14 并且禁用了线程安全,我使用的是 apache2.4。

这是一些代码片段

class Zookeeper_Module {

    private $zookeeper;

    public function __construct(){
        $this->ci = & get_instance();
        $zookeeper_server = $this->ci->config->item('zookeeper_server');

        $this->zookeeper = new Zookeeper($zookeeper_server);
    }

    public function set($path, $value){
        $this->zookeeper->set($path, $value);
    }

    public function get($path, $watch_cb = null){
        return $this->zookeeper->get($path, $watch_cb);
    }

    public function get_watch_cb($event_type = '', $stat = '', $path = ''){
        error_log('hello from get_watcher_cb');
        $value = $this->get($path, array($this, 'get_watch_cb'));
        // update redis cache
        $this->ci->cache->redis->save('some cache key', $value);
    }
}

class MyTest{
    public function get(){
        $zookeeper = new Zookeeper_Module ();

        $value = $zookeeper->get( '/foo/bar', array (
            $zookeeper,
            'get_watch_cb'
        ) );
    }

    public function set(){
        $zookeeper = new Zookeeper_Module ();
        $zookeeper->set( '/foo/bar', 'some value');
    }
}

我可以成功获取或设置一个节点值,但是我无法捕捉到watch回调日志,也无法更新redis缓存。

我写了一个更简单的demo,和这个非常相似https://github.com/andreiz/php-zookeeper/wiki,watcher在这个demo中工作正常。

最显着的区别是

while( true ) {
    echo '.';
    sleep(2);
}

虽然 java 有一个托管观察者的 jvm 容器,但 php 没有容器来执行此操作,因此我们必须使用 while(true) 来保持观察者存活。

所以我在我的代码中添加了一个 while(true),现在 watcher 工作正常了。

但我不想在网络应用中添加一个可怕的while(true),所以最终的解决方案是添加一个java应用来与zookeeper通信并将结果保存在redis中,并且php 应用程序只是从 redis 中读取信息。