定时任务代码:
public class ChatHistoryTimerListener implements ServletContextListener {
String chatUrl="http://a1.easemob.com/***/********/chatmessages";
private ChatHistoryService chService;
private Timer timer=null;
private static final long PERIOD_DAY = 24 * 60 * 60 * 1000;
//private static final long PERIOD_DAY = 1000;
@Override
public void contextDestroyed(ServletContextEvent arg0) {
}
@Override
public void contextInitialized(ServletContextEvent event) {
timer=new Timer();
WebApplicationContext applicationContext = WebApplicationContextUtils.getWebApplicationContext(event.getServletContext());
this.chService=(ChatHistoryService)applicationContext.getBean("chService");
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 1); //凌晨1点
calendar.set(Calendar.MINUTE,0);
calendar.set(Calendar.SECOND, 0);
Date date=calendar.getTime();
event.getServletContext().log("环信----------------定时器已启动。") ;
TimerTask task=new TimerTask() {
@Override
public void run() {
String tokenUrl="http://a1.easemob.com/***/*****/token";
Map<String,String>paramMap=new HashMap<String,String>();
paramMap.put("grant_type", "client_credentials");
paramMap.put("client_id", Config.hxclient_id);
paramMap.put("client_secret", Config.hxclient_secret);
Map<String, Object>tokenMap=JsonTools.jsonStrToMap(HttpTools.post(tokenUrl,paramMap));
System.out.println(calendar.get(Calendar.MINUTE));
List<Map<String,String>>headerList=new ArrayList<Map<String,String>>();
Map<String,String>header=new HashMap<String, String>();
Map<String,String>header2=new HashMap<String, String>();
header.put("headerName", "Authorization");
header.put("headerValue", "Bearer "+tokenMap.get("access_token").toString());
header2.put("headerName", "Content-Type");
header2.put("headerValue", "application/json");
headerList.add(header);
boolean isrun=true;
String pagram="";
//在此处要判断上次同步完成后的最后一条消息的时间,按照时间同步后面的数据
//ql=select * where timestamp<1403164734226 and timestamp>1403166586000
Timestamp time=chService.getNewTimeSynchronous();
if(ChkTools.isNotNull(time)){
chatUrl=chatUrl+"?ql=select+*+where+timestamp>"+time.getTime()+"&limit=100";
}else{
chatUrl=chatUrl+"?limit=100";
}
while (isrun) {
String json=HttpTools.getSetHeader(chatUrl+pagram, headerList);
if(ChkTools.isNull(json)){
isrun=false;
break;
}
JSONObject o=JSON.parseObject(json);
if(ChkTools.isNotNull(o.get("cursor"))){
pagram="&cursor="+o.get("cursor").toString();
}else{
isrun=false;
}
chService.SynchronousChat(o,event.getServletContext().getRealPath("/"));
//此处开始执行,业务数据在下面代码稍作分享
try {
Thread.sleep(10000);
System.out.println("等待一千毫秒后执行下一次循环");
} catch (InterruptedException e) {
e.printStackTrace();
}
//删除本地服务器的缓存文件,文件已经保存到七牛
File file=new File(event.getServletContext().getRealPath("/")+"downtem");
deleteFile(file);
}
//定时删除三天前的聊天记录
chService.deleteTimeAgoHistory();
}
};
timer.schedule(task, date,PERIOD_DAY) ;
event.getServletContext().log("聊天记录--------已经添加任务调度表。" ) ;
}
//使用的spring实现实例化
public ChatHistoryService getChService() {
return chService;
}
public void setChService(ChatHistoryService chService) {
this.chService = chService;
}
private void deleteFile(File file){
if(file.isDirectory()){
File[] files = file.listFiles();
for(int i=0; i<files.length; i++){
deleteFile(files[i]);
}
}
file.delete();
}
}
业务代码
public void SynchronousChat(JSONObject o, String filepath) {
JSONArray e = (JSONArray) o.get("entities");
if (e.size() > 0) {
List<B_Chat_History> list = new ArrayList<B_Chat_History>();
for (int i = 0; i < e.size(); i++) {
B_Chat_History bcHistory = new B_Chat_History();
JSONObject s = e.getJSONObject(i);
String from = s.getString("from");
String to = s.getString("to");
Long timestamp = Long.parseLong(s.getString("timestamp"));
JSONObject p = (JSONObject) s.get("payload");
JSONArray bodies = (JSONArray) p.get("bodies");
JSONObject b = bodies.getJSONObject(0);
// "msg": "哈哈哈","type":
// "txt""type": "video",
// 开始赋值
bcHistory.setFrom_phone(from);
bcHistory.setTo_phone(to);
bcHistory.setFrom_user(getuserName(from));
bcHistory.setTo_user(getuserName(to));
bcHistory.setTimestamp(new java.sql.Timestamp(timestamp));
switch (b.getString("type")) {
case "txt":
bcHistory.setMsg(b.getString("msg").replace("\n", ""));
bcHistory.setType("txt");
bcHistory.setLength(0);
break;
case "video":
bcHistory.setType("video");
String videokey = "video_" + new Date().getTime() + ".mp4";
try {
String file = HttpDownUtil.downloadNet(filepath,
b.getString("url"), "mp4");
try {
QiNiuUplodUtil.upload(file, videokey);
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
bcHistory.setUrl(Constant.QINIU_URL_WEB + videokey);
String thumbkey = "video_" + new Date().getTime() + ".png";
try {
String file = HttpDownUtil.downloadNet(filepath,
b.getString("thumb"), "png");
try {
QiNiuUplodUtil.upload(file, thumbkey);
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
bcHistory.setThumb(Constant.QINIU_URL_WEB + thumbkey);
bcHistory.setLength(0);
break;
case "img":
bcHistory.setType("img");
String imgkey = "img_" + new Date().getTime() + ".png";
try {
String file = HttpDownUtil.downloadNet(filepath,
b.getString("url"), "png");
try {
QiNiuUplodUtil.upload(file, imgkey);
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
bcHistory.setUrl(Constant.QINIU_URL_WEB + imgkey);
bcHistory.setLength(0);
break;
case "audio":
bcHistory.setType("audio");
String audiokey = "audio_" + new Date().getTime() + ".amr";
try {
String file = HttpDownUtil.downloadNet(filepath,
b.getString("url"), "amr");
try {
QiNiuUplodUtil.upload(file, audiokey);
} catch (IOException e1) {
e1.printStackTrace();
}
} catch (MalformedURLException e1) {
e1.printStackTrace();
}
//"length":10,语音时常秒
bcHistory.setLength(Integer.parseInt(b.getString("length")));
bcHistory.setUrl(Constant.QINIU_URL_WEB + audiokey);
break;
}
list.add(bcHistory);
}
/**
* 此处使用Springjdbc执行批量保存
*/
try {
jt.batchUpdate(
"insert into b_chat_history (id,from_phone,from_user,to_phone,to_user,type,msg,url,thumb,length,timestamp) value (?,?,?,?,?,?,?,?,?,?,?)",
new BatchPreparedStatementSetter() {
public void setValues(PreparedStatement ps, int i)
throws SQLException {
ps.setString(1, UUID.randomUUID().toString());// ID的值
ps.setString(2, list.get(i).getFrom_phone());
ps.setString(3, list.get(i).getFrom_user());
ps.setString(4, list.get(i).getTo_phone());
ps.setString(5, list.get(i).getTo_user());
ps.setString(6, list.get(i).getType());
ps.setString(7, list.get(i).getMsg());
ps.setString(8, list.get(i).getUrl());
ps.setString(9, list.get(i).getThumb());
ps.setInt(10,list.get(i).getLength());
ps.setTimestamp(11, list.get(i).getTimestamp());
}
public int getBatchSize() {
return list.size();
}
});
} catch (Exception e2) {
System.out.println("可能有数据异常,同步部分数据异常");
e2.printStackTrace();
}
}
}
OK了,最后实现的结果如下
上传到七牛的文件:语音、视频、图片