SpringBoot版本 :2.1.0.RELEASE
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.1.0.RELEASE</version>
<relativePath />
</parent>
自定义一个@Configuration 配置项
配置异步线程池
例如
/配置核心线程数/
/配置最大线程数/
/配置队列大小/
/活跃时间/
/配置线程池中的线程的名称前缀/
/设置拒绝策略:当pool已经达到max size的时候,如何处理新任务/
package com.xzk6.config;
import com.github.pagehelper.PageHelper;
import com.xzk6.config.async.AsyncTaskProperties;
import com.xzk6.constant.IConstants;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.web.servlet.MultipartConfigFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import javax.servlet.MultipartConfigElement;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
/**
* @author xzk
*/
@Configuration
@Slf4j
public class SysConfigure {
/** 注入配置类 */
private final AsyncTaskProperties config;
public SysConfigure(AsyncTaskProperties config) {
this.config = config;
}
/** 可定义注入Bean名称 和后续需要sync的方法使用 */
@Bean(IConstants.ASYNC_POOL)
public Executor asyncServiceExecutor() {
log.info("start asyncServiceExecutor(狗头保命)");
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
/**配置核心线程数**/
executor.setCorePoolSize(config.getCorePoolSize());
/**配置最大线程数**/
executor.setMaxPoolSize(config.getMaxPoolSize());
/**配置队列大小**/
executor.setQueueCapacity(config.getQueueCapacity());
/**活跃时间**/
executor.setKeepAliveSeconds(config.getKeepAliveSeconds());
/**配置线程池中的线程的名称前缀**/
executor.setThreadNamePrefix("xzk6-syncThread-");
/** 设置拒绝策略:当pool已经达到max size的时候,如何处理新任务**/
/** CALLER_RUNS:不在新线程中执行任务,而是有调用者所在的线程来执行**/
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
/**执行初始化**/
executor.initialize();
return executor;
}
}
线程池参数 AsyncTaskProperties
package com.xzk6.config.async;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
/**
* 线程池配置属性类
* @author xzk
* @date 2020年6月2日23:36:20
*/
@Data
@Component
@ConfigurationProperties(prefix = "task.pool")
public class AsyncTaskProperties {
private int corePoolSize;
private int maxPoolSize;
private int keepAliveSeconds;
private int queueCapacity;
}
task:
pool:
# 核心线程池大小
core-pool-size: 10
# 最大线程数
max-pool-size: 30
# 活跃时间
keep-alive-seconds: 60
# 队列容量
queue-capacity: 3000
package com.xzk6.test.controller;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xzk6.config.redis.RedisUtil;
import com.xzk6.controller.BaseController;
import com.xzk6.test.entity.Test5;
import com.xzk6.test.service.ITest5Service;
import com.xzk6.utils.PageUtil;
import com.xzk6.utils.ResultUtil;
import com.xzk6.utils.Util;
import com.xzk6.utils.UuidUtil;
import com.xzk6.utils.common.CommonUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
/**
*
* 前端控制器
*
*
* @author xzk
* @date 2020年6月2日23:47:46
*/
@Api(description = "测试")
@RestController
@RequestMapping("api/pub/test5")
@Slf4j
public class Test5Controller extends BaseController {
@Autowired
private ITest5Service iTest5Service;
@Autowired
private RedisUtil redisUtil;
/**
* 热点接口测试
*
* @param request
* @param bean
* @return JSONObject
*/
@ApiOperation(value = "查看测试列表(分页)", notes = "查看测试列表(分页)", httpMethod = "POST")
@ApiImplicitParams({})
@ResponseBody
@RequestMapping(value = "/testList", produces = "application/json;charset=utf-8")
public Object findPageList(HttpServletRequest request, Test5 bean) throws Exception {
long timer1 = System.currentTimeMillis();
String uuid = UuidUtil.get32UUID();
Map<String, Object> param = Util.getRequestParams( request );
log.info( "执行流水:开始[" + uuid + "]" + in_pageList + bean );
Integer page = PageUtil.getPage( param );// 获取页码
Integer size = PageUtil.getSize( param );// 获取条数
PageHelper.startPage( page, size );
List<Map<String, Object>> List = iTest5Service.findList( param );
/** 假如我们这个 iTest5Service.test 操作是非同步实时处理。
我们可以异步处理来提高接口响应速度提高性能,
if(牛逼接口){
牛逼的技术驱动业务,
吊炸天的业务给公司带来利益,
然后我们升职加薪,隐去白富美,走上人生巅峰。
}else{
菜鸡单体应用思维驱动不了互联网业务
业务凉凉,项目不验收。
老板开除你,
你露宿接头,饥肠辘辘
然后不小心吃了野味
然后。。。
}
哈哈哈,
我这只是一个小小的逻辑方式。提升性能方式、方法还很多。
大家一起学习。然后一起发财
**/
iTest5Service.test(bean);
PageInfo<Map<String, Object>> pageInfo = new PageInfo<Map<String, Object>>( List );
int count = (int) pageInfo.getTotal();
pageInfo = new PageInfo<Map<String, Object>>( ResultUtil.Listvaluechangenull( List ) );
log.info( "执行流水:结束[" + uuid + "] 总耗时 " + (System.currentTimeMillis() -timer1) );
return CommonUtil.successJson( count,pageInfo.getList() );
}
}
package com.xzk6.test.service;
import com.xzk6.test.entity.Test5;
import com.baomidou.mybatisplus.extension.service.IService;
import java.util.List;
import java.util.Map;
/**
*
* 服务类接口
*
*
* @author xzk
* @since 2020年6月2日23:47:46
*/
public interface ITest5Service extends IService<Test5> {
/**
*
* 列表
*
*
* @param map
* @return List
List<Map<String, Object>> findList(Map<String, Object> map) throws Exception;
/**
*
* 异步测试接口
*
*
* @param bean
* @return void
* @author xzk
* @date 2020年6月2日23:47:46
*/
void test(Test5 bean) throws Exception;
}
package com.xzk6.test.service.impl;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xzk6.constant.IConstants;
import com.xzk6.mapper.test.Test5Mapper;
import com.xzk6.test.entity.Test5;
import com.xzk6.test.service.ITest5Service;
import com.xzk6.utils.UuidUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
import java.util.Map;
/**
*
* 服务实现类
*
*
* @author xzk
* @since 2020年6月2日23:47:46
*/
@Service
@Slf4j
public class Test5ServiceImpl extends ServiceImpl<Test5Mapper, Test5> implements ITest5Service {
/**
*
* 列表
*
*
* @param map
* @return List
@Override
public List<Map<String, Object>> findList(Map<String, Object> map) throws Exception {
return baseMapper.findList( map );
}
/**
*
* 异步测试接口
*
*
* @param bean
* @return void
* @author xzk
* @date 2020年6月2日23:47:46
*/
@Async(IConstants.ASYNC_POOL)
@Override
@Transactional(rollbackFor = {Exception.class})
public void test(Test5 bean) throws Exception {
log.info("进入----异步 "+ bean);
Thread.sleep(3000);
log.info("结束----异步");
}
}
核心是 在调用方法加上 @Async
核心是 在启动主类加上 @EnableAsync
package com.xzk6;
import com.github.xiaoymin.swaggerbootstrapui.annotations.EnableSwaggerBootstrapUI;
import com.xzk6.config.Init;
import lombok.extern.slf4j.Slf4j;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ApplicationContext;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.transaction.annotation.EnableTransactionManagement;
/**
* @author xzk
*/
@EnableAsync
@SpringBootApplication // boot
@EnableTransactionManagement// 事务
@EnableScheduling // 启用定时器
@EnableSwaggerBootstrapUI // swagger
//@ComponentScan("com.xzk6")
@MapperScan(basePackages = {"com.xzk6.mapper"})
@Slf4j
public class ApiApplication {
/**
* Start
*/
public static void main(String[] args) {
long timer = System.currentTimeMillis();
SpringApplication springapplication = new SpringApplication( ApiApplication .class );
ApplicationContext applicationContext = springapplication.run( args );
log.info( "------------------Bean Nums" + applicationContext.getBeanDefinitionCount() );
Init.init();// 启动私有服务
log.info( "服务启动[成功] 耗时:[" + ((System.currentTimeMillis() - timer) / 1000) + " 秒]" );
}
}
完成! 是不是很简单 来验证结果