package com.bcxin.identify.components.ringbuffers;

import com.bcxin.identify.business.service.LogBusinessrequestService;
import com.bcxin.identify.components.ringbuffers.events.ObjectEvent;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.dsl.Disruptor;
import com.lmax.disruptor.util.DaemonThreadFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RingBufferConfig  {

    @Bean
    public ProcessingEventHandler cacheEventHandler(LogBusinessrequestService logBusinessrequestService) {
        return new ProcessingEventHandler(logBusinessrequestService);
    }

    @Bean
    public RingBufferProducer ringBufferProducer(ProcessingEventHandler processingEventHandler) {
        final int BUFFER_SIZE = 1024 * 1024;
        Disruptor<ObjectEvent<?>> disruptor = new Disruptor<>(
                () -> new ObjectEvent<>(), BUFFER_SIZE, DaemonThreadFactory.INSTANCE);
        disruptor
                .handleEventsWith(processingEventHandler)
                .then(new ClearingEventHandler());

        disruptor.start();

        RingBuffer<ObjectEvent<?>> ringBuffer = disruptor.getRingBuffer();
        return new RingBufferProducer(ringBuffer);
    }
}
