如何在使用 @Async 的方法中实现回调(Springboot 应用)

huangapple go评论69阅读模式
英文:

How to Implement a Callback in Methods that uses @Async (Springboot App)

问题

我需要实现一种类似回调的解决方案,以便在方法调用成功/失败时收到通知。我正在调用的这些方法位于一个 Springboot 应用程序中,并且它们都是异步的。更具体地说,它们都使用了 @Async 注解。

我在寻找解决方案方面并没有取得成功,想知道是否有其他人可能有一些想法。我不能使用另一个异步方法(即,我不能更改现有代码以删除 @Async 并使用其他替代方法)。但是,我可以修改方法体本身以添加任何回调能力。

谢谢。

英文:

I have a need to implement a callback-like solution to be notified of the success/failure of method calls. These methods I am calling are in a Springboot app and they are all asynchronous. More specifically, they all use the @Async annotation.

I have not been successful in finding a solution to this and was wondering whether others may have some ideas. I cannot use another async method (that is, I cannot change the existing code to remove the @Async and use something in its place). However, I can modify the method bodies themselves to add any callback capability.

Thank you.

答案1

得分: 2

基于M. Derium(上面的建议),我正在使用CompletableFuture来解决我的问题。我仍在实施和测试过程中,但它似乎是一个不错的解决方案。这是一个很好的参考资料:CompletableFuture指南

英文:

Based on the suggestion of M. Derium (above) I am using CompletableFuture for my solution. I am still in the process of implementing and testing, but it seems to be a good solutions. Here is a good reference: Guide to CompletableFuture

答案2

得分: 1

我认为你可以创建一个带有两个方法的新接口,然后将一个实现参数传递给异步方法。

public interface TaskCallBack {

    void success(int code);
    void fail(int code);
}
英文:

I think you can just create a new Interface with two methods, and then pass a implementation parameter to the async method.

public interface TaskCallBack {
    
    void success(int code);
    void fail(int code);
}

huangapple
  • 本文由 发表于 2020年9月30日 00:48:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/64124139.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定