1、安装成功zookeeper后,在zookeeper 的bin目录下有启动相应的启动脚本
启动server
./zkserver.sh start
启动client:(*注:cli需要安装java)
zkcli.sh
2、php实例:
get( '/test', array ($this, 'watcher' ) ); }}$zoo = new zookeeperdemo( '127.0.0.1:2181' );$zoo->get( '/test', array ($zoo, 'watcher' ) );while ( true ) { echo '.' ; sleep(2);}
leader与worker任务的分配:
class worker extends zookeeper { const container = '/cluster' ; protected $acl = array( array ( 'perms' => zookeeper:: perm_all, 'scheme' => 'world' , 'id' => 'anyone' ) ); private $isleader = false; private $znode ; public function __construct( $host = '', $watcher_cb = null , $recv_timeout = 10000 ) { parent:: __construct( $host, $watcher_cb, $recv_timeout ); } public function register() { if( ! $this->exists( self ::container ) ) { $this->create( self ::container , null, $this-> acl ); } $this->znode = $this->create( self ::container . '/w-' , null , $this->acl, zookeeper::ephemeral | zookeeper::sequence ); $this-> znode = str_replace( self ::container .'/' , '' , $this-> znode ); printf( i'm registred as: %s\n, $this-> znode ); $watching = $this->watchprevious(); if( $watching == $this-> znode ) { printf( nobody here, i'm the leader\n ); $this->setleader( true ); } else { printf( i'm watching %s\n , $watching ); } } public function watchprevious() { $workers = $this->getchildren( self ::container ); sort( $workers ); $size = sizeof( $workers ); for( $i = 0 ; $i if( $this-> znode == $workers[ $i ] ) { if ( $i > 0 ) { $this->get( self ::container . '/' . $workers[ $i - 1 ], array ( $this, 'watchnode' ) ); return $workers[ $i - 1 ]; } return $workers[ $i ]; } } throw new exception( sprintf( something went very wrong! i can't find myself: %s/%s, self ::container , $this-> znode ) ); } public function watchnode( $i, $type, $name ) { $watching = $this->watchprevious(); if( $watching == $this-> znode ) { printf( i'm the new leader!\n ); $this->setleader( true ); } else { printf( now i'm watching %s\n , $watching ); } } public function isleader() { return $this-> isleader ; } public function setleader($flag) { $this-> isleader = $flag; } public function run() { $this->register(); while( true ) { if( $this->isleader() ) { $this->doleaderjob(); } else { $this->doworkerjob(); } sleep( 2 ); } } public function doleaderjob() { echo leading\n ; } public function doworkerjob() { echo working\n ; }}$worker = new worker( '127.0.0.1:2181' );$worker->run();可以启动3个php进程,查看脚本的运行。
进程1:
[[email protected] zookeeper]# php -f worker.php
i'm registred as: w-0000000010
nobody here, i'm the leader
leading
进程2:
[[email protected] zookeeper]$ php -f worker.php
i'm registred as: w-0000000011
i'm watching w-0000000010
working
进程3:
[[email protected] zookeeper]$ php -f worker.php
i'm registred as: w-0000000012
i'm watching w-0000000011
working
ctrl + c 关闭leader进程后,会发现进程2与3会选举出新的leader