package hua;
/**
* 事件
*/
public class LongEvent {
public String name;
public long value;
public long getValue() {
return value;
}
public void setValue(long value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package hua;
import com.lmax.disruptor.EventFactory;
/**
事件工厂
*/
public class LongEventFactory implements EventFactory<LongEvent> {
public LongEvent newInstance()
{
return new LongEvent();
}
}
package hua;
import com.lmax.disruptor.EventHandler;
/**
消费者
*/
public class LongEventConsumer implements EventHandler<LongEvent>
{
public void onEvent(LongEvent event, long sequence, boolean endOfBatch)
{
//获取数据处理自己的业务
System.out.println( event.getName() +" "+ event.value + " sequence="+sequence + " endOfBatch="+endOfBatch);
}
}
package hua;
import com.lmax.disruptor.RingBuffer;
/**
* 生产者 方式1
*/
public class LongEventProducer
{
private final RingBuffer<LongEvent> ringBuffer;
public LongEventProducer(RingBuffer<LongEvent> ringBuffer)
{
this.ringBuffer = ringBuffer;
}
public void onData(LongEvent bb)
{
long sequence = ringBuffer.next(); // Grab the next sequence
try
{
LongEvent event = ringBuffer.get(sequence); // Get the entry in the Disruptor
event.setName(bb.getName());
event.setValue(bb.getValue());
}
finally
{
ringBuffer.publish(sequence);
}
}
}
package hua;
/**
* 生产者 方式2
*/
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, LongEvent> TRANSLATOR = new EventTranslatorOneArg<LongEvent, LongEvent>()
{
public void translateTo(LongEvent event, long sequence, LongEvent bb)
{
event.setName(bb.getName());
event.setValue(bb.getValue());
}
};
public void onData(LongEvent bb)
{
ringBuffer.publishEvent(TRANSLATOR, bb);
}
}
package hua; /** */ import com.lmax.disruptor.dsl.Disruptor; import com.lmax.disruptor.RingBuffer; import com.lmax.disruptor.util.DaemonThreadFactory; public class LongEventMain { public static void main(String[] args) throws Exception{ LongEventFactory factory = new LongEventFactory(); int bufferSize = 1024; Disruptor<LongEvent> disruptor = new Disruptor<>(factory, bufferSize, DaemonThreadFactory.INSTANCE); disruptor.handleEventsWith(new LongEventConsumer()); disruptor.start(); RingBuffer<LongEvent> ringBuffer = disruptor.getRingBuffer(); LongEventProducerWithTranslator producer = new LongEventProducerWithTranslator(ringBuffer); for (long l = 0; true; l++){ String name = "test"+l; LongEvent e = new LongEvent(); e.setName(name); e.setValue(l); producer.onData(e); Thread.sleep(1000); } } }