简体   繁体   中英

How to make an Async method call using jersey?

I'm working on a dropwizard application. I have a resource, EmployeeResource, which triggers a mail api.

@Path("/employee")
public class EmployeeResource {
    @GET
    @Path("/list")
    public void getEmployeeDetails(){
        //DAO call and other stuff

        mailClient.sendMail();
    }
}

Now, sendMail method will fetch some details from DB, and then make a call to a mail API. I want the method sendMail to not block the "/employee/list" request. Is there a way to make the sendMail method async?

I looked it up and found solutions to make an API async, but I want just my sendMail method to be async. How do I solve this?

Edit: I'm not using Spring framework, just using Dropwizard framework.

To make Async execution of method or any code block you can always create new Thread by implementing the Runnable Interface. For your requirement like below :

@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] If you think concurrency would be high for sending out emails then you can you use ExecutorService which has queue internally (you read more about it here ):

private static final ExecutorService TASK_EXECUTOR = Executors.newCachedThreadPool();

Your calling send mail method part code will look like :

TASK_EXECUTOR.submit(new Runnable() {
            @Override
            public void run() {
                mailClient.sendMail();
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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