Disruptor-生产者发布方式

旧版本API发布方式

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){
        long sequence = ringBuffer.next();  // Grab the next sequence
        try{
            LongEvent event = ringBuffer.get(sequence); // Get the entry in the Disruptor
                                                        // for the sequence
            event.set(bb.getLong(0));  // Fill with data
        }
        finally{
            ringBuffer.publish(sequence);
        }
    }
}

使用

RingBuffer<LongEvent> ringBuffer = disruptor.start();

LongEventProducer producer = new LongEventProducer(ringBuffer);

ByteBuffer bb = ByteBuffer.allocate(8);
for (long l = 0; l<5; l++) {
    bb.putLong(0, l);
    producer.onData(bb)
}
System.out.println("发布完成");

使用Translators发布

import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.EventTranslatorOneArg;

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.set(bb.getLong(0));
            }
        };
    
    public void onData(ByteBuffer bb){
        ringBuffer.publishEvent(TRANSLATOR, bb);
    }
}

使用

RingBuffer<LongEvent> ringBuffer = disruptor.start();

- LongEventProducer producer = new LongEventProducer(ringBuffer);
+ LongEventProducerWithTranslator producer = new LongEventProducerWithTranslator(ringBuffer);

ByteBuffer bb = ByteBuffer.allocate(8);
for (long l = 0; l<5; l++) {
    bb.putLong(0, l);
    producer.onData(bb)
}
System.out.println("发布完成");

使用Java8的Lambda表达式发布

RingBuffer<LongEvent> ringBuffer = disruptor.start();
- LongEventProducerWithTranslator producer = new LongEventProducerWithTranslator(ringBuffer);
ByteBuffer bb = ByteBuffer.allocate(8);
for (long l = 0; true; l++){
    bb.putLong(0, l);
-   producer.onData(bb);
+   ringBuffer.publishEvent((event, sequence, buffer) ->event.set(buffer.getLong(0)),bb);
}