服务器每次宕机都和日志记录有关系,这里的日志记录,是指手机端需要把一些错误日志上传到服务器,而每次发生稍微量大点的上传,就会出现宕机。
我在过滤器增加了每个请求的时间统计(http://www.javacui.com/service/56.html),发现很多请求都要好几分钟才能处理完,除了上传占用宽带以外,我开始怀疑HTTP请求是否适合与当前业务场景。
于是我开始考虑直接使用UDP进行文件上传(http://www.javacui.com/java/207.html),关于UDP的一些其他内容可以参考我的博客。
大家知道,使用UDP就是为了应和信号不稳定的场合,之前在做铁路方面系统时,列车上的数据是需要实时下地入库的,可是高速列车行驶中信号是不稳定的,需要就要采用UDP方式发送,且要实时重复发送直到成功。不成功的记录还要记录到本地数据库,有信号时要及时再次发送出去。
虽然现在已经开始普及4G网络,但是不要忽略还有一些低端手机,山寨手机,信号不稳定区段等特殊情况存在,如果此时仍然使用HTTP连接方式,那必然会出现连接突然中断,或长久占用连接的情况。
之前记录日志的方式代码如下:/**
* 记录日志
*/
@RequestMapping(value="/markLog")
@ResponseBody
public ResponseEntity markLog(
@RequestParam(value="orderId")String orderId,
@RequestParam(value="extensionName")String extensionName,
HttpServletRequest req) throws Exception{
//1.记录日志
if(!StringUtil.isNull(orderId) && !StringUtil.isNull(extensionName)){
StringUtil.saveFile(extensionName, orderId, req);
}
return new ResponseEntity(ConstantValueUtil.RETURN_VALUE_OK,HttpStatus.OK);
}
流程处理方法如下:/**
* 将输入流的内容保存在指定路径中
*/
public static int saveFile(String extensionName, String orderId, HttpServletRequest req) {
OutputStream bos = null;
String path = null;
InputStream stream = null;
try {
stream = req.getInputStream();
String pathname = getLogFileWritePath(extensionName, orderId, req);
pathname = pathname.replaceAll("\\\\", "/");
path = pathname.substring(0, pathname.lastIndexOf("/"));
java.io.File dir = new java.io.File(path);
if (!dir.isDirectory())
dir.mkdirs();// 创建不存在的目录
File file = new File(pathname);
if (!file.exists()) {
file.createNewFile();
}
// writeln the file to the file specified
bos = new FileOutputStream(pathname);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
bos.write(buffer, 0, bytesRead);
}
} catch (FileNotFoundException e) {
return -1;
} catch (IOException e) {
return -2;
} catch (Exception e) {
return -3;
} finally {
try {
if(null != bos) bos.flush();
if(null != bos) bos.close();
if(null != stream) stream.close();
} catch (IOException e) {
logger.error("", e);
}
}
return 0;
}
注意以上代码不是我写的,是我拿来给大家参考的。
可以看到,日志文件内容是从InputStream里面读取的,如此以来,一旦发生信号不稳定的情况,这个方法就有很大的风险了。
关于UDP的其他内容
更多内容,网上也有很多示例,欢迎大家提出宝贵意见和建议。