初步使用disruptor

来源:互联网 发布:cos后期特效软件 编辑:程序博客网 时间:2024/06/10 16:18

disruptor 是一个高性能的异步处理框架,可以认为是一个快速的的jms实现,从开发模式上讲是属于反应器模式

disruptor 的内部有个ringbuffer 是个很好的环形队列需要重点理解其原理

实例

package com.zyc.disruptor;import java.nio.ByteBuffer;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import com.lmax.disruptor.EventFactory;import com.lmax.disruptor.EventHandler;import com.lmax.disruptor.EventTranslator;import com.lmax.disruptor.EventTranslatorOneArg;import com.lmax.disruptor.RingBuffer;import com.lmax.disruptor.YieldingWaitStrategy;import com.lmax.disruptor.dsl.Disruptor;import com.lmax.disruptor.dsl.ProducerType;public class DisruptorMain {private static final EventTranslatorOneArg<EventEntity, Long> TRANSLATOR = new EventTranslatorOneArg<EventEntity, Long>() {@Overridepublic void translateTo(EventEntity event, long sequeue, Long buffer) {event.setValue(buffer);}};@SuppressWarnings("unchecked")public static void main(String[] args) throws InterruptedException {ExecutorService executorService = Executors.newCachedThreadPool();int ringBufferSize = 1024 * 1024;//ringbuffer的大小,最好是2的n次幂Disruptor<EventEntity> disruptor = new Disruptor<EventEntity>(new EventFactory<EventEntity>() {@Overridepublic EventEntity newInstance() {// TODO Auto-generated method stubreturn new EventEntity();}}, ringBufferSize, executorService, ProducerType.SINGLE,new YieldingWaitStrategy());disruptor.handleEventsWith(new EventHandler<EventEntity>() {@Overridepublic void onEvent(EventEntity arg0, long arg1, boolean arg2)throws Exception {Thread.sleep(5000);System.out.println(arg0.getValue());}},new CoustomerEventHandler2());//配置多个消费方,用","分割disruptor.start();RingBuffer<EventEntity> ringBuffer = disruptor.getRingBuffer();ringBuffer.publishEvent(TRANSLATOR,(long) 132);System.out.println("affdssdf");//此行验证异步是否可用disruptor.shutdown();executorService.shutdown();System.out.println("结束流程");}}class CoustomerEventHandler2 implements EventHandler<EventEntity> {@Overridepublic void onEvent(EventEntity arg0, long arg1, boolean arg2) throws Exception {System.out.println("this is a CoustomerEventHandler2  "+arg0.getValue());}}

package com.zyc.disruptor;public class EventEntity {  private long value;  public EventEntity(){    }    public EventEntity(long string) {this.value=string;}public long getValue() {         return value;     }      public void setValue(long value) {         this.value = value;     } }




原创粉丝点击