// 父类,
class LhsPadding
{
protected long p1, p2, p3, p4, p5, p6, p7;
}
class Value extends LhsPadding
{
protected volatile long value;
}
class RhsPadding extends Value
{
protected long p9, p10, p11, p12, p13, p14, p15;
}
public class Sequence extends RhsPadding
{
...
public void onData(String content) {
// ringBuffer是个队列,其next方法返回的是下最后一条记录之后的位置,这是个可用位置
long sequence = ringBuffer.next();
try {
// sequence位置取出的事件是空事件
OrderEvent orderEvent = ringBuffer.get(sequence);
// 空事件添加业务信息
orderEvent.setValue(content);
} finally {
// 发布
ringBuffer.publish(sequence);
}
}
package com.bolingcavalry.service;
import com.lmax.disruptor.EventTranslatorOneArg;
import com.lmax.disruptor.RingBuffer;
public class OrderEventProducerWithTranslator {
// 存储数据的环形队列
private final RingBuffer<OrderEvent> ringBuffer;
public OrderEventProducerWithTranslator(RingBuffer<OrderEvent> ringBuffer) {
this.ringBuffer = ringBuffer;
}
/**
* 内部类
*/
private static final EventTranslatorOneArg<OrderEvent, String> TRANSLATOR = new EventTranslatorOneArg<OrderEvent, String>() {
@Override
public void translateTo(OrderEvent event, long sequence, String arg0) {
event.setValue(arg0);
}
};
public void onData(String content) {
ringBuffer.publishEvent(TRANSLATOR, content);
}
}
@Override
public <A> void publishEvent(EventTranslatorOneArg<E, A> translator, A arg0)
{
final long sequence = sequencer.next();
translateAndPublish(translator, sequence, arg0);
}
private <A> void translateAndPublish(EventTranslatorOneArg<E, A> translator, long sequence, A arg0)
{
try
{
translator.translateTo(get(sequence), sequence, arg0);
}
finally
{
sequencer.publish(sequence);
}
}
// lambda类型的实例化
disruptor = new Disruptor<OrderEvent>(OrderEvent::new, BUFFER_SIZE, DaemonThreadFactory.INSTANCE);
// lambda表达式指定具体消费逻辑
disruptor.handleEventsWith((event, sequence, endOfBatch) -> {
log.info("lambda操作, sequence [{}], endOfBatch [{}], event : {}", sequence, endOfBatch, event);
// 这里延时100ms,模拟消费事件的逻辑的耗时
Thread.sleep(100);
// 计数
eventCountPrinter.accept(null);
});
public void publistEvent(EventTranslatorOneArg<OrderEvent, String> translator, String value) {
disruptor.getRingBuffer().publishEvent(translator, value);
}
for(int i=0;i<EVENT_COUNT;i++) {
log.info("publich {}", i);
final String content = String.valueOf(i);
lambdaService.publistEvent((event, sequence, value) -> event.setValue(value), content);
}