码迷,mamicode.com
首页 > 其他好文 > 详细

Disruptor使用简介

时间:2016-01-12 16:57:55      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:

 

 

public class DisruptorServer {
    private Disruptor disruptor = null;

    public static void main(String[] args) {
        DisruptorContext.start();
        System.out.println("Disruptor服务已启动...");
       
        for(long i=0; i<101; i++){
            DisruptorContext.publish(i);
        }
        DisruptorContext.stop();
        System.out.println("...Disruptor服务已停止");
    }
}

public class DisruptorContext {
    private static Disruptor<LongEvent> disruptor = null;
    private static ExecutorService executor = null;
    
    public static void start(){
        if(null==disruptor){
        EventFactory<LongEvent> eventFactory = new LongEventFactory();
        executor = Executors.newSingleThreadExecutor();
        WaitStrategy waitStrategy = new BlockingWaitStrategy();
        int ringBufferSize = 1024*1024;
        disruptor = new Disruptor<LongEvent>(eventFactory, 
                                             ringBufferSize, 
                                             executor, 
                                             ProducerType.SINGLE, 
                                             waitStrategy);
        EventHandler<LongEvent> eventHandler = new LongEventHandler();
        disruptor.handleEventsWith(eventHandler);
        disruptor.start();
        }
    }
    
    public static void stop(){
        disruptor.shutdown();
        executor.shutdown();
    }
    
    public static void publish(long eventData){
        RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer();
        long sequence = ringBuffer.next();
        try{
        LongEvent event = ringBuffer.get(sequence);
        event.set(eventData);
        }finally{
            ringBuffer.publish(sequence);
        }
    }
}


public class LongEvent {
    private long value;

    public void set(long value) {
        this.value = value;
    }
    
    public long get(){
        return this.value;
    }
}


public class LongEventFactory implements EventFactory<LongEvent> {

    @Override
    public LongEvent newInstance() {
        return new LongEvent();
    }

}


public class LongEventHandler implements EventHandler<LongEvent>{

    @Override
    public void onEvent(LongEvent event, long sequence, boolean endOfBatch) throws Exception {
        System.out.println("Disruptor消费者输出Event :" + event.get());
    }

}

Event 需要进入disruptor交换的对象都需要封装成event,本例中封装的是一个long

EventFactory工厂,决定以何种方式创建event。  
  *   工厂模式:我不知道你需要的是什么样的对象,索性把你的构造方法(工厂)传过来吧。

EventHandler事件处理的具体实现,也即producer——consumer中的consumer的具体实现
  *   本例中仅仅对event中的long进行输出

 

Disruptor使用简介

标签:

原文地址:http://www.cnblogs.com/lyhero11/p/5124844.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!