初步使用disruptor

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>() {
				@Override
				public 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>() {

					@Override
					public EventEntity newInstance() {
						// TODO Auto-generated method stub
						return new EventEntity();
					}
				}, ringBufferSize, executorService, ProducerType.SINGLE,
				new YieldingWaitStrategy());
		disruptor.handleEventsWith(new EventHandler<EventEntity>() {

			@Override
			public 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> {

	@Override
	public 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; 
	    } 
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值