如何找到Lmax Disruptor钻石(一个生产商5消费者1总结)的例子?

时间:2015-02-03 07:38:50

标签: java disruptor-pattern lmax

我发现github中Lmax disrupter的用户指南非常简单,现在我有一个生产者和五个cosumer的问题,之后我需要得出消费者的结果,是否有任何demo,如何找到一个Lmax Disruptor钻石(一个生产商5消费者1总结)例子?

非常感谢!

1 个答案:

答案 0 :(得分:1)

您可以通过varags向Disruptor.handleEventsWith提供多个消费者。然后通过调用then(流畅的DSL)来注册结论。第二个调用确保事件在传递到结束步骤之前由所有使用者处理。

一个工作示例可能如下所示:

import com.lmax.disruptor.*;
import com.lmax.disruptor.dsl.*;
import java.util.concurrent.*;

public class Diamond {

    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        Disruptor<LongEvent> disruptor = new Disruptor<>(LongEvent::new, 1024, executor, ProducerType.SINGLE, new SleepingWaitStrategy());

        //register five consumers and a final conclude
        disruptor.handleEventsWith(new Consumer(1), new Consumer(2), new Consumer(3), new Consumer(4), new Consumer(5)).then(new Conclude());

        disruptor.start();

        for (int i = 0; i < 3; i++) {
            disruptor.publishEvent((event, sequence, newValue) -> event.setValue(newValue), i);
        }

        disruptor.shutdown();
        executor.shutdown();
    }

    public static class Consumer implements EventHandler<LongEvent> {
        private int i;
        public Consumer(int i) { this.i = i; }

        @Override
        public void onEvent(LongEvent event, long sequence, boolean endOfBatch) throws Exception {
            System.out.println("Consumer: " + i);
            event.setValue(event.getValue() + 1);
        }
    }

    public static class Conclude implements EventHandler<LongEvent> {
        @Override
        public void onEvent(LongEvent event, long sequence, boolean endOfBatch) throws Exception {
            System.out.println("Conclude: " + event.getValue());
        }
    }

    public static class LongEvent
    {
        private long value;

        public void setValue(long value)
        {
            this.value = value;
        }

        public long getValue() {
            return this.value;
        }
    }
}

事件只包含一个长值。消费者增加价值,最后一步打印它。 for循环将三个事件的初始值1,2和3放入环中。

请注意,您不需要同步LongEventConsumer上的工作,因为ringbuffer确保只有一个处理程序一次处理事件。此外,请注意消费者的印刷品在多次运行中的变化情况。