WebAsyncTask直接释放处理线程连接,提高服务器吞吐量

两个基本概念:

  1. 处理线程:处理线程 属于 web 服务器线程,负责 处理用户请求,采用 线程池 管理。

  2. 异步线程:异步线程 属于 用户自定义的线程,可采用 线程池管理

工具类:

public class WebAsyncUtils {
    Logger logger = LoggerFactory.getLogger(WebAsyncUtils.class);

    /**
     * 移除初始化
     * @param callable
     * @return
     */
    public WebAsyncTask instance(Callable callable) {
        WebAsyncTask asyncTask = new WebAsyncTask<>(Constants.OUT_TIME, callable);

        asyncTask.onCompletion(() -> logger.info("任务执行完成"));
        asyncTask.onError(() -> {
            return new JsonResponse(JsonResponse.CODE_FAILURE, "out_line");
        });
        asyncTask.onTimeout(() -> {
            return new JsonResponse(JsonResponse.CODE_FAILURE, "out_time_line");
        });

        return asyncTask;
    }
}

配置:

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

	@Resource private CurrentUserMethodArgumentResolver currentUserMethodArgumentResolver;

//    WebMvcRegistrationsAdapter a1 = new WebMvcRegistrationsAdapter();

    @Bean
    public HttpMessageConverter responseBodyConverter(){
        StringHttpMessageConverter converter = new StringHttpMessageConverter(Charset.forName("UTF-8"));
        return converter;
    }

    @Override
    public void configureMessageConverters(List> converters) {
//        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
//        //自定义配置...
//        FastJsonConfig config = new FastJsonConfig();
//        /**
//         * QuoteFieldNames———-输出key时是否使用双引号,默认为true
//         WriteMapNullValue——–是否输出值为null的字段,默认为false
//         WriteNullNumberAsZero—-数值字段如果为null,输出为0,而非null
//         WriteNullListAsEmpty—–List字段如果为null,输出为[],而非null
//         WriteNullStringAsEmpty—字符类型字段如果为null,输出为”“,而非null
//         WriteNullBooleanAsFalse–Boolean字段如果为null,输出为false,而非null
//         */
//        config.setCharset(Charset.forName("UTF-8"));
//        config.setSerializerFeatures(SerializerFeature.PrettyFormat);
////        config.setSerializerFeatures(SerializerFeature.WriteMapNullValue);
//        converter.setFastJsonConfig(config);

        converters.add(responseBodyConverter());
    }

    // springboot 方式注入
//    通过 WebMvcRegistrations 来注入 RequestMappingHandlerMapping
    @Configuration
    public class WebMvcRegistrationsConfig implements WebMvcRegistrations {
        @Override
        public RequestMappingHandlerMapping getRequestMappingHandlerMapping() {
            return new MyRequestMappingHandlerMapping();
        }
    }


    @Override
    public void configureAsyncSupport(final AsyncSupportConfigurer configurer) {
        configurer.setDefaultTimeout(60 * 1000L);
        configurer.registerCallableInterceptors(timeoutInterceptor());
        configurer.setTaskExecutor(threadPoolTaskExecutor());
    }

    @Bean
    public TimeoutCallableProcessingInterceptor timeoutInterceptor() {
        return new TimeoutCallableProcessingInterceptor();
    }

    @Bean
    public ThreadPoolTaskExecutor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor t = new ThreadPoolTaskExecutor();
        t.setCorePoolSize(10);
        t.setMaxPoolSize(50);
        t.setThreadNamePrefix("MISSION");
        return t;
    }
}

使用:

    @CrossOrigin
    @RequestMapping(value = "missions")
    public WebAsyncTask getMyMissionList(Integer fid,Integer classId, Integer uid,int page,int pageSize) {
        WebAsyncTask asyncTask = new WebAsyncUtils().instance(()-> {
            try {
                List list = missionService.getMyMissionList(fid, classId, uid, page, pageSize);
                return new JsonResponse(JsonResponse.CODE_SUCCESS, "success").put("list", list)
                        .put("prefix", env.getProperty("STATIC.RESOURCE.URL") + env.getProperty("STATIC.RESOURCE.PIC.COVER"));
            } catch (Exception e) {
                e.printStackTrace();
                return new JsonResponse(JsonResponse.CODE_FAILURE, e.getMessage());
            }
        });
        return asyncTask;
    }

详解Spring/Spring boot异步任务编程WebAsyncTask

你可能感兴趣的:(并发编程)