+-
springboot 项目框架搭建

如果我需要使得一个方法采取异步执行
如果我需要使得一个方法采取异步执行,并且执行的时候需要指定线程池,那么我需要做三步操作。
1、配置线程池

@Configuration
@EnableAsync
public class ExecutorConfig implements AsyncConfigurer {

    @Bean("asyncServiceExecutor")
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //配置核心线程数
        executor.setCorePoolSize(10);
        //配置最大线程数
        executor.setMaxPoolSize(20);
        //配置队列大小
        executor.setQueueCapacity(99999);
        //配置线程池中的线程的名称前缀
        executor.setThreadNamePrefix("async-service-");
        // rejection-policy:当pool已经达到max size的时候,如何处理新任务
        // CALLER_RUNS:不在新线程中执行任务,而是由调用者所在的线程来执行
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //执行初始化
        executor.initialize();

        return executor;
    }
}

2、启用异步方法注解

@EnableAsync

3、在方法上开启注解,并配置线程池

@Async("asyncServiceExecutor")

springboot系统启动时初始化数据

@Component
@Slf4j
public class ApplicationRunnerImpl implements ApplicationRunner {
    @Override
    public void run(ApplicationArguments args) {

    }
}

配置拦截器
1、添加拦截器配置文件

@Configuration
public class MyWebConfig implements WebMvcConfigurer {

    @Value("${api.contextPath}")
    private String apiContextPath;

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {

    }

    public String getLocalFileServerDir() {
        return System.getProperty("user.dir") + "/data/";
    }

    @Resource
    private SessionInterceptor sessionInterceptor;

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
           registry.addInterceptor(sessionInterceptor)
                .addPathPatterns(apiContextPath + "/**")
                .excludePathPatterns(apiContextPath + "/user/test")
                .excludePathPatterns(apiContextPath + "/log/**");
    }

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("*")
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "DELETE", "PUT", "PATCH")
                .maxAge(3600 * 24)
                .allowedHeaders("*")// 允许头部设置
                .allowCredentials(true);  // 是否发送cookie
    }
}

springboot测试类

@SpringBootTest
@RunWith(SpringRunner.class)