通过 netty 实现异步任务回调获取执行结果

目前java 8 之前的异步并发编程的API(callable、future、futuretask),都有一个共同的问题,就是要获取结果必须阻塞等待。netty提供了一种通过回调的方式获得结果的办法:

Future<TGroup> future = businessEG.submit(new Callable<TGroup>() {
            @Override
            public TGroup call() throws Exception {
                //从数据库查询
                TGroup group = groupService.getDBTGroupById(gid);
                targetGroupsHM.put(gid, group);
                return group;
            }
        });

        future.addListener(new GenericFutureListener<Future<? super TGroup>>() {
            @Override
            public void operationComplete(Future<? super TGroup> future) throws Exception {
                //处理返回的结果
                TGroup group = (TGroup) future.get();
                if (group == null) {
                    byteBuf.release();
                    return;
                }
                sendToSingleGroup(group, byteBuf);
            }
        });
阅读 7k

推荐阅读