七、curator recipes之阻塞队列SimpleDistributedQueue

简介

Java在单机环境实现了BlockQueue阻塞队列,与之类似的curator实现了分布式场景下的阻塞队列,SimpleDistributedQueue

官方文档:http://curator.apache.org/curator-recipes/simple-distributed-queue.html

javaDoc:http://curator.apache.org/apidocs/org/apache/curator/framework/recipes/queue/SimpleDistributedQueue.html

注意:zookeeper虽然可以实现队列,但是官方并不推荐使用zookeeper来做队列,主要原因在于zookeeper的空间大小设计的比较小,且对于大量数据的处理性能比较低,所以比较适合用户处理一些元数据以及应用协调,对于大量数据的建议使用其它分布式队列,比如redisson之类的,或者采用共享存储来实现。

代码示例

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.recipes.queue.SimpleDistributedQueue;
import org.apache.curator.retry.ExponentialBackoffRetry;

public class SimpleQueueDemo {
    private static CuratorFramework client = CuratorFrameworkFactory.newClient("localhost:2181", new ExponentialBackoffRetry(3000, 2));
    private static String path = "/queue/path001";
    public static void main(String[] args) throws InterruptedException {
        client.start();
        System.out.println("started");
        SimpleDistributedQueue queue = new SimpleDistributedQueue(client, path);
        new Thread(() -> {
            try {
                System.out.println("sleeping");
                Thread.sleep(3000);
                System.out.println("sleep end");
                new SimpleDistributedQueue(client, path).offer("lay".getBytes("utf-8"));
                System.out.println("offered");
            } catch (Exception e) {
                System.out.println("exception");
                e.printStackTrace();
            }
        }).start();
        System.out.println("polling");
        String data = null;
        try {
            data = new String(queue.take());
        } catch (Exception e) {
            e.printStackTrace();
        }
        System.out.println("data=" + data);
        client.close();
    }
}

输出结果

started
polling
sleeping
sleep end
offered
data=lay

主线程会阻塞直到offer了数据

 

转载于:https://www.cnblogs.com/lay2017/p/10264503.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值