0    课程地址

https://coding.imooc.com/lesson/201.html#mid=12717

 

1    重点关注

1.1    本节内容

使用STS开发工具作为客户端连接zk服务端,详见3.1

 

 

1.2     连接方式参数说明

如下段zk原生class标注:

  • connectString

连接zk服务端的ip和端口(比如案例的 集群:127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002,单机:172.26.139.4:2181

 

  • sessionTimeout

session会话的超时时间

 

  • watcher:

watcher事件

a  本类直接实现 Watcher接口,传入本类,然后再process方法写业务逻辑即可(process方法是Watcher接口的抽象方法,所以子类可以重写)。  详见3.1

b  process方法入参 WatchedEvent 的属性 EventType 是枚举,可以判断事件类型,比如节点创建删除更改等,我已在下边标注对应的字典

 

  • sessionId和sessionPasswd(不常用)

旧的session断开后,可以用这两个字段恢复旧的会话

 

  • canBeReadOnly(不常用)

会话已经断开,原先会话的数据还是可以读取(因为断开连接了,原数据可能已经不是最新的了,读取的可能数据不一致,所以通常不用或者设置为false)

/**
     *
     *
     * @param connectString
     *            comma separated host:port pairs, each corresponding to a zk
     *            server. e.g. "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002"
     *            If the optional chroot suffix is used the example would look
     *            like: "127.0.0.1:3000,127.0.0.1:3001,127.0.0.1:3002/app/a"
     *            where the client would be rooted at "/app/a" and all paths
     *            would be relative to this root - ie getting/setting/etc...
     *            "/foo/bar" would result in operations being run on
     *            "/app/a/foo/bar" (from the server perspective).
     * @param sessionTimeout
     *            session timeout in milliseconds
     * @param watcher
     *            a watcher object which will be notified of state changes, may
     *            also be notified for node events
     * @param sessionId
     *            specific session id to use if reconnecting
     * @param sessionPasswd
     *            password for this session
     * @param canBeReadOnly
     *            (added in 3.4) whether the created client is allowed to go to
     *            read-only mode in case of partitioning. Read-only mode
     *            basically means that if the client can't find any majority
     *            servers but there's partitioned server it could reach, it
     *            connects to one in read-only mode, i.e. read requests are
     *            allowed while write requests are not. It continues seeking for
     *            majority in the background.
     *
     * @throws IOException in cases of network failure
     * @throws IllegalArgumentException if an invalid chroot path is specified
     */
    public ZooKeeper(String connectString, int sessionTimeout, Watcher watcher,
            long sessionId, byte[] sessionPasswd, boolean canBeReadOnly)
        throws IOException
    {
        LOG.info("Initiating client connection, connectString=" + connectString
                + " sessionTimeout=" + sessionTimeout
                + " watcher=" + watcher
                + " sessionId=" + Long.toHexString(sessionId)
                + " sessionPasswd="
                + (sessionPasswd == null ? "<null>" : "<hidden>"));

        watchManager.defaultWatcher = watcher;

        ConnectStringParser connectStringParser = new ConnectStringParser(
                connectString);
        HostProvider hostProvider = new StaticHostProvider(
                connectStringParser.getServerAddresses());
        cnxn = new ClientCnxn(connectStringParser.getChrootPath(),
                hostProvider, sessionTimeout, this, watchManager,
                getClientCnxnSocket(), sessionId, sessionPasswd, canBeReadOnly);
        cnxn.seenRwServerBefore = true; // since user has provided sessionId
        cnxn.start();
    }
            None (-1),
            NodeCreated (1),
            NodeDeleted (2),
            NodeDataChanged (3),
            NodeChildrenChanged (4);

 



 

2    课程内容

2.1    STS下载安装

 

  • 直接点击下载即可;
  • 直接解压文件即可使用;
  • 双击STS打开工具

参考:

https://blog.csdn.net/qq_42139049/article/details/129034837

 

 

 

3    Coding

3.1    通过STS连接zk服务端

  • 主类:
package com.imooc.zk.demo;

import java.util.concurrent.CountDownLatch;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @Title: ZKConnectDemo.java
 * @Package com.imooc.zk.demo
 * @Description: zookeeper 连接demo演示
 */
public class ZKConnect implements Watcher {
        
    final static Logger log = LoggerFactory.getLogger(ZKConnect.class);

    public static final String zkServerPath = "172.26.139.4:2181";
//    public static final String zkServerPath = "192.168.1.111:2181,192.168.1.111:2182,192.168.1.111:2183";
    public static final Integer timeout = 5000;
    
    public static void main(String[] args) throws Exception {
        /**
         * 客户端和zk服务端链接是一个异步的过程
         * 当连接成功后后,客户端会收的一个watch通知
         * 
         * 参数:
         * connectString:连接服务器的ip字符串,
         *         比如: "192.168.1.1:2181,192.168.1.2:2181,192.168.1.3:2181"
         *         可以是一个ip,也可以是多个ip,一个ip代表单机,多个ip代表集群
         *         也可以在ip后加路径
         * sessionTimeout:超时时间,心跳收不到了,那就超时
         * watcher:通知事件,如果有对应的事件触发,则会收到一个通知;如果不需要,那就设置为null
         * canBeReadOnly:可读,当这个物理机节点断开后,还是可以读到数据的,只是不能写,
         *                            此时数据被读取到的可能是旧数据,此处建议设置为false,不推荐使用
         * sessionId:会话的id
         * sessionPasswd:会话密码    当会话丢失后,可以依据 sessionId 和 sessionPasswd 重新获取会话
         */
        ZooKeeper zk = new ZooKeeper(zkServerPath, timeout, new ZKConnect());
        
        log.warn("客户端开始连接zookeeper服务器...");
        log.warn("连接状态:{}", zk.getState());
        
        new Thread().sleep(2000);
        
        log.warn("连接状态:{}", zk.getState());
    }

    @Override
    public void process(WatchedEvent event) {
        log.warn("接受到watch通知:{}", event);
    }
}

 

  • log4j.properties
log4j.rootLogger=WARN,console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.encoding=UTF-8
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss,SSS} [%t] [%l] - [%p] %m%n

 

  • 打印日志:

可见,已经打印出了process方法的内容

2024-03-29 07:30:34,843 [main] [com.imooc.zk.demo.ZKConnect.main(ZKConnect.java:43)] - [WARN] 客户端开始连接zookeeper服务器...
2024-03-29 07:30:34,848 [main] [com.imooc.zk.demo.ZKConnect.main(ZKConnect.java:44)] - [WARN] 连接状态:CONNECTING
2024-03-29 07:30:34,880 [main-EventThread] [com.imooc.zk.demo.ZKConnect.process(ZKConnect.java:53)] - [WARN] 接受到watch通知:WatchedEvent state:SyncConnected type:None path:null
2024-03-29 07:30:36,859 [main] [com.imooc.zk.demo.ZKConnect.main(ZKConnect.java:48)] - [WARN] 连接状态:CONNECTED

 

posted on 2024-03-29 08:14  菜鸟乙  阅读(26)  评论(0编辑  收藏  举报