如何使用球衣进行异步方法调用?
How to make an Async method call using jersey?
我正在开发一个 dropwizard 应用程序。我有一个资源 EmployeeResource,它会触发邮件 api.
@Path("/employee")
public class EmployeeResource {
@GET
@Path("/list")
public void getEmployeeDetails(){
//DAO call and other stuff
mailClient.sendMail();
}
}
现在,sendMail 方法将从数据库中获取一些详细信息,然后调用邮件 API。我希望 sendMail 方法不阻止“/employee/list”请求。有没有办法让 sendMail 方法异步?
我查找并找到了使 API 异步的解决方案,但我只希望我的 sendMail 方法是异步的。我该如何解决?
编辑:我不使用Spring框架,只是使用Dropwizard框架。
要异步执行方法或任何代码块,您始终可以通过实现 Runnable 接口来创建新线程。对于您的要求如下:
@Path("/employee")
public class EmployeeResource {
@GET
@Path("list")
@Async
public void getEmployeeDetails(){
//DAO call and other stuff
new Thread(new Runnable() {
public void run() {
mailClient.sendMail();
}
}).start();
}
}
[edit1] 如果您认为发送电子邮件的并发性很高,那么您可以使用 ExecutorService 内部有队列(您阅读了更多相关信息 here ):
private static final ExecutorService TASK_EXECUTOR = Executors.newCachedThreadPool();
您调用发送邮件方法的部分代码如下:
TASK_EXECUTOR.submit(new Runnable() {
@Override
public void run() {
mailClient.sendMail();
}
});
我正在开发一个 dropwizard 应用程序。我有一个资源 EmployeeResource,它会触发邮件 api.
@Path("/employee")
public class EmployeeResource {
@GET
@Path("/list")
public void getEmployeeDetails(){
//DAO call and other stuff
mailClient.sendMail();
}
}
现在,sendMail 方法将从数据库中获取一些详细信息,然后调用邮件 API。我希望 sendMail 方法不阻止“/employee/list”请求。有没有办法让 sendMail 方法异步?
我查找并找到了使 API 异步的解决方案,但我只希望我的 sendMail 方法是异步的。我该如何解决?
编辑:我不使用Spring框架,只是使用Dropwizard框架。
要异步执行方法或任何代码块,您始终可以通过实现 Runnable 接口来创建新线程。对于您的要求如下:
@Path("/employee")
public class EmployeeResource {
@GET
@Path("list")
@Async
public void getEmployeeDetails(){
//DAO call and other stuff
new Thread(new Runnable() {
public void run() {
mailClient.sendMail();
}
}).start();
}
}
[edit1] 如果您认为发送电子邮件的并发性很高,那么您可以使用 ExecutorService 内部有队列(您阅读了更多相关信息 here ):
private static final ExecutorService TASK_EXECUTOR = Executors.newCachedThreadPool();
您调用发送邮件方法的部分代码如下:
TASK_EXECUTOR.submit(new Runnable() {
@Override
public void run() {
mailClient.sendMail();
}
});