乐趣区

关于java:SpringBoot中如何优雅的使用多线程

在 SpringBoot 利用中,常常会遇到在一个接口中,同时做事件 1,事件 2,事件 3,如果同步执行的话,则本次接口工夫取决于事件 1 2 3 执行工夫之和;如果三件事同时执行,则本次接口工夫取决于事件 1 2 3 执行工夫最长的那个,正当应用多线程,能够大大缩短接口工夫。那么在 SpringBoot 利用中如何优雅的应用多线程呢?

疾速应用
SpringBoot 利用中须要增加 @EnableAsync 注解,来开启异步调用,个别还会配置一个线程池,异步的办法交给特定的线程池实现,如下:

@Configuration
@EnableAsync
public class AsyncConfiguration {@Bean("doSomethingExecutor")
    public Executor doSomethingExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 外围线程数:线程池创立时候初始化的线程数
        executor.setCorePoolSize(10);
        // 最大线程数:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过外围线程数的线程
        executor.setMaxPoolSize(20);
        // 缓冲队列:用来缓冲执行工作的队列
        executor.setQueueCapacity(500);
        // 容许线程的闲暇工夫 60 秒:当超过了外围线程之外的线程在闲暇工夫达到之后会被销毁
        executor.setKeepAliveSeconds(60);
        // 线程池名的前缀:设置好了之后能够不便咱们定位解决工作所在的线程池
        executor.setThreadNamePrefix("do-something-");
        // 缓冲队列满了之后的回绝策略:由调用线程解决(个别是主线程)executor.setRejectedExecutionHandler(new ThreadPoolExecutor.DiscardPolicy());
        executor.initialize();
        return executor;
    }

}

AsyncService

@Slf4j
@Service
public class AsyncService {

    // 指定应用 beanname 为 doSomethingExecutor 的线程池
    @Async("doSomethingExecutor")
    public String doSomething(String message) {log.info("do something, message={}", message);
        try {Thread.sleep(1000);
        } catch (InterruptedException e) {log.error("do something error:", e);
        }
        return message;
    }
}

AsyncController

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/open/something")
    public String something() {
        int count = 10;
        for (int i = 0; i < count; i++) {asyncService.doSomething("index =" + i);
        }
        lon
        return "success";
    }
}

拜访:127.0.0.1:8080/open/something,日志如下

2020-04-19 23:42:42.486 INFO 21168 — [io-8200-exec-17] x.g.b.system.controller.AsyncController : do something end, time 8 milliseconds
2020-04-19 23:42:42.488 INFO 21168 — [do-something-1] x.gits.boot.system.service.AsyncService : do something, message=index = 0
2020-04-19 23:42:42.488 INFO 21168 — [do-something-5] x.gits.boot.system.service.AsyncService : do something, message=index = 4
2020-04-19 23:42:42.488 INFO 21168 — [do-something-4] x.gits.boot.system.service.AsyncService : do something, message=index = 3
2020-04-19 23:42:42.488 INFO 21168 — [do-something-6] x.gits.boot.system.service.AsyncService : do something, message=index = 5
2020-04-19 23:42:42.488 INFO 21168 — [do-something-9] x.gits.boot.system.service.AsyncService : do something, message=index = 8
2020-04-19 23:42:42.488 INFO 21168 — [do-something-8] x.gits.boot.system.service.AsyncService : do something, message=index = 7
2020-04-19 23:42:42.488 INFO 21168 — [do-something-10] x.gits.boot.system.service.AsyncService : do something, message=index = 9
2020-04-19 23:42:42.488 INFO 21168 — [do-something-7] x.gits.boot.system.service.AsyncService : do something, message=index = 6
2020-04-19 23:42:42.488 INFO 21168 — [do-something-2] x.gits.boot.system.service.AsyncService : do something, message=index = 1
2020-04-19 23:42:42.488 INFO 21168 — [do-something-3] x.gits.boot.system.service.AsyncService : do something, message=index = 2

由此可见曾经达到异步执行的成果了,并且应用到了咱们配置的线程池

获取异步办法返回值

当异步办法有返回值时,如何获取异步办法执行的返回后果呢?这时须要异步调用的办法带有返回值 CompletableFuture。
CompletableFuture 是对 Feature 的加强,Feature 只能解决简略的异步工作,而 CompletableFuture 能够将多个异步工作进行简单的组合。如下:

AsyncService

@Slf4j
@Service
public class AsyncService {@Async("doSomethingExecutor")
    public CompletableFuture<String> doSomething1(String message) throws InterruptedException {log.info("do something1: {}", message);
        Thread.sleep(1000);
        return CompletableFuture.completedFuture("do something1:" + message);
    }

    @Async("doSomethingExecutor")
    public CompletableFuture<String> doSomething2(String message) throws InterruptedException {log.info("do something2: {}", message);
        Thread.sleep(1000);
        return CompletableFuture.completedFuture("; do something2:" + message);
    }

    @Async("doSomethingExecutor")
    public CompletableFuture<String> doSomething3(String message) throws InterruptedException {log.info("do something3: {}", message);
        Thread.sleep(1000);
        return CompletableFuture.completedFuture("; do something3:" + message);
    }
}

AsyncController

@RestController
public class AsyncController {

    @Autowired
    private AsyncService asyncService;

    @GetMapping("/open/somethings")
    public String somethings() {CompletableFuture<String> createOrder = asyncService.doSomething1("create order");
        CompletableFuture<String> reduceAccount = asyncService.doSomething2("reduce account");
        CompletableFuture<String> saveLog = asyncService.doSomething3("save log");

        // 期待所有工作都执行完
        CompletableFuture.allOf(createOrder, reduceAccount, saveLog).join();
        // 获取每个工作的返回后果
        String result = createOrder.get() + reduceAccount.get() + saveLog.get();
        return result;
    }
}

注意事项

@Async 注解会在以下几个场景生效,也就是说明明应用了 @Async 注解,但就没有走多线程

1. 异步办法应用 static 关键词润饰
2. 异步类不是一个 Spring 容器的 bean(个别应用注解 @Component 和 @Service,并且能被 Spring 扫描到)
3.SpringBoot 利用中没有增加 @EnableAsync 注解
4. 在同一个类中,一个办法调用另外一个有 @Async 注解的办法,注解不会失效。起因是 @Async 注解的办法,是在代理类中执行的

退出移动版