1.disruptor是什么?
disruptor是一个高性能的异步处理框架,或者可以认为是最快的消息框架(轻量的JMS),也可以认为是一个观察者模式的实现,或者事件监听模式的实现。2.disruptor的原理
英文:http://stackoverflow.com/questions/6559308/how-does-lmaxs-disruptor-pattern-work翻译:http://www.cnblogs.com/adaikiss/archive/2012/02/15/2352545.html
3.实现例子
(1)pojo
/**
* just think of a pojo
* @author guolei
*
*/
public final class ValueEvent
{
private long value;
public long getValue()
{
return value;
}
public void setValue(final long value)
{
this.value = value;
}
public final static EventFactory<ValueEvent> EVENT_FACTORY = new EventFactory<ValueEvent>()
{
public ValueEvent newInstance()
{
return new ValueEvent();
}
};
}
(2)生产者
public class Producer implements Runnable {
private RingBuffer<ValueEvent> ringBuffer = null;
public Producer(RingBuffer<ValueEvent> rb) {
ringBuffer = rb;
}
@Override
public void run() {
// Publishers claim events in sequence
long sequence = ringBuffer.next();
ValueEvent event = ringBuffer.get(sequence);
event.setValue(1234); // this could be more complex with multiple fields
// make the event available to EventProcessors
ringBuffer.publish(sequence);
}
}
(3)消费者
public class ConsumeEventHandler implements EventHandler<ValueEvent>{
@Override
public void onEvent(ValueEvent event, long sequence, boolean endOfBatch) throws Exception {
// TODO Auto-generated method stub
System.out.println("=================="+event.getValue());
}
}
(4)测试类
public class TestShow {
private static final int BUFFER_SIZE = 16;
private final RingBuffer<ValueEvent> ringBuffer = new RingBuffer<ValueEvent>(
ValueEvent.EVENT_FACTORY, new SingleThreadedClaimStrategy(BUFFER_SIZE),
new YieldingWaitStrategy());
private final SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();
private final ConsumeEventHandler handler = new ConsumeEventHandler();
private final ExecutorService EXECUTOR = Executors.newSingleThreadExecutor();
private final BatchEventProcessor<ValueEvent> batchEventProcessor = new BatchEventProcessor<ValueEvent>(
ringBuffer, sequenceBarrier, handler);
public TestShow() {
ringBuffer.setGatingSequences(batchEventProcessor.getSequence());
}
public void consume() {
EXECUTOR.submit(batchEventProcessor);
}
public void produce() {
new Thread(new Producer(ringBuffer)).start();
}
public static void main(String[] args) {
TestShow test = new TestShow();
test.produce();
test.consume();
}
}
原文 http://my.oschina.net/xishuixixia/blog/92439