关于springboot:springboot-项目框架搭建

34次阅读

共计 1769 个字符,预计需要花费 5 分钟才能阅读完成。

如果我须要使得一个办法采取异步执行
如果我须要使得一个办法采取异步执行,并且执行的时候须要指定线程池,那么我须要做三步操作。
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 + "/***")
                .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
    }
}

正文完
 0