在Java开发中经常使用到一些比较常用的通用性代码,这里部分整理出来,记录一下零碎的知识代码,方便以后使用,以工具类形式给出;
// 不使用定时任务,定时按时间轮询启动新线程执行某业务
@Service
public class Biz01Service(
@Autowired
private ScheduledExecutorService scheduledExecutorService;
/**
* java内部实现,不用定时任务,
* 从当前时间开始延时0秒,每隔30秒重复执行一次执行器任务
*/
public void fun01() {
//...other code..
// 从当前时间开始延时0秒,每隔30秒重复执行一次执行器,直到任务介绍终止任务
scheduledExecutorService.scheduleWithFixedDelay(
new XxxBizExecutor(param1, param2, param3), 0, 30, TimeUnit.SECONDS
);
//...other code..
}
}
执行器类,业务逻辑
//执行器类,业务处理逻辑
@Service
public class XxxBizExecutor implements Runnable {
@Autowired
private UserMapper userMappers;
@Autowired
private ProductService productServices
private static UserMapper userMapper;
private static ProductService productService;
private String param1;
private long param2;
private String param3;
public XxxBizExecutor(){}
//构造函数初始化变量
public XxxBizExecutor(String param1, long param2, String param3){
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
}
// 启动应用时,仅一次初始化相关Bean对象;
@PostConstruct
public void initData() {
this.userMapper = userMappers;
this.productService = productServices;
}
// 执行器的具体执行业务逻辑
@Override
public void run() {
//...biz code..
int num = productService.getCount(param1)
//达到预期条件,即库存为0执行,否则不执行
if (0 == num) {
//...biz logic...
//主动抛出异常,退出当前执行任务
throw new Exception();
}
}
}
// 用户自定义线程池
@Configuration
public class UserThreadPoolConfig {
/**用户自定义线程池,异步的多线程之间不能共享请求的头信息*/
@Bean("asyncPostExecutor")
public Executor asyncPostExecutor(){
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePololSize(4);
executor.setMaxPoolSize(8);
executor.setQueueCapacity(50);
executor.setKeepAllveSeconds(60);
executor.setRejectedExecutionHanlder(new ThreadPoolExecutor.CallerRunsPolicy());
executor.setThreadNamePrefix("asyncPostExecutor--thread-pool-");
return executor;
}
/**用户自定义线程池,异步的多线程之间可以共享某些信息,如请求头信息的登陆用户信息等*/
@Bean("asyncQueryExecutor")
public Executor asyncQueryExecutor(){
ExecutorService executor = Executors.newFixedThreadPool(8);
return TtlExecutors.getTtlExecutorService(executor);
}
}
// 异步触发线程执行某任务
@Service
public class ProductService {
@Autowired
private Executor asyncPostExecutor;
public String saveProduct(Product product) {
// ...other code...
// 异步触发线程执行某任务
CompletableFuture.runAsync((param1, param2)->{
//...user biz logic...
}, asyncPostExecutor);
// ...other code...
}
}