Zookeeper Operation Tool Class

Source: Internet
Author: User

Package Com.carelink.rpc.registry.client.util;import Java.net.inetaddress;import java.net.UnknownHostException; Import Java.util.list;import Java.util.map;import Java.util.concurrent.executorservice;import Java.util.concurrent.executors;import Org.apache.curator.framework.curatorframework;import Org.apache.curator.framework.curatorframeworkfactory;import Org.apache.curator.framework.api.GetChildrenBuilder ; Import Org.apache.curator.framework.api.getdatabuilder;import Org.apache.curator.framework.recipes.cache.pathchildrencache;import Org.apache.curator.framework.recipes.cache.pathchildrencachelistener;import Org.apache.curator.framework.recipes.cache.pathchildrencache.startmode;import Org.apache.curator.framework.state.connectionstate;import Org.apache.curator.framework.state.connectionstatelistener;import Org.apache.curator.retry.retryntimes;import Org.apache.curator.utils.zkpaths;import Org.apache.zookeeper.createmode;import Org.apache.zookeeper.data.Stat; Import Com.carelink.rpc.registRy.client.zkclient;import Com.carelink.rpc.registry.client.zkconfig;import Com.carelink.rpc.registry.client.factory.zkclientservicefactory;import Com.google.common.base.charsets;import Com.google.common.base.objects;import Com.google.common.base.strings;import Com.google.common.collect.Maps; public class Rpcregisteryservice {public static final int PROCESS = Runtime.getruntime (). Availableprocessors ();p rivate Rpcregisteryservice () {}private static class Singletonholder {static final Rpcregisteryservice instance = new Rpcregister Yservice ();} public static Rpcregisteryservice instance () {return singletonholder.instance;} Private Curatorframework zkclient = Null;public curatorframework getzkclient () {return zkclient;} private void Setzkclient (Curatorframework zkclient) {this.zkclient = zkclient;} /** * Connect ZK Create initial * * @param address * address * @param timeout * Time Out * @param namespace * Name empty * @param Group * Group * @param groupval * Group node value * @param noDe * node * @param nodeval * node value */public void Connectzookeeper (string address, int timeout, string na Mespace, String group, String groupval,string node, string nodeval) {if (getzkclient ()! = null) {return;} Curatorframeworkfactory.builder Builder = Curatorframeworkfactory.builder (); builder.connectstring (address). CONNECTIONTIMEOUTMS (timeout). SESSIONTIMEOUTMS (timeout). Retrypolicy (New Retryntimes (Integer.max_value,)); if ( ! Strings.isnullorempty (namespace)) {Builder.namespace (namespace);} Setzkclient (Builder.build ()); Rpcconnectionstatelistener listener = new Rpcconnectionstatelistener (group, Groupval, node, nodeval); Getzkclient (). Getconnectionstatelistenable (). AddListener (listener); Getzkclient (). Start ();//inject Startregisterserver (group, Groupval, node, nodeval);} private void Startregisterserver (string group, string Groupval, String node, string nodeval) {Registergroup (group, GROUPV AL); Registernode (Group, node, nodeval);} public boolean Registergroup (string group, string Groupval) {return CreateNode ("/" + Group, Groupval, createmode.persistent);//Create a persistent}public boolean registernode (String g  Roup, String node, string nodeval) {return CreateNode ("/" + Group + "/" + node, nodeval, createmode.ephemeral_sequential); Create temporary}//set path change listen public void Listenerpathchildren (String Group,pathchildrencachelistener listener) throws Exception {Executorservice pool = executors.newfixedthreadpool (PROCESS * 2); @SuppressWarnings ("Resource") Pathchildrencache Childrencache = new Pathchildrencache (Getzkclient (), "/" + group, True); Childrencache.start (startmode.post_ initialized_event); childrencache.getlistenable (). AddListener (listener, pool);} /** * Create node * * @param nodeName * @param value * @param createmode * @return * @throws Exception */public boolean Createno De (string nodeName, String value, Createmode Createmode) {Boolean suc = False;if (getzkclient () = = null) {return suc;} try {stat stat = getzkclient (). Checkexists (). Forpath (NodeName); if (Stat = = null) {String Opresult = The null;//node determines that the value is not NULL if (Strings.isnullorempty (value)) {Opresult = Getzkclient (). Create (). creatingparentsifneeded (). Withmode (Createmode). Forpath (NodeName);} else {Opresult = Getzkclient (). Create (). creatingparentsifneeded (). Withmode (Createmode). Forpath (NodeName, Value.getbytes (Charsets.utf_8));} suc = Objects.equal (NodeName, Opresult);}} catch (Exception e) {System.out.println ("Create node fail! Path: "+ NodeName +" value: "+ Value +" Createmode: "+ createmode.name ()); E.printstacktrace (); return suc;} return suc;} public void Destory () {if (getzkclient () ==null) {return;} Getzkclient (). Close ();} /** * Remove Node * * @param node * @return */public boolean Deletenode (String node) {if (getzkclient () = = null) {return false;} try {stat stat = getzkclient (). Checkexists (). Forpath (node); if (Stat! = null) {getzkclient (). Delete (). Deletingchildrenifneeded (). Forpath (node);} return true;} catch (Exception e) {System.out.println ("Delete node fail! Path: "+ node"; return false;}} /** * Gets the child node path and value under the specified node * @param nodE * @return */public map<string, string> getchildrendetail (String node) {if (getzkclient () = = null) {return null;} map<string, string> map = Maps.newhashmap (); try {getchildrenbuilder childrenbuilder = Getzkclient (). GetChildren ( ); list<string> children = childrenbuilder.forpath (node);  Getdatabuilder Databuilder = Getzkclient (). GetData (); if (children! = null) {for (string child:children) {string Proppath = Zkpaths.makepath (node, child); Map.put (Child, New String (Databuilder.forpath (Proppath), charsets.utf_8));}}} catch (Exception e) {System.out.println ("Get node Chilren list fail! Path: "+ node"; return null;} return map;} Class Rpcconnectionstatelistener implements Connectionstatelistener{private String Group; @SuppressWarnings ("Unused" ) private string Groupval;private string Node;private string Nodeval;public rpcconnectionstatelistener (string group, String groupval,string node,string nodeval) {this.groupval = Groupval;this.group = Group;this.node = Node;this.nodeVal = n OdevAl;} @Overridepublic void statechanged (Curatorframework CF, ConnectionState State) {if (state = = Connectionstate.lost) {// Re-registering while (true) {//only need to register the node, the group is already persistent//if (Registernode (Group, node, nodeval)) {break;}}}} Gets the native ippublic static string Getlocalhost (String type) {InetAddress addr = null;try {addr = Inetaddress.getlocalhost (); ("Address". Equals (Type)) {return Addr.gethostname (). ToString ();//Gets the native name}return addr.gethostaddress (). ToString ();//Get Native IP} catch ( Unknownhostexception e) {e.printstacktrace (); return "";}} public static void Main (string[] args) throws Exception {String address = " 192.168.200.34:2181,192.168.200.44:2181,192.168.200.64:2181 "; System.out.println (Zkconfig.forview ()); System.out.println (getlocalhost ("IP")); Zkclient.startzkregistery (address,5000); int i = 0;while (true) {try {System.out.println ( Zkclientservicefactory.getrpcclientservcie (0). Getserversbygroup (Zkconfig.getzkservergroup ()). Size ()); System.out.println (Zkclientservicefactory.getrpcclientservcie (0). Getserversbygroup (ZkconFig.getzkservergroup ())); Thread.Sleep (5000);} catch (Interruptedexception e) {e.printstacktrace ();} I++;if (i>10000) {break;}}}

}


Package Com.carelink.rpc.registry.server.util;import Java.net.inetaddress;import java.net.UnknownHostException; Import Java.util.list;import Java.util.map;import Org.apache.curator.framework.curatorframework;import Org.apache.curator.framework.curatorframeworkfactory;import Org.apache.curator.framework.api.GetChildrenBuilder ; Import Org.apache.curator.framework.api.getdatabuilder;import Org.apache.curator.framework.state.connectionstate;import Org.apache.curator.framework.state.connectionstatelistener;import Org.apache.curator.retry.retryntimes;import Org.apache.curator.utils.zkpaths;import Org.apache.zookeeper.createmode;import Org.apache.zookeeper.data.Stat; Import Com.carelink.rpc.registry.server.zkconfig;import Com.carelink.rpc.registry.server.zkservice;import Com.google.common.base.charsets;import Com.google.common.base.objects;import com.google.common.base.Strings; Import Com.google.common.collect.maps;public class Rpcregisteryservice {private Rpcregisteryservice () {}private Static CLass Singletonholder {static final Rpcregisteryservice instance = new Rpcregisteryservice ();} public static Rpcregisteryservice instance () {return singletonholder.instance;} Private Curatorframework zkclient = null;private curatorframework getzkclient () {return zkclient;} private void Setzkclient (Curatorframework zkclient) {this.zkclient = zkclient;} /** * Connect ZK Create initial * * @param address * address * @param timeout * Time Out * @param namespace * Name empty            * @param Group * Group * @param groupval * Group node values * @param node * nodes * @param nodeval * Node value */public void Connectzookeeper (string address, int timeout, string namespace, String group, string Groupval,stri NG node, String nodeval) {if (getzkclient () = null) {return;} Curatorframeworkfactory.builder Builder = Curatorframeworkfactory.builder ();//Exponentialbackoffretry: Retry the specified number of times, And the time to pause between retries increases gradually.//Retryntimes: Specifies the retry policy for the maximum number of retries//Retryonetime: Retry only//retryuntilelapsed: Retry until the specified time is reached Builder.conNectstring (address). CONNECTIONTIMEOUTMS (timeout). SESSIONTIMEOUTMS (timeout). Retrypolicy (New Retryntimes ( Integer.max_value)); if (! Strings.isnullorempty (namespace)) {Builder.namespace (namespace);} Setzkclient (Builder.build ()); Rpcconnectionstatelistener listener = new Rpcconnectionstatelistener (group, Groupval, node, nodeval); Getzkclient (). Getconnectionstatelistenable (). AddListener (Listener), Getzkclient (). Start ();//Injection Service Startregisterserver (group, Groupval, node, nodeval);} private void Startregisterserver (string group, string Groupval, String node, string nodeval) {Registergroup (group, GROUPV AL); Registernode (Group, node, nodeval);} public boolean Registergroup (string group, string groupval) {return CreateNode ("/" + Group, Groupval, Createmode.persiste  NT);//Create Persistent}public boolean Registernode (string group, String node, string nodeval) {return CreateNode ("/" + Group + "/" + node, nodeval, createmode.ephemeral_sequential); Create a temporary}/** * Create node * * @param nodeName * @param value * @param creAtemode * @return * @throws Exception */public boolean createnode (String nodeName, String value, Createmode createmode) {b Oolean suc = false;if (getzkclient () = = null) {return suc;} try {stat stat = getzkclient (). Checkexists (). Forpath (NodeName); if (Stat = = null) {String Opresult = null;//node determines that the value is not NULL if (S Trings.isnullorempty (value)) {Opresult = Getzkclient (). Create (). creatingparentsifneeded (). Withmode (Createmode). Forpath (nodeName);} else {Opresult = Getzkclient (). Create (). creatingparentsifneeded (). Withmode (Createmode). Forpath (NodeName, Value.getbytes (Charsets.utf_8));} suc = Objects.equal (NodeName, Opresult);}} catch (Exception e) {System.out.println ("Create node fail! Path: "+ NodeName +" value: "+ Value +" Createmode: "+ createmode.name ()); E.printstacktrace (); return suc;} return suc;} public void Destory () {if (getzkclient () ==null) {return;} Getzkclient (). Close ();} /** * Remove Node * * @param node * @return */public boolean Deletenode (String node) {if (getzkclient () = = null) {return false;} TRY {Stat stat = getzkclient (). Checkexists (). Forpath (node); if (Stat! = null) {getzkclient (). Delete (). Deletingchildrenifneeded (). Forpath (node);} return true;} catch (Exception e) {System.out.println ("Delete node fail! Path: "+ node"; return false;}} /** * Gets the child node path and value under the specified node * @param node * @return */public map<string, string> getchildrendetail (String node) {if (Getzk Client () = = null) {return null;} map<string, string> map = Maps.newhashmap (); try {getchildrenbuilder childrenbuilder = Getzkclient (). GetChildren ( ); list<string> children = childrenbuilder.forpath (node);  Getdatabuilder Databuilder = Getzkclient (). GetData (); if (children! = null) {for (string child:children) {string Proppath = Zkpaths.makepath (node, child); Map.put (Child, New String (Databuilder.forpath (Proppath), charsets.utf_8));}}} catch (Exception e) {System.out.println ("Get node Chilren list fail! Path: "+ node"; return null;} return map;} Class Rpcconnectionstatelistener implements Connectionstatelistener{private STring Group; @SuppressWarnings ("unused") private string Groupval;private string Node;private string nodeval;public Rpcconnectionstatelistener (String group, string groupval,string node,string nodeval) {this.groupval = Groupval; This.group = Group;this.node = Node;this.nodeval = Nodeval;} @Overridepublic void statechanged (Curatorframework CF, ConnectionState State) {if (state = = Connectionstate.lost) {// Re-registering the service while (true) {//only need to register the node, the group is already persistent if (Registernode (Group, node, nodeval)) {break;}}}} public static string Getlocalhost (String type) {InetAddress addr = null;try {addr = Inetaddress.getlocalhost (); Address ". Equals (Type)" {return Addr.gethostname (). ToString ();//Gets the native name}return addr.gethostaddress (). ToString ();/ Get native IP} catch (Unknownhostexception e) {e.printstacktrace (); return "";}} public static void Main (string[] args) {zkconfig.readconfig (); System.out.println (Zkconfig.forview ()); System.out.println (getlocalhost ("IP")); Zkservice.startzkregistery (); int i = 0;while (true) {try {thread.sleep);} CATCH (interruptedexception e) {e.printstacktrace ();} I++;if (i>10) {break;}} Zkservice.stopzkregistery ();}}



Zookeeper Operation Tool Class

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.