This queue is distributed using the FIFO queue implemented by the zookeeper.
Package Fifo;import Java.util.collections;import Java.util.list;import java.util.concurrent.countdownlatch;import Org.apache.zookeeper.createmode;import Org.apache.zookeeper.watchedevent;import Org.apache.zookeeper.Watcher; Import Org.apache.zookeeper.watcher.event.keeperstate;import Org.apache.zookeeper.zoodefs.ids;import Org.apache.zookeeper.zoodefs;import Org.apache.zookeeper.zookeeper;import org.apache.zookeeper.data.stat;/** * FIFO queue implemented using ZooKeeper * @author LISG * */public class Zkfifo {private static final String HOSTS = "VM1";p rivate ZooKeeper Z K = null;private static final String parent_path = "/fifo";p rivate static final String seq_prefix = "seq-";p ublic Zkfifo () {try {final countdownlatch CDL = new Countdownlatch (1); ZK = new ZooKeeper (HOSTS,, New Watcher () {@Overridepublic voi D process (Watchedevent event) {if (KeeperState.SyncConnected.equals (Event.getstate ())) {Cdl.countdown ();}}); Cdl.await ();//Create parent node Stat stat = Zk.exists (Parent_path, false); if (stat = = null) {zk.create (PARent_path, "". GetBytes (), Ids.open_acl_unsafe, createmode.persistent);}} catch (Exception e) {System.out.println ("Zookeeper Cluster Connection failed! "); E.printstacktrace ();}} /** * Create order child nodes under parent node * @param data */public void push (String data) {if (data = = NULL) {data = "";} try {zk.create (Parent_path + "/" + Seq_prefix, Data.getbytes ("UTF-8"), ZooDefs.Ids.OPEN_ACL_UNSAFE, createmode.persistent_sequential);} catch (Exception e) {e.printstacktrace ();}} /** * Deletes the word first child node and returns its value * @return */public String pop () {try {final list<string> children = Zk.getchildren (Parent_pat H, False); if (Children.isempty ()) {return null;} Collections.sort (children); String Firstchildpath = Parent_path + "/" + children.get (0); final byte[] data = Zk.getdata (Firstchildpath, false, null); ZK . Delete (Firstchildpath,-1); return new String (data, "UTF-8");} catch (Exception e) {e.printstacktrace ();} return null;} public void Close () {try {this.zk.close ();} catch (Interruptedexception e) {e.printstacktrace ();}} public static void Main (string[] args{final Zkfifo FIFO = new Zkfifo ();/*for (int i=0; i<10; i++) {new Thread () {public void run () {Fifo.push ("data-" + UUI D.randomuuid (). toString (). Replace ("-", ""));};}. Start ();} */system.out.println (Fifo.pop ()); Fifo.close ();}}
Places to be improved: 1) Zookeeper exception handling, retry
Zookeeper application-FIFO queue distributed queue