Official address|: https://github.com/LMAX-Exchange/disruptor/wiki/Getting-Started
https://github.com/LMAX-Exchange/disruptor
public class LongEvent { private Long value; public Long getValue() { return value; } public void setValue(Long value) { this.value = value; } }
import com.lmax.disruptor.EventFactory; /** *Event Factory */ public class LongEventFactory implements EventFactory<LongEvent>{ @Override public LongEvent newInstance() { return new LongEvent(); } }
import com.lmax.disruptor.EventHandler; /** * Consumer/Event Handler */ public class LongEventHandler implements EventHandler{ @Override public void onEvent(Object event, long sequence, boolean endOfBatch) throws Exception { System.out.println("Event:"+event+" sequence:"+sequence+" endOfBatch:"+endOfBatch); } }
import java.nio.ByteBuffer; import com.lmax.disruptor.RingBuffer; public class LongEventProducer { private final RingBuffer<LongEvent> ringBuffer; public LongEventProducer(RingBuffer<LongEvent> ringBuffer) { this.ringBuffer = ringBuffer; } public void onData(ByteBuffer bb) { // next sequence long sequence = ringBuffer.next(); try { // Get the entry in the Disruptor for the sequence LongEvent event = ringBuffer.get(sequence); //Data input event.setValue(bb.getLong(0)); } finally { //publish sequence ringBuffer.publish(sequence); } } }
import java.nio.ByteBuffer; import com.lmax.disruptor.EventTranslatorOneArg; import com.lmax.disruptor.RingBuffer; public class LongEventProducerWithTranslator { private final RingBuffer<LongEvent> ringBuffer; public LongEventProducerWithTranslator(RingBuffer<LongEvent> ringBuffer) { this.ringBuffer = ringBuffer; } private static final EventTranslatorOneArg<LongEvent, ByteBuffer> TRANSLATOR = new EventTranslatorOneArg<LongEvent, ByteBuffer>() { public void translateTo(LongEvent event, long sequence, ByteBuffer bb) { event.setValue(bb.getLong(0));; } }; public void onData(ByteBuffer bb) { ringBuffer.publishEvent(TRANSLATOR, bb); } }
import java.nio.ByteBuffer; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.dsl.Disruptor; public class LongEventMain { public static void main(String[] args) throws Exception { Executor executor = Executors.newCachedThreadPool(); // bufferSize must be 2 to the Nth power int bufferSize = 1024; // Construct the disruptor Disruptor<LongEvent> disruptor = new Disruptor<>(LongEvent::new,bufferSize, executor); // link handler disruptor.handleEventsWith((event, sequence, endOfBatch) -> System.out.println("Event: " + event+" sequence:"+sequence+" endOfBatch:"+endOfBatch)); // start running Disruptor disruptor.start(); // Get the ring buffer from the disruptor RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer(); ByteBuffer bb = ByteBuffer.allocate(8); for (long l = 0; true; l++) { bb.putLong(0, l); ringBuffer.publishEvent((event, sequence, buffer) -> event.setValue(buffer.getLong(0)),bb); Thread.sleep(1000); } } }