有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java@Async在REST类中不起作用

我正在从事一个使用Spring构建的WebService项目。所有配置都是使用注释完成的。有一种方法可以发送推送通知。因为有许多通知要发送,这会导致响应延迟。因此,我将@Async注释应用于我的“sendPushnotification”方法。但是,在响应方面仍然没有任何改进。我浏览了一些博客和stackoverflow来找到解决方案。但是,没有成功。我已将以下注释应用于我的服务类

@Component
@Configuration
@EnableAspectJAutoProxy
@EnableAsync

从中调用async的方法

@POST
@Path("/sampleService")
@Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public Response sampleService(@FormParam ...) {
    ...
    List<User> commentors = <other method to fetch commentors>;
    sendPushnotification(commentors);
    ...
}

我的异步方法

@Async
private void sendPushnotification(List<User> commentors) {
    if (commentors != null) {
        for (User user : commentors) {
            try {
                int numNewComments = ps.getCommentsUnseenByUser(user); 

                sendMessage("ios", user, "2", "" + numNewComments, "true"); 
            } catch (Exception e) {
                log.error(e.getMessage(), e);
            }
        }
    }
}

我有什么遗漏吗


共 (1) 个答案

  1. # 1 楼答案

    您正在this上调用该方法

    sendPushnotification(commentors);
    // equivalent to
    this.sendPushnotification(commentors);
    

    那不行。Spring通过代理您的bean来提供功能。它将返回一个代理bean,该bean具有对真实对象的引用。因此调用者看到并调用

    proxy.someEnhancedMethod()
    

    但是发生的是

    proxy.someEnhancedMethod() -> some enhanced logic -> target.someEnhancedMethod()
    

    但是在sampleService服务方法中,您没有对代理的引用,而是对目标的引用。基本上,你什么也没得到。我建议将@Async逻辑移到另一个类型,声明该类型的bean并将其注入到您的资源中

    Spring在文档here中解释了上述所有内容