标签:
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.jd.test</groupId> <artifactId>test-demo</artifactId> <packaging>war</packaging> <version>1.0-SNAPSHOT</version> <name>test-demo Maven Webapp</name> <url>http://maven.apache.org</url> <properties> <junit.version>4.12</junit.version> <zkclient.version>2.1.1</zkclient.version> <zookeeper.version>3.4.6</zookeeper.version> <slf4j-log4j12.version>1.7.12</slf4j-log4j12.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>${junit.version}</version> <!--<scope>test</scope>--> </dependency> <!-- <dependency> <groupId>com.github.adyliu</groupId> <artifactId>zkclient</artifactId> <version>${zkclient.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.6.1</version> <scope>compile</scope> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.6.1</version> <scope>compile</scope> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.16</version> <scope>compile</scope> </dependency> --> <!--zookeeper java客户端--> <dependency> <groupId>org.apache.zookeeper</groupId> <artifactId>zookeeper</artifactId> <version>${zookeeper.version}</version> <exclusions> <exclusion> <groupId>jline</groupId> <artifactId>jline</artifactId> </exclusion> <exclusion> <groupId>io.netty</groupId> <artifactId>netty</artifactId> </exclusion> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> </exclusion> <exclusion> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> </exclusion> <exclusion> <groupId>log4j</groupId> <artifactId>log4j</artifactId> </exclusion> </exclusions> </dependency> <!--日志相关--> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j-log4j12.version}</version> </dependency> </dependencies> <build> <finalName>test-demo</finalName> </build> </project>
log4j.properties
log4j.rootCategory=info,stdout log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.encoding=utf-8 log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=[%p]%d{yyyy-MM-dd HH:mm:ss} (%F:%L) %m%n
java类
package com.jd.test.zk; import org.apache.zookeeper.*; import org.apache.zookeeper.data.ACL; import org.apache.zookeeper.data.Id; import org.apache.zookeeper.data.Stat; import org.apache.zookeeper.server.auth.DigestAuthenticationProvider; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.sql.Timestamp; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.List; /** * zookeeper java客户端学习 * Created by cuize on 2015/8/13. */ public class ZkTest { private final Logger logger = LoggerFactory.getLogger(ZkTest.class); private DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private String address = "127.0.0.1:8080"; private Integer timeOut = 600000; private String path; private ZooKeeper zooKeeper; private Watcher watcher; //测试权限控制的参数 private String auth_type; private String auth; private String p; @Before public void init() { try { auth_type = "digest"; auth = "joey:some"; p = "/acl_digest"; path = "/test"; watcher = new Watcher() { public void process(WatchedEvent event) { logger.info("watcher info..." + event.toString()); } }; zooKeeper = new ZooKeeper(address, timeOut, watcher); logger.info("zookeeper注册成功..."); } catch (IOException e) { logger.error("初始化zookeeper失败...", e); } } //@Test public void add() { try { watcher = new Watcher() { public void process(WatchedEvent event) { logger.info("exists watcher..." + event.toString()); } }; Stat stat = zooKeeper.exists(path, true);//stat代表节点信息 //如果path不存在 返回null logger.info(stat.toString()); if (stat != null) { byte[] bytes = zooKeeper.getData(path, true, stat); String result = new String(bytes, "UTF-8"); logger.info("getData ersult..." + result); logger.info("getData stat..." + stat.toString()); } } catch (Exception e) { logger.error(path + "是否存在出错..", e); } } //此方法不建议使用 //@Test public void aclAuthCreate() { zooKeeper.addAuthInfo(auth_type, auth.getBytes()); try { zooKeeper.create(p, "hello".getBytes(), ZooDefs.Ids.CREATOR_ALL_ACL, CreateMode.PERSISTENT); } catch (Exception e) { logger.error("权限控制创建节点出错...", e); } } //@Test public void aclAuthGet() { zooKeeper.addAuthInfo(auth_type, auth.getBytes()); Stat stat = new Stat(); try { zooKeeper.getData(p, null, stat); logger.info(p + "创建时间" + (df.format(new Timestamp(stat.getCtime())))); } catch (Exception e) { logger.error("获取权限控制节点数据异常...", e); } } //实现创建一个节点,给不同用户赋予不同权利 //@Test public void testAcl() { try { List<ACL> acls = new ArrayList<ACL>(2); Id id1 = new Id("digest", DigestAuthenticationProvider.generateDigest("admin:admin123")); ACL acl1 = new ACL(ZooDefs.Perms.ALL, id1); Id id2 = new Id("digest", DigestAuthenticationProvider.generateDigest("guest:guest123")); ACL acl2 = new ACL(ZooDefs.Perms.READ, id2); acls.add(acl1); acls.add(acl2); zooKeeper.create("/testAcl", "testAclValue".getBytes(), acls, CreateMode.PERSISTENT); } catch (Exception e) { logger.error("测试zookeeper权限出错...",e); } } //测试watcher //@Test public void testWatcher() { try { DefaultWatcher defaultWatcher = new DefaultWatcher(); ExistsWatcher existsWatcher = new ExistsWatcher(); String p = "/watcher"; zooKeeper.register(defaultWatcher);//通过构造方法或者register指定的watcher一直有效 Stat stat = zooKeeper.exists(p, existsWatcher);//这种方式的watcher只生效一次 zooKeeper.create(p, p.getBytes(), ZooDefs.Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);//触发上一步设置的watcher //exists watcher=true 方式不会触发 stat = zooKeeper.exists(p, true); byte[] b = zooKeeper.getData(p, true, stat); System.out.println(new String(b)); stat = zooKeeper.exists(p, true); zooKeeper.setData(p, "Iloveyou".getBytes(), stat.getVersion()); //set watcher方式会触发 stat = zooKeeper.exists(p, existsWatcher); zooKeeper.delete(p, stat.getVersion()); } catch(Exception ex) { ex.printStackTrace(); } } //测试异步调用getData @Test public void testSync(){ String p = "/lf";//已经在zookeeper中创建此节点 zooKeeper.getData(p, false, new AsyncCallback.DataCallback() { public void processResult(int rc, String path, Object ctx, byte[] data, Stat stat) { logger.info(path+"值为"+new String(data)); logger.info("外部参数传递:"+ctx); } }, "hello world!"); } @After public void destory() { if (zooKeeper != null) { try { zooKeeper.close(); logger.info("关闭zookeeper"); } catch (InterruptedException e) { logger.error("关闭zookeeper异常..", e); } } } class ExistsWatcher implements Watcher { public void process(WatchedEvent event) { System.out.println("---------------------------"); System.out.println("setting by exist watcher"); System.out.println("path is : " + event.getPath()); System.out.println("type is : " + event.getType()); System.out.println("state is : " + event.getState()); System.out.println("---------------------------"); } } class DefaultWatcher implements Watcher { public void process(WatchedEvent event) { System.out.println("=====>Default Watch Event,patch:" + event.getPath()+",type:"+event.getType()); } } }
标签:
原文地址:http://my.oschina.net/u/2418042/blog/492230