1.实例化线程池,数据入队,定时任务提交出队,执行run。异步保存日志
1.首先是service层
@Service
public class SysLogServiceImpl implements SysLogService {
@Resource
private LogThreadPool logThreadPool;
@Resource
private SysLogMapper sysLogMapper;
@Override
public <<span style="color:#20999d;">PK> SysLog getById(PK id) throws ServiceException {
return null;
}
@Override
public int save(SysLog entity) throws ServiceException {
try {
logThreadPool.pushLog(entity);
} catch (Exception e) {
e.printStackTrace();
}
//sysLogMapper.insert(entity);
return 0;
}
}
2.线程池
@Component
public class LogThreadPool {
private ThreadPoolExecutor poolExecutor;
BlockingQueue blockingQueue = null;
public ThreadPoolExecutor getPoolExecutor(){
return this.poolExecutor;
}
//初始化线程池
@PostConstruct
public void initPool(){
blockingQueue = new LinkedBlockingQueue<>(5);
poolExecutor = new ThreadPoolExecutor(10,15,100, TimeUnit.MILLISECONDS,blockingQueue);
}
//大小
public int getPoolSize(){
return poolExecutor.getPoolSize();
}
//入队
public void pushLog(SysLog entity) throws Exception {
//将日志信息保存到队列中去,使用put(会造成阻塞)
blockingQueue.put(new LogThread(entity));
}
//出队
public Runnable poll(){
//从队列中取出任务,使用poll(会造成阻塞)
Runnable poll = (Runnable) blockingQueue.poll();
return poll;
}
}
3.提交任务才会保存
@Component
public class ThreadPoolSubmit {
@Resource
private LogThreadPool logThreadPool;
@Scheduled(cron = "0 0/1 * * * ?")
public void logOper(){
ThreadPoolExecutor poolExecutor = logThreadPool.getPoolExecutor();
Runnable runnable = logThreadPool.poll();
System.out.println(poolExecutor.hashCode());
if(null != runnable){
poolExecutor.submit(runnable);
}
}
}
4.提交后执行这个保存日志
@Component
public class LogThread implements Runnable{
private SysLog entity;
public LogThread() {
}
public LogThread(SysLog entity) {
this.entity = entity;
}
public SysLog getEntity() {
return entity;
}
public void setEntity(SysLog entity) {
this.entity = entity;
}
@Override
public void run() {
//TODO 应该做个判断否则会出现内存溢出的情况
SysLogMapper sysLogMapper = SpringContextUtil.getBean(SysLogMapper.class);
sysLogMapper.insert(entity);
}
}
加载中,请稍候......