@ Async-- easily SpringBoot of open asynchronous tasks

Asynchronous tasks

In many businesses, we need to take into account the asynchronous execution of certain tasks, particularly during lengthy calls http interface,
for example:

  • SMS: After we call third-party SMS interface to receive a response will generally result in real-time, but the result does not represent the message was successfully sent, but said the third-party interface to check the basic data have not been informed of the problem receive your SMS request. As for the real message sending process is asynchronous processing.
  • Payment interface: general payment class interface transfer operations are performed asynchronously, and then go to inform the caller
  • Download large amount of data tables: general export large amounts of data because too much data tables, sql complex lead to time-consuming, as users wait for the page is likely to occur overtime and other reasons. So many are exported in the form of job creation, asynchronous, then generate reports to Download Center has generated a good report.

Of course, there are too many scenes will not list them.

Create a new thread

There may be many brothers'm still achieve Runnable to achieve a new thread to do asynchronous tasks through inheritance or Thread, some brothers were using thread pool Executors.newFixedThreadPool () ;, but I do not want to lazy to write so many things, I do not so I like to create the wheel used @Async.

@Async Profile

  • @Async on the method must be registered before use by @EnableAsync open asynchronous calls. (Of course, can also open xml configuration will not be discussed here)
  • In Spring, the method @Async based tagging, called asynchronous methods; these methods when executed, will be executed in a separate thread, the caller without waiting for its completion, we can continue with other operations.
  • In the asynchronous method above are denoted by the @Async annotation means that the process is run asynchronously. Remember, though, this method must be public, and, in its own class, call the asynchronous method is invalid.

Simple to use @Async

No return value of asynchronous tasks

New service for executing asynchronous tasks

package com.zhibo.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;

@EnableAsync
@Service
@Slf4j
public class AsyncDemoService {
    @Async
    public void AsyncTest1(int num) {
        log.info("----------AsyncTest1 num:{} ",num);
    }

    @Async
    public void AsyncTest2(int num){
        log.info("----------AsyncTest2 num:{} ",num);
    }

	// 有返回值的复杂异步任务
    @Async
    public Future<String> AsyncTest(int num)throws Exception{
        log.info("----------AsyncTest1 num:{} ",num);
        Thread.sleep(2000);
        return new AsyncResult<String>("Rsp AsyncTest num:"+num);
    }

	// 错误案例,同一个类中调用是同步的
    public void AsyncTestX(int num) throws Exception{
        AsyncTest1(num);
        AsyncTest2(num);
    }
}

Test Case

	@Autowired
    private AsyncDemoService asyncDemoService;

    @Test
    public void asyncTest() throws Exception{
        for (int i = 0 ; i<5;i++){
            asyncDemoService.AsyncTest1(i);
            asyncDemoService.AsyncTest2(i);
        }
        log.info("asyncTest success");
    }

Output Log

[INFO ] [zhibo-test] 2019-04-18 16:33:22.967 [main] [] [] [] com.zhibo.test.service.AsyncDemoServiceTest - asyncTest success
[INFO ] [zhibo-test] 2019-04-18 16:33:22.975 [SimpleAsyncTaskExecutor-1] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest1 num:0 
[INFO ] [zhibo-test] 2019-04-18 16:33:22.975 [SimpleAsyncTaskExecutor-6] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest2 num:2 
[INFO ] [zhibo-test] 2019-04-18 16:33:22.975 [SimpleAsyncTaskExecutor-9] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest1 num:4 
[INFO ] [zhibo-test] 2019-04-18 16:33:22.975 [SimpleAsyncTaskExecutor-8] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest2 num:3 
[INFO ] [zhibo-test] 2019-04-18 16:33:22.975 [SimpleAsyncTaskExecutor-3] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest1 num:1 
[INFO ] [zhibo-test] 2019-04-18 16:33:22.975 [SimpleAsyncTaskExecutor-10] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest2 num:4 
[INFO ] [zhibo-test] 2019-04-18 16:33:22.975 [SimpleAsyncTaskExecutor-5] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest1 num:2 
[INFO ] [zhibo-test] 2019-04-18 16:33:22.975 [SimpleAsyncTaskExecutor-2] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest2 num:0 
[INFO ] [zhibo-test] 2019-04-18 16:33:22.975 [SimpleAsyncTaskExecutor-7] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest1 num:3 
[INFO ] [zhibo-test] 2019-04-18 16:33:22.975 [SimpleAsyncTaskExecutor-4] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest2 num:1 

@Async is as simple as headstrong, I admit I'm lazy, but lazy is one of the virtues of the program ape!

It returns a value of multi-threaded asynchronous tasks

Test Case

	@Autowired
    private AsyncDemoService asyncDemoService;

    @Test
    public void asyncTest() throws Exception{
        //用于收集每个线程的Future
        List<Future<String>> resultList = new ArrayList<>();
        for (int i = 0 ; i<5;i++){
            Future<String> future = asyncDemoService.AsyncTest(i);
            resultList.add(future);
        }
        //开始处理返回值
        for (Future<String> future:resultList){
            //get方法是阻塞式的
            log.info(future.get());
        }
        log.info("asyncTest success");
    }

Output Log

[INFO ] [zhibo-test] 2019-04-18 20:06:56.547 [SimpleAsyncTaskExecutor-5] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest1 num:4 
[INFO ] [zhibo-test] 2019-04-18 20:06:56.547 [SimpleAsyncTaskExecutor-2] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest1 num:1 
[INFO ] [zhibo-test] 2019-04-18 20:06:56.547 [SimpleAsyncTaskExecutor-4] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest1 num:3 
[INFO ] [zhibo-test] 2019-04-18 20:06:56.547 [SimpleAsyncTaskExecutor-3] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest1 num:2 
[INFO ] [zhibo-test] 2019-04-18 20:06:56.547 [SimpleAsyncTaskExecutor-1] [] [] [] com.zhibo.service.AsyncDemoService - ----------AsyncTest1 num:0 
[INFO ] [zhibo-test] 2019-04-18 20:06:59.540 [main] [] [] [] com.zhibo.test.service.AsyncDemoServiceTest - Rsp AsyncTest num:0
[INFO ] [zhibo-test] 2019-04-18 20:06:59.540 [main] [] [] [] com.zhibo.test.service.AsyncDemoServiceTest - Rsp AsyncTest num:1
[INFO ] [zhibo-test] 2019-04-18 20:06:59.541 [main] [] [] [] com.zhibo.test.service.AsyncDemoServiceTest - Rsp AsyncTest num:2
[INFO ] [zhibo-test] 2019-04-18 20:06:59.541 [main] [] [] [] com.zhibo.test.service.AsyncDemoServiceTest - Rsp AsyncTest num:3
[INFO ] [zhibo-test] 2019-04-18 20:06:59.541 [main] [] [] [] com.zhibo.test.service.AsyncDemoServiceTest - Rsp AsyncTest num:4
[INFO ] [zhibo-test] 2019-04-18 20:06:59.541 [main] [] [] [] com.zhibo.test.service.AsyncDemoServiceTest - asyncTest success

done ~ still simple. Brothers roll up sleeves refueling dry.
Digression: the feeling now is not a bad mix industry more than a few years ago? A friend find a job in Wuhan abnormalities did not go well, compared to the north of Guangzhou-Shenzhen from Hangzhou to drop one-third? And are interviewing airplanes and entry tighten the screws ...
I heard that there are one million concurrent interviewer asks how to handle the business, probably I was too dishes I think this interview questions have BUG!
1, does not describe how specific business scenario design?
2. What complicated by that? I am not referring to the number of requests per second? A second one million in order to ensure that the response speed of the server you want, then how many? This question is a work in 2034 is not right,
I have no way because of work exposure to high concurrency to know if this one is not particularly big science under God willing grateful! Thank you

Published 18 original articles · won praise 45 · views 110 000 +

Guess you like

Origin blog.csdn.net/zhibo_lv/article/details/89387317