1、创建LongEvent
public class LongEvent { private long value; public long getValue() { return value; } public void setValue(long value) { this.value = value; } }
2、创建LongEventFactory实现EventFactory
public class LongEventFactory implements EventFactory { @Override public Object newInstance() { return new LongEvent(); } }
3、创建LongEventHandler实现EventHandler
public class LongEventHandler implements EventHandler<LongEvent> { @Override public void onEvent(LongEvent longEvent, long l, boolean b) throws Exception { System.out.println(longEvent.getValue()); } }
4、创建LongEventProducer
public class LongEventProducer { private final RingBuffer<LongEvent> ringBuffer; public LongEventProducer(RingBuffer<LongEvent> ringBuffer){ this.ringBuffer = ringBuffer; } /** * onData用来发布事件,每调用一次就发布一次事件它的参数会通过事件传递给消费者 */ public void onData(ByteBuffer bb){ //1.可以把ringBuffer看做一个事件队列,那么next就是得到下面一个事件槽 long sequence = ringBuffer.next(); try { //2.用上面的索引取出一个空的事件用于填充(获取该序号对应的事件对象) LongEvent event = ringBuffer.get(sequence); //3.获取要通过事件传递的业务数据 event.setValue(bb.getLong(0)); } finally { //4.发布事件 //注意,最后的 ringBuffer.publish 方法必须包含在 finally 中以确保必须得到调用;如果某个请求的 sequence 未被提交,将会堵塞后续的发布操作或者其它的 producer。 ringBuffer.publish(sequence); } } }
5、创建LongEventProducerWithTranslator
public class LongEventProducerWithTranslator { //一个translator可以看做一个事件初始化器,publicEvent方法会调用它 填充Event private static final EventTranslatorOneArg<LongEvent, ByteBuffer> TRANSLATOR = new EventTranslatorOneArg<LongEvent, ByteBuffer>() { @Override public void translateTo(LongEvent event, long sequeue, ByteBuffer buffer) { event.setValue(buffer.getLong(0)); } }; private final RingBuffer<LongEvent> ringBuffer; public LongEventProducerWithTranslator(RingBuffer<LongEvent> ringBuffer) { this.ringBuffer = ringBuffer; } public void onData(ByteBuffer buffer){ ringBuffer.publishEvent(TRANSLATOR, buffer); } }
6、创建disruptor
Disruptor<LongEvent> disruptor = new Disruptor<LongEvent>(new LongEventFactory (), 1024*1024, Executors.newCachedThreadPool(), ProducerType.SINGLE----一个生产者,如果是多个生产者用MULTI , new YieldingWaitStrategy()-----一种关于生产和消费的策略 ); 连接消费事件方法 disruptor.handleEventsWith(new LongEventHandler()); 启动 disruptor.start(); 发布事件 RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer(); LongEventProducer producer = new LongEventProducer(ringBuffer);或者LongEventProducerWithTranslator producer = new LongEventProducerWithTranslator(ringBuffer); ByteBuffer byteBuffer = ByteBuffer.allocate(8); byteBuffer.putLong(0, 1); producer.onData(byteBuffer); disruptor.shutdown();//关闭 disruptor,方法会堵塞,直至所有的事件都得到处理; executor.shutdown();//关闭 disruptor 使用的线程池;如果需要的话,必须手动关闭, disruptor 在 shutdown 时不会自动关闭;