Java @异步在REST类中不起作用
我正在从事一个使用Spring构建的WebService项目。所有配置都是使用注释完成的。有一种方法可以发送推送通知。因为有许多通知要发送,这会导致响应延迟。因此,我将@Async注释应用于我的“sendPushnotification”方法。但是,在响应方面仍然没有任何改进。我浏览了一些博客和stackoverflow来找到解决方案。但是,没有成功。我已将以下注释应用于我的服务类Java @异步在REST类中不起作用,java,spring,asynchronous,annotations,Java,Spring,Asynchronous,Annotations,我正在从事一个使用Spring构建的WebService项目。所有配置都是使用注释完成的。有一种方法可以发送推送通知。因为有许多通知要发送,这会导致响应延迟。因此,我将@Async注释应用于我的“sendPushnotification”方法。但是,在响应方面仍然没有任何改进。我浏览了一些博客和stackoverflow来找到解决方案。但是,没有成功。我已将以下注释应用于我的服务类 @Component @Configuration @EnableAspectJAutoProxy @Enable
@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);
...
}
@POST
@路径(“/sampleService”)
@使用(MediaType.APPLICATION\u FORM\u URLENCODED)
公共响应sampleService(@FormParam…){
...
列出评论者=;
发送通知(评论);
...
}
我的异步方法
@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);
}
}
}
}
@Async
私有void sendPushnotification(列出注释者){
if(注释者!=null){
for(用户:评论员){
试一试{
int numNewComments=ps.getCommentsUnseenByUser(用户);
sendMessage(“ios”,用户,“2”,以及“+numNewComments”,true”);
}捕获(例外e){
log.error(e.getMessage(),e);
}
}
}
}
我遗漏了什么吗?您正在调用此
上的方法
sendPushnotification(commentors);
// equivalent to
this.sendPushnotification(commentors);
那不行。Spring通过代理您的bean来提供功能。它将返回一个代理bean,该bean具有对真实对象的引用。因此调用者看到并调用
proxy.someEnhancedMethod()
但是发生的是
proxy.someEnhancedMethod() -> some enhanced logic -> target.someEnhancedMethod()
但是在您的sampleService
服务方法中,您没有对代理的引用,而是对目标的引用。基本上,你什么也没得到。我建议将@Async
逻辑移到另一个类型,声明并将该类型的bean注入到您的资源中
Spring在文档中解释了以上所有内容。您是否已使用适当数量的线程注册了执行器?您是否已将Jersey(或您正在使用的任何JAX-RS实现)与Spring正确集成?是的。它已正确配置。这个应用程序运行得非常好。所有请求和响应都很好。我正在查看链接。