java中如何获取异步接口的回调通知?
在Java中获取异步接口的回调通知通常涉及使用回调机制、Future和CompletableFuture类、或者更高级的异步框架。以下是几种常见的实现方式:
1. 使用回调接口
通过定义一个回调接口并在异步任务完成时调用回调方法。
javapublic interface Callback {
void onComplete(String result);
void onError(Exception e);
}
public class AsyncTask {
public void executeAsync(Callback callback) {
new Thread(() -> {
try {
// 模拟异步任务
Thread.sleep(1000);
String result = "Task completed";
callback.onComplete(result);
} catch (Exception e) {
callback.onError(e);
}
}).start();
}
}
public class Main {
public static void main(String[] args) {
AsyncTask task = new AsyncTask();
task.executeAsync(new Callback() {
@Override
public void onComplete(String result) {
System.out.println("Callback received: " + result);
}
@Override
public void onError(Exception e) {
System.err.println("Error: " + e.getMessage());
}
});
}
}
2. 使用Future
通过Future获取异步任务的结果。这种方法适用于需要阻塞等待结果的场景。
javaimport java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newSingleThreadExecutor();
Callable<String> task = () -> {
Thread.sleep(1000);
return "Task completed";
};
Future<String> future = executor.submit(task);
try {
// 阻塞等待结果
String result = future.get();
System.out.println("Result: " + result);
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
} finally {
executor.shutdown();
}
}
}
3. 使用CompletableFuture
CompletableFuture提供了更强大的异步编程能力,包括非阻塞回调和组合多个异步任务。
javaimport java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "Task completed";
}).thenAccept(result -> {
System.out.println("Callback received: " + result);
}).exceptionally(e -> {
System.err.println("Error: " + e.getMessage());
return null;
});
}
}
4. 使用高级异步框架
像RxJava或Akka等框架可以提供更强大的异步处理能力和模式。
使用RxJava
javaimport io.reactivex.Observable;
public class Main {
public static void main(String[] args) {
Observable<String> observable = Observable.create(emitter -> {
try {
Thread.sleep(1000);
emitter.onNext("Task completed");
emitter.onComplete();
} catch (Exception e) {
emitter.onError(e);
}
});
observable.subscribe(
result -> System.out.println("Callback received: " + result),
error -> System.err.println("Error: " + error.getMessage())
);
}
}
使用Akka
javaimport akka.actor.AbstractActor;
import akka.actor.ActorRef;
import akka.actor.ActorSystem;
import akka.actor.Props;
public class Main {
static class MyActor extends AbstractActor {
@Override
public Receive createReceive() {
return receiveBuilder()
.matchEquals("start", msg -> {
// 模拟异步任务
Thread.sleep(1000);
getSender().tell("Task completed", getSelf());
})
.build();
}
}
public static void main(String[] args) {
ActorSystem system = ActorSystem.create("MySystem");
ActorRef myActor = system.actorOf(Props.create(MyActor.class), "myActor");
myActor.tell("start", ActorRef.noSender());
myActor.tell("start", ActorRef.noSender());
system.terminate();
}
}
这些方法都可以用于处理Java中的异步接口回调,根据具体需求选择合适的实现方式。