侧边栏壁纸
博主头像
王一川博主等级

努力成为一个不会前端的全栈工程师

  • 累计撰写 70 篇文章
  • 累计创建 20 个标签
  • 累计收到 39 条评论

目 录CONTENT

文章目录

手写 kafka 异步回调

王一川
2022-04-04 / 0 评论 / 4 点赞 / 1,371 阅读 / 3,234 字
温馨提示:
本文最后更新于 2022-05-31,若内容或图片失效,请留言反馈。部分素材来自网络,若不小心影响到您的利益,请联系我们删除。

玩过 kafka 的小伙伴相信对 kafka 生产者和消费者的异步回调记忆犹新,不由的赞叹这种设计模式真的超赞,心想如果我也能写出这样的异步回调那该多好,今天他来了!!!

Callback

模仿 kafka 的这个接口用于接收回调信息

package demo;

import java.util.Map;

public interface Callback {
    void onCompletion(Map<String, String> offset, Exception exception);
}

ReomteServer

这个就相当于 kafka 实际发消息的类,将消息异步发送(也可以同步)给服务器后返回元数据信息。首先分析一下既要异步也要支持同步那就需要使用 Future 类了,利用它的 get() 方法实现同步即可!!!

package demo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.TimeUnit;

public class RemoteServer<T> {
    private static final SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public Future<Map<String, String>> send(T message) {
        return send(message, null);
    }

    public Future<Map<String, String>> send(T message, Callback callback) {
        FutureTask<Map<String, String>> futureTask = new FutureTask<>(
                () -> {
                    if (callback != null) {
                        if ("error".equals(message)) {
                            callback.onCompletion(null, new RuntimeException(sdf.format(new Date())+"因为你发了error,所以报错了"));
                        } else {
                            callback.onCompletion(getMap(message), null);
                        }
                    }
                    return getMap(message);
                }
        );
        new Thread(futureTask).start();
        return futureTask;
    }

    public Map<String, String> getMap(T message) {
        HashMap<String, String> map = new HashMap<>();
        map.put("message", message.toString());
        map.put("offset", message.hashCode() + "");
        map.put("time", sdf.format(new Date()));
        return map;
    }
}

这样一个简单的异步回调就完成啦。

LocalServer

本地测试

正常消息异步发送+回调

package demo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class LocalServer {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        String message = "message";
        RemoteServer<String> remoteServer = new RemoteServer<>();
        for (int i = 0; i < 10; i++) {
            remoteServer.send(message, new Callback() {
                @Override
                public void onCompletion(Map<String, String> offset, Exception exception) {
                    if (null == exception) {
                        System.out.println(offset);
                    } else {
                        exception.printStackTrace();
                    }
                }
            });
            System.out.println(new Date() + "发过去了");
        }
    }
}

测试结果

正常消息同步发送

package demo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class LocalServer {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        String message = "error";
        RemoteServer<String> remoteServer = new RemoteServer<>();
        for (int i = 0; i < 10; i++) {
            System.out.println(remoteServer.send(message).get());
            System.out.println(new Date() + "发过去了");
        }
    }
}

错误消息异步发送+回调

package demo;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.ExecutionException;

public class LocalServer {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        String message = "error";
        RemoteServer<String> remoteServer = new RemoteServer<>();
        for (int i = 0; i < 10; i++) {
            remoteServer.send(message, new Callback() {
                @Override
                public void onCompletion(Map<String, String> offset, Exception exception) {
                    if (null == exception) {
                        System.out.println(offset);
                    } else {
                        exception.printStackTrace();
                    }
                }
            });
            System.out.println(new Date() + "发过去了");
        }
    }
}
4

评论区