文章作者: 小王是个弟弟
文章链接: https://kpretty.tech/archives/kafka-problem-2
版权声明: 本站所有文章均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 小王是个弟弟
结构

Callback.java
import java.util.Map;
public interface Callback {
void onCompletion(Map<String, String> offset, Exception exception);
}
CallbackImpl.java
import java.util.Map;
public class CallbackImpl implements Callback {
@Override
public void onCompletion(Map<String, String> offset, Exception exception) {
if (null == exception) {
System.out.println("======"+offset+"======");
} else {
exception.printStackTrace();
}
}
}
RemoteServer.java
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;
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.java
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){
String message = "message";
RemoteServer<String> remoteServer = new RemoteServer<>();
for (int i = 0; i < 10; i++) {
remoteServer.send(message,new CallbackImpl());
System.out.println(new Date() + "发过去了");
}
}
}
正常消息异步发送+回调

正常消息同步发送

错误消息异步发送+回调
