当我运行此代码时
public class Test {
public static void main(String[] args) {
Disruptor<MyEvent> disruptor = new Disruptor<MyEvent>(new EventFactoryImpl<MyEvent>(),
Executors.newFixedThreadPool(2), new MultiThreadedClaimStrategy(32), new BusySpinWaitStrategy());
MyEventHandler myEventHandler1 = new MyEventHandler("1");
MyEventHandler myEventHandler2 = new MyEventHandler("2");
disruptor.handleEventsWith(myEventHandler1, myEventHandler2);
RingBuffer<MyEvent> ringBuffer = disruptor.start();
ByteBuffer bb = ByteBuffer.allocate(8);
for (long l = 0; l < 2; l++) {
bb.putLong(0, l);
long sequence = ringBuffer.next();
try {
MyEvent event = ringBuffer.get(sequence);
event.set(bb.getLong(0));
}
finally {
ringBuffer.publish(sequence);
}
}
}
}
public class MyEvent {
private long value;
public void set(long value) {
this.value = value;
}
public long get() {
return value;
}
}
public class MyEventHandler implements EventHandler<MyEvent> {
private String id;
public MyEventHandler(String id) {
this.id = id;
}
public void onEvent(MyEvent event, long sequence, boolean endOfBatch) {
System.out.println("id: " + id + ", event: " + event.get() + ", sequence: " + sequence + "," + Thread.currentThread().getName());
}
}
public class EventFactoryImpl<T> implements EventFactory<T> {
@SuppressWarnings("unchecked")
public T newInstance() {
return (T) new MyEvent();
}
}
我收到了这个输出
id: 1, event: 0, sequence: 0,pool-1-thread-1 id: 1, event: 1, sequence: 1,pool-1-thread-1 id: 2, event: 0, sequence: 0,pool-1-thread-2 id: 2, event: 1, sequence: 1,pool-1-thread-2
但我希望每个事件都由一个单独的线程处理一次。我怎样才能实现呢?
答案 0 :(得分:1)
使用Disruptor,订阅环形缓冲区的每个EventHandler
将读取每条消息一次。
如果您希望多个线程处理来自环形缓冲区的消息,则有几个选项。第一个也是最好的选择是为每个读者线程设置一个单独的Disruptor
,并让编写器以循环方式在缓冲区之间交替。如果你必须使用一个环形缓冲区(也许是对事件进行排序),那么你可以设置 应该处理事件本身的线程ID(再次以交替的方式),并拥有与该ID不匹配的线程会丢弃该事件。
答案 1 :(得分:1)
每个EventHandler
都会处理每个事件。您可以选择链接EventHandler
,以便它们对链中先前处理程序的处理状态起作用。
破坏者还provides一个WorkerPool
,用于在一群工人中传播事件。