disruptor简介
配景
Disruptor是英海外汇生意业务公司LMAX开拓的一个高机能行列,研发的初志是办理内存行列的延迟问题。与Kafka(Apache Kafka)、RabbitMQ(RabbitMQ)用于处事间的动静行列差异,disruptor一般用于线程间动静的通报。基于Disruptor开拓的系统单线程能支撑每秒600万订单,2010年在QCon演讲后,得到了业界存眷。2011年,企业应用软件专家Martin Fowler专门撰写长文先容The LMAX Architecture。同年它还得到了Oracle官方的Duke大奖。其他关于disruptor的配景就不在此多言,可以本身google。
官方资料
disruptor github wiki有关于disruptor相关观念和道理的先容,该wiki已经好久没有更新。像Design and Implementation,对付想相识disruptor的人是很有吸引力的,可是只有题目没有内容,照旧很遗憾的。本文稍后会对其内部道理做一个先容性的描写。
disruptor github wiki:
Home · LMAX-Exchange/disruptor Wiki
disruptor github:
LMAX-Exchange/disruptor: High Performance Inter-Thread Messaging Library
这个处所也有许多不错的资料:Disruptor by LMAX-Exchange
机能
disruptor是用于一个JVM中多个线程之间的动静行列,浸染与ArrayBlockingQueue有相似之处,可是disruptor从成果、机能都远好于ArrayBlockingQueue,当多个线程之间通报大量数据或对机能要求较高时,可以思量利用disruptor作为ArrayBlockingQueue的替代者。
官方也对disruptor和ArrayBlockingQueue的机能在差异的应用场景下做了比拟,本文列出个中一组数据,数据中P代表producer,C代表consumer,ABS代表ArrayBlockingQueue:
完整的官方机能测试数据在Performance Results · LMAX-Exchange/disruptor Wiki可以看到,机能测试的代码已经包括在disruptor的代码中,劳务派遣管理系统,你完全可以git下来在本身的主机上测试一下看看
如何利用
单出产者,单消费者
//声明disruptor中事件范例及对应的事件工场 private class LongEvent { private long value; public LongEvent() { this.value = 0L; } public void set(long value) { this.value = value; } public long get() { return this.value; } } private EventFactory<LongEvent> eventFactory = new EventFactory<LongEvent>() { public LongEvent newInstance() { return new LongEvent(); } }; //声明disruptor, private int ringBufferSize = 1024; private Executor executor = Executors.newFixedThreadPool(8); private Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(eventFactory, ringBufferSize, executor); //pubisher逻辑,将原始数据转换为event,publish到ringbuffer private class Publisher implements EventTranslatorOneArg<LongEvent , String> { public void translateTo(LongEvent event, long sequence, String arg0) { event.set(Long.parseLong(arg0)); } } //consumer逻辑,获取event举办处理惩罚 private class Consumer implements EventHandler<LongEvent> { public void onEvent(LongEvent event, long sequence, boolean endOfBatch) throws Exception { long value = event.get(); int index = (int) (value % Const.NUM_OF_FILE); fileWriter[index].write("" + value + "\n"); if(value == Long.MAX_VALUE) { isFinish = true; } } } //注册consumer启动disruptor disruptor.handleEventsWith(new Consumer()); disruptor.start(); //获取disruptor的ringbuffer,用于出产数据 private RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer(); ringBuffer.publishEvent(new Publisher(), line);
多出产者
多出产者的窜改相对简朴,只需将disruptor的声明换一个结构函数即可,可是多出产者ringbuffer的处理惩罚逻辑完全差异,只是这些差异对利用者透明,本文将在后边接头单出产者,多出产者ringbuffer逻辑的差异
private Disruptor<LongEvent> disruptor1 = new Disruptor<LongEvent>(eventFactory, ringBufferSize, executor, ProducerType.MULTI, new BlockingWaitStrategy());
多消费者
多消费者的环境分为两类:
广播
假设今朝有handler1,handler2,handler3三个消费者处理惩罚一批动静,每个动静都要被三个消费者处理惩罚到,三个消费者无依赖干系,则如下所示即可
disruptor.handleEventsWith(handler1,handler2,handler3);