加载中…
个人资料
  • 博客等级:
  • 博客积分:
  • 博客访问:
  • 关注人气:
  • 获赠金笔:0支
  • 赠出金笔:0支
  • 荣誉徽章:
正文 字体大小:

java多线程异步保存日志

(2019-10-23 19:27:43)
标签:

it

教育

文化

分类: javaEE

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);
}
}

0

阅读 收藏 喜欢 打印举报/Report
  

新浪BLOG意见反馈留言板 欢迎批评指正

新浪简介 | About Sina | 广告服务 | 联系我们 | 招聘信息 | 网站律师 | SINA English | 产品答疑

新浪公司 版权所有