由于项目的jdk版本小于1.8 所以用的ThreadPoolExecutor
需求:
要求用多线程的形式去处理当前接口的插入数据并且调用绿盾方的api实行聊天内容监控
controller.class(接口)
/**
* 绿盾
* @param param
* @return
*/
@RequestMapping("/chatMonitorForLD")
public @ResponseBody Object getChatMonitor(@RequestBody Map<String,Object> param) {
//方法1
new Thread(new ChatMonintorRequestHandler(param)).start();
//方法2
ChatMonintorRequestHandler runnable=new ChatMonintorRequestHandler(param);
TreadPoolUtil.getInstance().execute(runnable);
//返回内容
Map<String, Object> res = new HashMap<String, Object>();
res.put("code", 200);
res.put("message", "调用成功");
res.put("result", null);
return JSONObject.toJSON(res);
}
ChatMonintorRequestHandler.class(处理业务逻辑)
/**
* 处理业务逻辑
**/
public class ChatMonintorRequestHandler implements Runnable {
private static final Log logger = LogFactory.getLog(ChatMonintorRequestHandler.class);
private Map<String,Object> param;
public ChatMonintorRequestHandler(Map<String,Object> param){
//参数赋值
this.param = param;
}
@Override
public void run() {
try {
ChatLogGMCommandService ccService = ContextHolder.getInstance().getSpringBean("ChatLogGMCommandService");
ccService.getChatMonitor(param);
} catch (DataAccessException e) {
logger.info("当前线程异常:"+Thread.currentThread().getName());
e.printStackTrace();
}
}
}
实现方法 (1)
一开始想到的实现方法是SDK调用接口时候,新增一个Thread去执行,由于游戏中聊天内容还是很多,并发还是挺大,线程数量容易过大,给服务器造成压力。
实现方法 (2)
打算采用线程池的方式去处理。因为接口会被频繁调用,所以需要用单例模式去创建一个线程池
单例模式的线程池类
public class TreadPoolUtil {
private TreadPoolUtil() {
};
private static final int DEFAULT_CORE_SIZE=100;
private static final int MAX_QUEUE_SIZE=500;
private volatile static ThreadPoolExecutorUtil executor;
// 获取单例的线程池对象
public static ThreadPoolExecutorUtil getInstance() {
if (executor == null) {
executor = new ThreadPoolExecutorUtil(DEFAULT_CORE_SIZE,// 核心线程数
MAX_QUEUE_SIZE, // 最大线程数
Integer.MAX_VALUE, // 闲置线程存活时间
TimeUnit.MILLISECONDS,// 时间单位
new LinkedBlockingDeque<Runnable>(Integer.MAX_VALUE)// 线程队列
);
}
return executor;
}
public void execute(Runnable runnable) {
if (runnable == null) {
return;
}
executor.execute(runnable);
}
// 从线程队列中移除对象
public void cancel(Runnable runnable) {
if (executor != null) {
executor.getQueue().remove(runnable);
}
}
}
因为要统计单个线程的处理时间 所以要新建个类去继承ThreadPoolExecutor,重写他的beforeExecute和afterExecute方法
public class ThreadPoolExecutorUtil extends ThreadPoolExecutor {
private static final Log logger = LogFactory.getLog(ThreadPoolExecutorUtil.class);
public ThreadPoolExecutorUtil(int corePoolSize, int maximumPoolSize,
long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) {
super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue);
// TODO Auto-generated constructor stub
}
public void beforeExecute(Thread t, Runnable r){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
logger.info("线程"+t.getName()+"开始时间:"+sdf.format(new Date())+"线程池中线程数目:"+TreadPoolUtil.getInstance().getPoolSize()+",队列中等待执行的任务数目:"+
TreadPoolUtil.getInstance().getQueue().size()+",已执行玩别的任务数目:"+TreadPoolUtil.getInstance().getCompletedTaskCount());
}
public void afterExecute(Thread t, Runnable r){
logger.info("线程"+t.getName()+"结束时间:"+new Date());
}
}
数据库处理
因为用的是Durid的,设置了最大的连接数量为200
第一次实现采用了JdbcTemplate.update(sql),基本的jdbcTemplete没有主动释放连接,所以在插入200条数据后后面的线程就无法获取到数据库连接 从而报错
public class ChatLogGMCommandService{
final String upSql = "insert into gms_chat(chatStr,pid,playerName,chatType,privateName,createTime,serverIp,serverPort,platformId)"
+" values('"+content+"','"+uid+"','"+nickName+"','"+msgType+"','"+toUid+"','"+sdf.format(new Date())+"','"+serverIp+"','"+serverPort+"',"+platformId+")";
KeyHolder keyHolder = new GeneratedKeyHolder();
//获取插入sql的id
getJdbcTemplate().update(
new PreparedStatementCreator() {
@Override
public java.sql.PreparedStatement createPreparedStatement(
java.sql.Connection con) throws SQLException {
PreparedStatement ps = (PreparedStatement) getJdbcTemplate().getDataSource()
.getConnection().prepareStatement(upSql,Statement.RETURN_GENERATED_KEYS);
return ps;
}
}, keyHolder);
}
正确
public class ChatLogGMCommandService{
//主动关闭数据库连接,这样就不会造成数据库连接一直不被释放,无法插入下面的语句
final String upSql = "insert into gms_chat(chatStr,pid,playerName,chatType,privateName,createTime,serverIp,serverPort,platformId)"
+" values('"+content+"','"+uid+"','"+nickName+"','"+msgType+"','"+toUid+"','"+sdf.format(new Date())+"','"+serverIp+"','"+serverPort+"',"+platformId+")";
int id= 0;
PreparedStatement prepareStatement=null;
DruidPooledConnection connection=null;
ResultSet rs = null;
try {
connection = (DruidPooledConnection) getJdbcTemplate().getDataSource().getConnection();
prepareStatement= connection.prepareStatement(upSql,Statement.RETURN_GENERATED_KEYS);
prepareStatement.executeUpdate();
rs = prepareStatement.getGeneratedKeys();
if (rs.next())
id = rs.getInt(1);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (prepareStatement != null) {
try {
prepareStatement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}