springboot中@Async的使用

@async注解的使用

springboot中的启动类中需要添加注解@EnableAsync来开启异步调用,在需要异步执行的方法上添加@Async(“taskExecutor”)注解进行标注

启动类:

@EnableScheduling
@EnableAsync
@SpringBootApplication
@ComponentScan("com.swj")
public class WebApiApplication {

    public static void main(String[] args) {
        SpringApplication.run(WebApiApplication.class, args);
    }

线程池:一般会添加一个线程池的配置,不影响主线程,异步方法交给单独的线程完成

@Configuration
public class AsyncConfig {

    private static final int MAX_POOL_SIZE = 50;

    private static final int CORE_POOL_SIZE = 20;

    @Bean("taskExecutor")
    public AsyncTaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
        taskExecutor.setMaxPoolSize(MAX_POOL_SIZE);
        taskExecutor.setCorePoolSize(CORE_POOL_SIZE);
        taskExecutor.setThreadNamePrefix("async-task-thread-pool");
        taskExecutor.initialize();
        return taskExecutor;
    }
}

方法调用:需要执行异步调用的方法示例(带有返回值的Future,需要用到AsyncResult)

@Service
public class DeviceProcessServiceImpl implements DeviceProcessService {

    @Autowired
    private DeviceRpcService deviceRpcService;

    @Async("taskExecutor")
    @Override
    public Future>> queryDeviceProcessAbilities(List bindDevices) {
        if (CollectionUtils.isEmpty(bindDevices)) {
            return new AsyncResult<>(Maps.newHashMap());
        }
        List deviceIds = bindDevices.stream().map(BindDeviceDO::getDeviceId).collect(Collectors.toList());

        List devices = deviceRpcService.getDeviceProcessAbility(deviceIds);
        Map> deviceAbilityMap = Maps.newHashMap();
        ...
        return new AsyncResult<>(deviceAbilityMap);
    }
}

对加了@async注解方法有返回值的调用

private ProcessAbilityData asyncCollectProcessAbilities(List bindDevices,
                                                            List bindStaffs, String dccId) {
        // 返回值
        Future>> deviceProcessFutureResult = deviceProcessService
            .queryDeviceProcessAbilities(bindDevices);
        Future>> staffAbilityFutureResult = staffProcessService
            .queryStaffProcessAbilities(bindStaffs, dccId);
        Map> deviceAbilityMap;
        Map> staffAbilityMap;
        try {
            deviceAbilityMap = deviceProcessFutureResult.get();
            staffAbilityMap = staffAbilityFutureResult.get();
        } catch (InterruptedException | ExecutionException e) {
            ...
        }
        return new ProcessAbilityData(deviceAbilityMap, staffAbilityMap);
    }

你可能感兴趣的:(java,java)