Zookeeper学习2:Java编写访问的客户端 错误: 找不到或无法加载主类
代码按《ZooKeeper分布式过程协同技术详解》中编写:
需要先设置CLASSPATH ,可以在~/.bashrc 或者~/.bash_profile 中:添加:
export ZOOBINDIR=${ZOOKEEPER_HOME}/bin,ZOOKEEPER_HOME就是zookeeper的包位置
然后运行:. zkEnv.sh
echo $CLASSPATH 看看变化
package zkWatcher; import org.apache.zookeeper.ZooKeeper; import org.apache.zookeeper.CreateMode; import org.apache.zookeeper.KeeperException; import org.apache.zookeeper.WatchedEvent; import org.apache.zookeeper.Watcher; import org.apache.zookeeper.ZooDefs; import java.io.IOException; import java.util.Random; public class Master implements Watcher{ ZooKeeper zk; String hostPort; Master(String hostPort){ this.hostPort = hostPort; } void startZK() throws IOException { zk = new ZooKeeper(hostPort,15000,this); try { runForMaster(); } catch (KeeperException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } void closeZK() throws InterruptedException { zk.close(); } void runForMaster() throws KeeperException, InterruptedException { Random rand = new Random(); String serverId = Integer.toHexString(rand.nextInt()) ; zk.create("/master", serverId.getBytes(),ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL ); } public static void main(String[] args) throws Exception { // TODO Auto-generated method stub Master m = new Master(args[0]); m.startZK(); System.out.println("load"); Thread.sleep(10000); //m.closeZK(); } @Override public void process(WatchedEvent event) { // TODO Auto-generated method stub System.out.println(event); } }
编译的时候在zkWatcher 目录下面:javac -cp $CLASSPATH Master.java
可以正常生成Master.class 文件
运行:javac -cp $CLASSPATH Master 127.0.0.1:2181
时会报:错误: 找不到或无法加载主类 Master
这个时候因为 Master.java带了包名,回退到上一级目录就可以通过了
java -cp $CLASSPATH zkWatcher/Master 127.0.0.1:2181