disruptor demo(二) 使用WorkerPool辅助创建消费者


1.

//POJO 交易类
public class TradeTransaction {
	private String id; //交易ID
	private double price;//交易金额
	
	public TradeTransaction(){}
	
	public TradeTransaction(String id,double price){
		super();
		this.id = id;
		this.price = price;
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}
	
}

2.

import java.util.UUID;

import com.lmax.disruptor.EventHandler;
import com.lmax.disruptor.WorkHandler;


public class TradeTransactionInDBHandler implements WorkHandler{

	@Override
	public void onEvent(TradeTransaction event) throws Exception {
		event.setId(UUID.randomUUID().toString());
		System.out.println(event.getId());
		
	}

}

3.

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

import com.lmax.disruptor.EventFactory;
import com.lmax.disruptor.IgnoreExceptionHandler;
import com.lmax.disruptor.RingBuffer;
import com.lmax.disruptor.SequenceBarrier;
import com.lmax.disruptor.WorkHandler;
import com.lmax.disruptor.WorkerPool;

public class Demo2 {
	public static void main(String[] args) throws InterruptedException {
		final int BUFFER_SIZE = 1024;
		final int THREAD_NUMBERS = 4;
		EventFactory eventFactory = new EventFactory() {
			public TradeTransaction newInstance() {
				return new TradeTransaction();
			}
		};

		RingBuffer ringBuffer = RingBuffer.createSingleProducer(eventFactory, BUFFER_SIZE);

		SequenceBarrier sequenceBarrier = ringBuffer.newBarrier();

		ExecutorService executor = Executors.newFixedThreadPool(THREAD_NUMBERS);

		WorkHandler[] workHandlers = new WorkHandler[3];
		for (int i = 0; i < 3; i++) {
			WorkHandler workHandler = new TradeTransactionInDBHandler();
			workHandlers[i] = workHandler;
		}

		WorkerPool workerPool = new WorkerPool(ringBuffer, sequenceBarrier, new IgnoreExceptionHandler(), workHandlers);

		workerPool.start(executor);

		for (int i = 0; i < 800; i++) {
			long seq = ringBuffer.next();
			ringBuffer.get(seq).setPrice(Math.random() * 9999);
			ringBuffer.publish(seq);
			if (i % 10 == 0) {
				System.out.println(((ThreadPoolExecutor) executor).getActiveCount() + "============================================");
			}
		}
		Thread.sleep(1000);
		workerPool.halt();
		Thread.sleep(1);
		executor.shutdown();
	}
}


你可能感兴趣的:(disruptor)