java定時任務使用方法之實現環信聊天記錄同步並定時刪除

來源:互聯網
上載者:User


定時任務代碼:

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了,最後實現的結果如下

 

上傳到七牛的檔案:語音、視頻、圖片

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.