package processing; import javax.servlet.ServletContext; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.Set; public class ChatCacheController { /** * 通过chat_key获得后台保存的历史信息点 * chatCache:存储了chatKye相对应的对话记录(历史信息点) * @return 历史信息点,引擎在上一轮(多轮)识别的关键字 */ public static synchronized Map getChatCache(String chatKey, ServletContext context){ Map historyInfoPoint = null; Map> chatCache = null; if(context.getAttribute("chatCache") == null) { chatCache = new HashMap>(); context.setAttribute("chatCache", chatCache); } else{ chatCache = (Map>) context.getAttribute("chatCache"); } String chatkey; try{ historyInfoPoint = chatCache.get(chatKey); //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); }catch(Exception e){ //可整合 historyInfoPoint = null; } return historyInfoPoint; } /** * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 */ public static synchronized void updateChatCache4Delete(ServletContext context){ String chatKey; long lastChatTime,now; Map history = new HashMap(); Map> chatCache = (Map>) context.getAttribute("chatCache"); Iterator it = chatCache.keySet().iterator(); while (it.hasNext()) { chatKey = it.next(); history = chatCache.get(chatKey); lastChatTime = Long.valueOf(history.get("lastUpdateTime")); now = System.currentTimeMillis(); if (now - lastChatTime > 300000) { it.remove(); } } context.setAttribute("chatCache", chatCache); } /** * 根据chatKey更新chatCache的数据,并修改最后更新时间 */ public static synchronized void updateChatCache4Insert(Map curInfoPoint,Map historyInfoPoint,ServletContext context){ historyInfoPoint.put("lastUpdateTime",String.valueOf(System.currentTimeMillis())); Map> keyCache = (Map>) context.getAttribute("chatCache"); keyCache.put(curInfoPoint.get("chat_key")[0],historyInfoPoint); context.setAttribute("chatCache",keyCache); } }