springboot使用多线程调用接口控制层

同样是拿别人的,整体没报错,不过还未经具体测试
配置类: 

package com.tansuo365.test1.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

@Configuration
@EnableAsync
public class AsyncConfig {

    @Bean
    public TaskExecutor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        // 设置核心线程数
        executor.setCorePoolSize(5);
        // 设置最大线程数
        executor.setMaxPoolSize(10);
        // 设置队列容量
        executor.setQueueCapacity(20);
        // 设置线程活跃时间(秒)
        executor.setKeepAliveSeconds(60);
        // 设置默认线程名称
        executor.setThreadNamePrefix("danhao-");
        // 设置拒绝策略
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        // 等待所有任务结束后再关闭线程池
        executor.setWaitForTasksToCompleteOnShutdown(true);
        return executor;
    }
}

注意配置类的新注解 @EnableAsync

控制层:

    @Async
    @RequestMapping("/getChukuNumber")
    public ListenableFuture<String> genBillCode(String type) throws Exception {
        StringBuffer billCodeStr = new StringBuffer();
        billCodeStr.append(chukudanPrefix);
        billCodeStr.append(DateUtil.getCurrentDateStr());
        String todayMaxChukuDanNumber = chukuZongService.getTodayMaxChukuDanNumber();
        if (todayMaxChukuDanNumber != null) {
            billCodeStr.append(StringUtil.formatCode(todayMaxChukuDanNumber));
        } else {
            billCodeStr.append("0001");
        }
        return new AsyncResult<>(billCodeStr.toString());
//        return billCodeStr.toString();
    }

注意控制层的返回类型 返回值 以及新注解@Async
同样的启动类上:

//@EnableCaching
@SpringBootApplication
@MapperScan(value = {"com.xxxxxxxxx.test1.mapper"})
@EnableAsync//开启异步任务
public class Test1Application {

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

}

注意启动类上的 @EnableAsync 注解

猜你喜欢

转载自www.cnblogs.com/ukzq/p/12204138.html
今日推荐