Zookeeper 간이 자바 클 라 이언 트

47955 단어 zookeeper
원생 표기 법:
package com.gcx.zookeeper;

import java.util.List;

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.Ids;
import org.apache.zookeeper.ZooKeeper;
import org.apache.zookeeper.data.Stat;
import org.junit.Before;
import org.junit.Test;

public class Tests {

	private static final String connectString ="node01:2181,node02:2181,node03:2181";
	private static final int sessionTimeout=60000;
  

	ZooKeeper zkClient = null;

	@Before
	public void init() throws Exception {
		zkClient = new ZooKeeper(connectString, sessionTimeout, new Watcher() {
			@Override
			public void process(WatchedEvent event) {
				//             (              )
				System.out.println(event.getType() + "---" + event.getPath());
				try {
					zkClient.getChildren("/", true);
				} catch (Exception e) {
				}
			}
		});

	}

		/**
		 *        
		 * 
		 * @throws InterruptedException
		 * @throws KeeperException
		 */

		//        zk 
		public void testCreate() throws KeeperException, InterruptedException {
			//   1:            2:        3:        4:     
			String nodeCreated = zkClient.create("/eclipse", "hellozk".getBytes(), Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
			//            ,     byte[]
		}

		//  znode    
		@Test	
		public void testExist() throws Exception{
			Stat stat = zkClient.exists("/eclipse", false);
			System.out.println(stat==null?"not exist":"exist");
			
			
		}
		
		//      
		@Test
		public void getChildren() throws Exception {
			List<String> children = zkClient.getChildren("/", true);
			for (String child : children) {
				System.out.println(child);
			}
			Thread.sleep(Long.MAX_VALUE);
		}

		//  znode   
		@Test
		public void getData() throws Exception {
			
			byte[] data = zkClient.getData("/eclipse", false, null);
			System.out.println(new String(data));
			
		}
		
		//  znode
		@Test
		public void deleteZnode() throws Exception {
			
			//  2:        ,-1        
			zkClient.delete("/eclipse", -1);
			
			
		}
		//  znode
		@Test
		public void setData() throws Exception {
			
			zkClient.setData("/app1", "imissyou angelababy".getBytes(), -1);
			
			byte[] data = zkClient.getData("/app1", false, null);
			System.out.println(new String(data));
			
		}
		
		
	}


curator 프레임 워 크 구현 zk 클 라 이언 트
1. maven 좌표
<dependencies>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-framework</artifactId>
            <version>2.12.0</version>
        </dependency>
        <dependency>
            <groupId>org.apache.curator</groupId>
            <artifactId>curator-recipes</artifactId>
            <version>2.12.0</version>
        </dependency>
        <dependency>
            <groupId>com.google.collections</groupId>
            <artifactId>google-collections</artifactId>
            <version>1.0</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-simple</artifactId>
            <version>1.7.25</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <!-- java     -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.2</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>
        </plugins>
    </build>

2. 테스트 코드:
package com.gcxzflgl;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.cache.ChildData;
import org.apache.curator.framework.recipes.cache.TreeCache;
import org.apache.curator.framework.recipes.cache.TreeCacheEvent;
import org.apache.curator.framework.recipes.cache.TreeCacheListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;
import org.junit.Test;

/**
 * @author gcxzf$
 * @version : CuratorTest$, v 0.1 2020/6/26$ 08:24$ gcxzf$ Exp$
 */

public class CuratorTest {

    /**
     *       
     * @throws Exception
     */
    @Test
    public void createNode() throws Exception {
        //      (                   )
        // param1     
        // param2     
        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000, 3);

        //       
        // param1   zk    
        // param2       
        // param3       
        // param4     
        CuratorFramework client = CuratorFrameworkFactory.newClient("node01:2181,node02:2181,node03:2181", 3000, 3000, retryPolicy);

        //     
        client.start();

        //      
        client
                .create()
                .creatingParentsIfNeeded() //       
                .withMode(CreateMode.PERSISTENT) //     
                .forPath("/hello","words".getBytes()); //    

        //     
        client.close();
    }


    /**
     *       
     */
    @Test
    public void updateNode() throws Exception {

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000,3);

        CuratorFramework client = CuratorFrameworkFactory.newClient("node01:2181,node02:2181,node03:2181", 3000, 3000, retryPolicy);

        client.start();

        //         
        client.setData().forPath("/hello","words_holiday".getBytes());

        client.close();
    }


    /**
     *       
     */
    @Test
    public void searchNode() throws Exception {

        RetryPolicy retryPolicy = new ExponentialBackoffRetry(3000,3);

        CuratorFramework client = CuratorFrameworkFactory.newClient("node01:2181,node02:2181,node03:2181", 3000, 3000, retryPolicy);

        client.start();

        //         
        byte[] bytes = client.getData().forPath("/hello");

        System.out.println("      :" + new String(bytes));

        client.close();
    }


    /**

     * zookeeper watch  

     * @throws Exception

     */
    @Test
    public void watchNode() throws Exception {

        RetryPolicy policy = new ExponentialBackoffRetry(3000, 3);

        CuratorFramework client = CuratorFrameworkFactory.newClient("node01:2181,node02:2181,node03:2181", policy);

        client.start();

        //     cache,   hello
        TreeCache treeCache = new TreeCache(client, "/hello");

        //          
        treeCache.getListenable().addListener(new TreeCacheListener() {
            @Override
            public void childEvent(CuratorFramework client, TreeCacheEvent event) throws Exception {
                ChildData data = event.getData();
                if(data !=null){
                    switch (event.getType()) {
                        case NODE_ADDED:
                            System.out.println("NODE_ADDED : "+ data.getPath() +"    :"+ new String(data.getData()));
                            break;
                        case NODE_REMOVED:
                            System.out.println("NODE_REMOVED : "+ data.getPath() +"    :"+ new String(data.getData()));
                            break;
                        case NODE_UPDATED:
                            System.out.println("NODE_UPDATED : "+ data.getPath() +"    :"+ new String(data.getData()));
                            break;
                        default:
                            break;
                    }
                }else{
                    System.out.println( "data is null : "+ event.getType());
                }
            }
        });
        //    
        treeCache.start();
        Thread.sleep(50000000);

    }
}

좋은 웹페이지 즐겨찾기