简体   繁体   English

服务层上的异步 java 方法

[英]asynchronous java method on service layer

I'm using a library called PubNub for posting messages.我正在使用一个名为 PubNub 的库来发布消息。 The PubNub method posts messages asynchronously, and it has a way to see if the message was posted or not. PubNub 方法异步发布消息,它有一种方法可以查看消息是否已发布。

I'm using Spring MVC and ThymeLeaf, so I would like to send the response back to my front-end after I get the message status (error or success), however, I don't know how to wait until my PubNub method finishes, and then send the result.我正在使用 Spring MVC 和 ThymeLeaf,所以我想在收到消息状态(错误或成功)后将响应发送回我的前端,但是,我不知道如何等到我的 PubNub 方法完成,然后发送结果。 Here's the code:这是代码:

    @Controller
    public class HomeController {
    
        @PostMapping("/triggerDevices")
        public String triggerDevices(@ModelAttribute(value = "message") Message message, Model model) {
        //
        //
        // validations and build data
        //
        //
         MyResult result = null;
    
         //Async method
                pubNub.publish()
                .message(message)
                .channel(channel)
                .async((result, status) -> {
                 //This block takes some time
                    if (status == null || status.isError()) {
                       //Error case
                       result = new MyResult (false, status.errorMessage(),message.device);
                    } else {
                       //Success case
                       result = new MyResult (true, null, message.device);
                    }
                });
    
            //Result
            model.addAttribute("result", result);
            return "home :: info-success";
       }  
    
    }

I hope someone helps me, thanks so much.我希望有人帮助我,非常感谢。

PubNub Java SDK Publish sync PubNub Java SDK 发布sync

Just use the sync method instead of async只需使用sync方法而不是async

PNPublishResult result = pubnub.publish()
                             .channel("coolChannel")
                             .message("test")
                             .shouldStore(true)
                             .ttl(10)
                             .sync();

See full PubNub SDK Java Docs for publish/sync .请参阅完整的 PubNub SDK Java 文档以进行发布/同步

That should do it for you.那应该为你做。 Cheers!干杯!

Using sync is an easy fix, but if u need to keep it async: i would return within the async function result here after you get the result:使用同步是一个简单的修复,但如果你需要保持异步:我会在你得到结果后在异步 function 结果中返回:

//Success case
result = new MyResult (true, null, message.device);
model.addAttribute("result", result);
return "home :: info-success";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM