十七、curator recipes之DistributedPriorityQueue
简介
官方文档:http://curator.apache.org/curator-recipes/distributed-priority-queue.html
代码示例
import org.apache.curator.framework.CuratorFramework; import org.apache.curator.framework.CuratorFrameworkFactory; import org.apache.curator.framework.recipes.queue.*; import org.apache.curator.framework.state.ConnectionState; import org.apache.curator.retry.ExponentialBackoffRetry; import java.io.UnsupportedEncodingException; public class DistributedPriorityQueueDemo { private static CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(3000, 2)); private static String path = "/queue/0003"; private static DistributedPriorityQueue<String> queue; static { client.start(); } public static void main(String[] args) throws Exception { QueueConsumer<String> consumer = new QueueConsumer<String>() { @Override public void stateChanged(CuratorFramework curatorFramework, ConnectionState connectionState) { System.out.println("state changed"); } @Override public void consumeMessage(String s) { System.out.println("消费数据:" + s); } }; queue = QueueBuilder.builder(client, consumer, new QueueSerializer<String>() { @Override public byte[] serialize(String s) { try { return s.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } @Override public String deserialize(byte[] bytes) { return new String(bytes); } }, path).buildPriorityQueue(10); queue.start(); System.out.println("queue built"); queue.put("a", 2); queue.put("b", 1); System.out.println("put ended"); Thread.sleep(100); queue.close(); Thread.sleep(50000); client.close(); } }