玩过 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() + "发过去了");
        }
    }
}
Logo

Kafka开源项目指南提供详尽教程,助开发者掌握其架构、配置和使用,实现高效数据流管理和实时处理。它高性能、可扩展,适合日志收集和实时数据处理,通过持久化保障数据安全,是企业大数据生态系统的核心。

更多推荐