背景:前段时间工作需要开发一个socket服务端,在接受到客户端发过来的报文信息后解析报文调用数据库程序完成数据文件的生成再拼凑结果报文反馈给客户端。由于客户数比较多,所以用线程池和数据库连接池。
一.线程池
ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors()*POOL_SIZE);
1.接到一个连接启用一个线程执行任务
executorService.execute(new Handler(socket));//注:Handler实现了Runnable接口
2.Handler类中run方法实现业务逻辑
InputStream socketIn=socket.getInputStream();
byte[] buf=new byte[1024];
int len = 0;
while((len=socketIn.read(buf))>0) {
//1.接收报文字符串进行解析
//2.调用数据库存储过程生成数据文件获得文件名和成功标识
//3.将组装的报文进行返回
}
二.数据库连接池(c3p0)
//默认的读取c3p0-config.xml中默认配置,也可在程序中配置如(ds.setInitialPoolSize(),ds.setMinPoolSize,ds.setMaxPoolSize等);
<span style="font-size:14px;">ComboPooledDataSource ds =new ComboPooledDataSource();
Connection conn = ds.getConnection();
//拿到连接后,后面的就和jdbc的操作一样啦
Connection conn = CpDB.getConn();
CallableStatement cstmt = null;
String sql = "{ call PKG_DC_QUERY.pro_dc_query(?,?,?,?,?,?,?,?,?) }";
Date begDate = DateUtil.getSqlDate(param.get("begndt"));
Date endDate = DateUtil.getSqlDate(param.get("termdt"));
ResultSet rs = null;
StringBuffer sb = new StringBuffer("");
try {
cstmt = CpDB.callStmt(conn, sql);
cstmt.setDate(1, begDate);
cstmt.setDate(2, endDate);
cstmt.setString(3, param.get("acctno"));
cstmt.registerOutParameter(4, Types.VARCHAR);
cstmt.registerOutParameter(5, Types.VARCHAR);
cstmt.registerOutParameter(6, Types.VARCHAR);
cstmt.registerOutParameter(7, oracle.jdbc.OracleTypes.INTEGER);
cstmt.registerOutParameter(8, oracle.jdbc.OracleTypes.VARCHAR);
cstmt.registerOutParameter(9, oracle.jdbc.OracleTypes.CURSOR);
cstmt.execute();
for(int i=0;i<proStr.length-1; i++) {
proStr[i] = cstmt.getString(4+i);
System.out.println(proStr[i]);
}
//这个返回的是个cursor
rs = (ResultSet) cstmt.getObject(9);
while(rs.next()) {
while(rs.next()) {
String record = rs.getString(1);
sb.append(record).append(",");
}
String records = sb.toString();
records = records.substring(0,records.length()-6);
proStr[5] = records;
finally {
<span style="white-space:pre"> </span>CpDB.close(rs);
<span style="white-space:pre"> </span>CpDB.close(cstmt);
<span style="white-space:pre"> </span>CpDB.close(conn);
}
</span>
三.日志管理(log4j)
1.配置文件配置
### set log levels ###
log4j.rootLogger = INFO,D
### 输出到日志文件 ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss} [ %t:%r ] - [ %p ] %m%n
2.在程序中用
logger.info(e.getMessage(),e);//记录异常信息