controller异步处理请求

1,需求场景

后台数据处理需要多个远程调用,数据拉取推送等IO操作很耗时或者时间预估困难,手动重新推送或拉取数据等操作。

2,第一种方案

直接在controller创建子线程

@RestController
@RequestMapping("/pulldata")
@Slf4j
public class PullOrderController {
    @Autowired
    private TestService testService;
    /**
     * 定义任务线程池,手动处理的情况比较少,不需要太多线程数
     */
    private static ExecutorService threadPool = new ThreadPoolExecutor(1, 5, 1000, TimeUnit.MILLISECONDS, new SynchronousQueue<Runnable>(),Executors.defaultThreadFactory(),new ThreadPoolExecutor.AbortPolicy());
    /**
     * 拉取调拨单
     *
     * @param sapRequestPO
     * @return
     */
    @PostMapping(value = "test")
    public Result list(@RequestBody SapRequestPO sapRequestPO) {
        log.debug("主线程开始");
        Callable<Boolean> callable = new Callable<Boolean>() {
            @Override
            public Boolean call(){
                log.debug("子线程开始");
                boolean res = testService.pullStockOutOrderByQm(
                        sapRequestPO.getFromWho(),
                        sapRequestPO.getShopno(),
                        sapRequestPO.getSaledate(),
                        sapRequestPO.getOrderno());
                log.debug("子线程结束");
                return res;
            }
        };
        threadPool.submit(callable);
        log.debug("主线程结束");
        return Result.success();
    }
}

2,第二种方案

耗时任务实现 Runnable

@Slf4j
@Service
@AllArgsConstructor
public class IotService implements Runnable{

    private final HwApicService hwApicService;
    private final ApoiSbxxDao apoiSbxxDao;

    /**
     * 同步物联设备到数据库
     */
    @SneakyThrows
    @Override
    public void run() {
//        //当前偏移量
//        int offset = 0;
//        //当前页返回行数
//        int resDataSize = 0;
//        String gxsjStr = DateUtil.formatDateTime(new Date());
//        //循环同步物联设备
//        do {
//            resDataSize = extracted(gxsjStr, offset);
//            offset = offset + 1000;
//        }
//        while (resDataSize == 1000);
//        log.warn("同步完成,offset:{}",offset);
//        apoiSbxxDao.del("iot", gxsjStr);
        //模拟耗时任务执行60秒
        System.out.println("任务执行开始");
        Thread.sleep(60000);
        System.out.println("任务执行结束");
    }
}
@Api(tags = "测试")
@RequestMapping("/tup")
@RestController
public class TupController {

    private final IotService wlService;

    public TupController(IotService wlService) {
        this.wlService = wlService;
    }

    @GetMapping("/syncget")
    @ApiOperation(value = "测试异步请求")
    public Rest<String> test1() throws Exception {
        //不需要返回值
        CompletableFuture.runAsync(wlService);
        return Rest.success(DateUtil.now());
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

占星安啦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值