Disruptor--Quick Start

这篇博客介绍了如何使用Disruptor框架创建一个高性能的队列,包括设置EventTranslatorOneArg进行事件转换,通过RingBuffer进行数据发布,并且实现了一个DisruptorEventHandler来监听和处理事件。Disruptor的使用显著提高了并发处理能力和效率。
摘要由CSDN通过智能技术生成
  • 注册队列并生产
public class DisruptorQueue<T> extends AbstractQueue<T> {
 
    private final EventTranslatorOneArg translator;
    private final RingBuffer ringBuffer;
    private final Disruptor disruptor;
    private final int bufferSize;
    private static final int RINGBUFFER_DEFAULT_SIZE = 4 * 1024;
 
    public DisruptorQueue(EventFactory eventFactory , EventTranslatorOneArg translator , DisruptorEventHandler eventHandler) {
        super(eventHandler);
        bufferSize = getBufferSize();
        Disruptor disruptor = new Disruptor<>(eventFactory, bufferSize,
                new ThreadUtils(getClass().getSimpleName()), ProducerType.MULTI, new BlockingWaitStrategy());
        disruptor.handleEventsWith(eventHandler);
        this.translator = translator;
        this.ringBuffer = disruptor.getRingBuffer();
        this.disruptor = disruptor;
    }
 
    @Override
    public void publish(T item) {
        if (!ringBuffer.tryPublishEvent(translator, item)) {
            ringBuffer.publishEvent(translator, item);
        }
    }
 
    @Override
    public void start() {
        super.start();
        disruptor.start();
    }
 
    @Override
    public void close() {
        super.close();
        disruptor.shutdown();
    }
 
    @Override
    public int size() {
        return bufferSize - (int) ringBuffer.remainingCapacity();
    }
 
    private static int getBufferSize() {
        return RINGBUFFER_DEFAULT_SIZE;
    }
}
  • 监听事件并消费
public abstract class DisruptorEventHandler<T> implements EventHandler<EventHolder<T>> {
 
    protected final boolean allowDiscard = true;
    private final AtomicBoolean running = new AtomicBoolean(false);
    private final AtomicLong failCount = new AtomicLong(0);
 
    public void onEvent(EventHolder eventHolder, long sequence, boolean endOfBatch) {
        T event = eventHolder.getEvent();
        if (event != null && isRunning()) {
            handleEvent(event, endOfBatch);
        }
        eventHolder.setEvent(null);
    }
 
    public abstract void handleEvent(T eventItem, boolean endOfBatch);
 
    public boolean isRunning() {
        return running.get();
    }
 
    public void start() {
        running.getAndSet(true);
    }
 
    public void close() {
        running.getAndSet(false);
    }
 
    protected void incrementFailCount(long delta) {
        failCount.addAndGet(delta);
    }
 
    public long getFailCount() {
        return failCount.get();
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值