多线程插入等待响应-单线程顺序消费-非阻塞模式

Jensun

1.创建一个单线程的队列处理类
1.1实现Thread run阻塞读队列并处理
1.2提供submit提交请求,并返回处理future
1.3队列请求完成后,置fulture为complete
1.4req处理函数设为类私有成员,可以通过初始化动态设置

2.创建一个调用类
2.1初始化队列处理类实例,并赋值req处理函数,并启动
2.2调用队列submit,通过future接收提交的消息处理完后的反馈消息。

/**调用类,例如中间件接收到消息后,向队列提交请求*/
public class WalRequestConsumer implements Consumer<Req> {
    private final SingularUpdateQueue<Req, Res> walWriterQueue;

    public WalRequestConsumer() {
        walWriterQueue = new SingularUpdateQueue<Req, Res>((message) -> {
           return  responseMessage(message);
        });
        startHandling();
    }
    private Res responseMessage(Req message) {
        return new Res();
    }
    private void startHandling() { this.walWriterQueue.start();}
    @Override
    public void accept(Req req) {
        CompletableFuture<Res> future = walWriterQueue.submit(req);
        future.whenComplete((responseMessage, error) -> {
            sendResponse(responseMessage);
        });
    }
    private void sendResponse(Res responseMessage) {
    }
}
/**异步接收,单一处理,完成响应**/
public class SingularUpdateQueue<Req, Res> extends Thread {
    private ArrayBlockingQueue<RequestWrapper<Req, Res>> workQueue
            = new ArrayBlockingQueue<RequestWrapper<Req, Res>>(100);
    private Function<Req, Res> handler;
    private volatile boolean isRunning = false;

    public SingularUpdateQueue (Function<Req,Res> t){
        this.handler = t;
    }

    private Optional<RequestWrapper<Req, Res>> take() {
        try {
            return Optional.ofNullable(workQueue.poll(300, TimeUnit.MILLISECONDS));
        } catch (InterruptedException e) {
            return Optional.empty();
        }
    }
    
    public void shutdown() {
        this.isRunning = false;
    }
    
    public CompletableFuture<Res> submit(Req request) {
        try {
            RequestWrapper requestWrapper = new RequestWrapper<Req, Res>(request);
            workQueue.put(requestWrapper);
            return requestWrapper.getFuture();
        }
        catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
    }
    @SneakyThrows
    @Override
    public void run() {
        isRunning = true;
        while(isRunning) {
            Optional<RequestWrapper<Req, Res>> item = take();
            item.ifPresent(requestWrapper -> {
                try {
                    Res response = handler.apply(requestWrapper.getRequest());
                    requestWrapper.complete(response);

                } catch (Exception e) {
                    requestWrapper.completeExceptionally(e);
                }
            });
        }
    }
}
阅读 862
1 声望
0 粉丝
0 条评论
1 声望
0 粉丝
文章目录
宣传栏