@async注解的使用

異步調用

1.使用:

springboot中的啟動類中需要添加注解@EnableAsync來開啟異步調用,在需要異步執(zhí)行的方法上添加@Async("taskExecutor")注解進行標注。

@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Async {

    /**
     * A qualifier value for the specified asynchronous operation(s).
     * <p>May be used to determine the target executor to be used when executing this
     * method, matching the qualifier value (or the bean name) of a specific
     * {@link java.util.concurrent.Executor Executor} or
     * {@link org.springframework.core.task.TaskExecutor TaskExecutor}
     * bean definition.
     * <p>When specified on a class level {@code @Async} annotation, indicates that the
     * given executor should be used for all methods within the class. Method level use
     * of {@code Async#value} always overrides any value set at the class level.
     * @since 3.1.2
     */
    String value() default "";

}

一般會添加一個線程池的配置,不影響主線程,異步方法交給單獨的線程完成

@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;
    }
}

需要執(zhí)行異步調用的方法示例(帶有返回值的Future<T>,需要用到AsyncResult)

@Service
public class DeviceProcessServiceImpl implements DeviceProcessService {

    @Autowired
    private DeviceRpcService deviceRpcService;

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

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

對加了@async注解方法有返回值的調用

private ProcessAbilityData asyncCollectProcessAbilities(List<BindDeviceDO> bindDevices,
                                                            List<BindStaffDO> bindStaffs, String dccId) {
        // 返回值
        Future<Map<Long, List<ProcessDTO>>> deviceProcessFutureResult = deviceProcessService
            .queryDeviceProcessAbilities(bindDevices);
        Future<Map<String, List<ProcessDTO>>> staffAbilityFutureResult = staffProcessService
            .queryStaffProcessAbilities(bindStaffs, dccId);
        Map<Long, List<ProcessDTO>> deviceAbilityMap;
        Map<String, List<ProcessDTO>> staffAbilityMap;
        try {
            deviceAbilityMap = deviceProcessFutureResult.get();
            staffAbilityMap = staffAbilityFutureResult.get();
        } catch (InterruptedException | ExecutionException e) {
            ...
        }
        return new ProcessAbilityData(deviceAbilityMap, staffAbilityMap);
    }
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • 1.ios高性能編程 (1).內層 最小的內層平均值和峰值(2).耗電量 高效的算法和數(shù)據(jù)結構(3).初始化時...
    歐辰_OSR閱讀 30,262評論 8 265
  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,618評論 19 139
  • Android 自定義View的各種姿勢1 Activity的顯示之ViewRootImpl詳解 Activity...
    passiontim閱讀 179,154評論 25 708
  • 夏冰是我的第一個朋友,真正意義上的不同于玩伴的朋友。 我忘了你是幾年級轉來我們班級的,只記得你第一次上講臺自我介紹...
    蘇唐西閱讀 322評論 0 0
  • 牽來的文字 植物也有知覺,這是并不稀奇,比如含羞草一碰就低頭,豬籠草可以捉蟲什么的。但植物的知覺遠比你想像的要發(fā)達...
    fty閱讀 410評論 0 0

友情鏈接更多精彩內容