package com.qiwu.chatbotbackend.processing; import com.alibaba.fastjson.JSON; import com.qiwu.chatbotbackend.GameEnvironment.GameEnv; import com.qiwu.chatbotbackend.GameEnvironment.ObjectFileUtil; import com.qiwu.chatbotbackend.db.SqlHelper; import com.qiwu.chatbotbackend.entity.ArchiveInfo; import com.qiwu.chatbotbackend.entity.ChatCache; import com.qiwu.chatbotbackend.entity.UserInfo; import javax.servlet.ServletContext; import java.io.*; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class ChatCacheController2 { public static long TIME_OUT = 300000; private static String CHAT_CACHE_DIR = "ChatCache/"; private static String ARCHIVE_NAME = "%s-%s-%s"; private static String ENV_PATH = CHAT_CACHE_DIR + "%s-%s-%s-env.data"; private static String INFO_PATH = CHAT_CACHE_DIR + "%s-%s-%s-info.data"; private static String ENV_POSTFIX = "-env.data"; private static String INFO_POSTFIX = "-info.data"; public static String COMBINE_PUNC1 = "@@@"; public static String COMBINE_PUNC2 = "@@@@"; /** * 通过chat_key获得后台保存的历史信息点 * chatCache:存储了chatKye相对应的对话记录(历史信息点) * * @return 历史信息点,对话过程中引擎提取的用户信息 */ public static synchronized ChatCache getChatCache(String userKey, String randKey, ServletContext context, UserInfo userinfo, Map receiveParamters, Boolean loadCacheStatus) throws Exception { Map chatCacheMap = null; ChatCache chatCache = null; if (context.getAttribute("chatCache") == null) { chatCacheMap = new HashMap(); //chatCacheMap.put(chatKey, new ChatCache(userinfo)); context.setAttribute("chatCache", chatCacheMap); } else { chatCacheMap = (Map) context.getAttribute("chatCache"); } try { chatCache = chatCacheMap.get(userKey); //如果用户之前没有玩过或者有一段时间没有玩 if(chatCache == null){ chatCache = new ChatCache(userinfo, userKey, randKey); chatCacheMap.put(userKey, chatCache); //用户几分钟前还在玩 } else { if( !chatCache.getRandKey().equals(randKey)) { //同一个用户的不同一次会话, 保存上一次会话 saveChatCache(chatCache, null); chatCache = new ChatCache(userinfo, userKey, randKey); chatCacheMap.put(userKey, chatCache); } } //historyInfoPoint = (Map) context.getAttribute("chat_key+"+userinfo.userName); } catch (Exception e) { //可整合 e.printStackTrace(); chatCache = new ChatCache(userinfo, userKey, randKey); chatCacheMap.put(userKey, chatCache); } return chatCache; } public static synchronized boolean saveChatCache(ChatCache chatCache, SqlHelper helper) throws IOException { LocalDateTime now = LocalDateTime.now(); DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-dd hh:mm:ss"); String nowTime = now .format(format); Boolean opFlag; String userKey = chatCache.getUserKey(); String site = chatCache.getInfoPoint().get("site"); String archiveName = String.format(ARCHIVE_NAME, userKey, site, nowTime); try { if(helper == null){ helper = new SqlHelper(); } File dir = new File(CHAT_CACHE_DIR); if (!dir.exists()) dir.mkdir(); ObjectFileUtil.writeObjectToFile(chatCache.getGameEnv(), String.format(ENV_PATH, userKey, site, nowTime)); File file = new File(String.format(INFO_PATH, userKey, site, nowTime)); FileWriter fw = new FileWriter(file); String jsonString = JSON.toJSONString(chatCache.getInfoPoint()); fw.write(jsonString); fw.close(); opFlag = helper.insertArchiveInfo(archiveName, userKey, site); } catch (Exception e) { System.out.println("游戏存档时发生异常"); e.printStackTrace(); opFlag = false; } return opFlag; } public static synchronized ChatCache loadChatCache(ArchiveInfo archiveInfo) throws Exception { ChatCache chatCache = null; GameEnv gameEnv = null; Map infoPoint = null; String keys[] = archiveInfo.getArchiveId().split(COMBINE_PUNC1); keys[1] = keys[1].split("-")[0]; String fileDir = System.getProperty("user.dir") + "/ChatCache"; String line, pair[]; Map infoPoints = new HashMap(); try { File file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); if (file.exists()){ gameEnv = (GameEnv) ObjectFileUtil.readObjectFromFile(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + ENV_POSTFIX); }else{ throw new IOException("环境存档不存在"); } file = new File(CHAT_CACHE_DIR + archiveInfo.getArchiveId() + INFO_POSTFIX); FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr); String jsonStr = br.readLine(); infoPoint = (Map)JSON.parseObject(jsonStr); chatCache = new ChatCache(keys[0], keys[1], gameEnv, infoPoint); chatCache.setReloading(true); br.close(); fr.close(); } catch (IOException e) { System.out.println(e.toString()); } return chatCache; } /** * chatChche中每个chatkey都有对应的最后更新时间,如果最后更新时间已经是x分钟前(超时),就清除该chatKey的数据 */ public static synchronized void updateChatCache4Delete(String userKey, ServletContext context, UserInfo userInfo) throws IOException { String sessionKey; ChatCache chatCache = null; SqlHelper helper = null; long lastChatTime, now; Map history = new HashMap(); Map chatCacheMap = (Map) context.getAttribute("chatCache"); try { Iterator it = chatCacheMap.keySet().iterator(); while (it.hasNext()) { sessionKey = it.next(); if (sessionKey.equals(userKey)) { saveChatCache(chatCacheMap.get(sessionKey),null); continue; } history = chatCacheMap.get(sessionKey).getInfoPoint(); lastChatTime = Long.valueOf(history.get("lastUpdateTime")); now = System.currentTimeMillis(); if (now - lastChatTime > ChatCacheController2.TIME_OUT) { chatCache = chatCacheMap.get(sessionKey); if(chatCache != null && !chatCache.getRandKey().equals(chatCache.getUserKey()) && chatCache.isReloading()) { saveChatCache(chatCache, null); } System.out.println("移除" + sessionKey); it.remove(); } } }catch (Exception e){ e.printStackTrace(); } context.setAttribute("chatCache", chatCacheMap); } /** * 根据chatKey更新chatCache的数据,并修改最后更新时间 */ public static synchronized void updateChatCache4Insert(Map curInfoPoint, Map historyInfoPoint, GameEnv gameEnv, ServletContext context, UserInfo userInfo) { historyInfoPoint.put("lastUpdateTime", String.valueOf(System.currentTimeMillis())); Map keyCacheMap = (Map) context.getAttribute("chatCache"); ChatCache chatCache = keyCacheMap.get(curInfoPoint.get("userKey")); chatCache.setInfoPoint(historyInfoPoint); chatCache.setGameEnv(gameEnv); context.setAttribute("chatCache", keyCacheMap); } public static synchronized boolean findChatCache(String userKey, ServletContext context, String botAccount) throws Exception { ChatCache chatCache = null; GameEnv gameEnv = null; ArchiveInfo archiveInfo = null; Map infoPoint = null; String fileDir = System.getProperty("user.dir") + "/ChatCache"; String line, pair[]; SqlHelper helper; Map infoPoints = new HashMap(); try { helper = new SqlHelper(); archiveInfo = helper.queryUserLastGameArchive(userKey); } catch(Exception e){ e.printStackTrace(); return false; } return archiveInfo != null; } public static synchronized boolean deleteUnuseChatCache(String chatKey, ServletContext context) throws Exception { try { System.out.println("移除----------------------------"); HashMap chatCacheHashMap = (HashMap)context.getAttribute("chatCache"); chatCacheHashMap.remove(chatKey); } catch(Exception e){ e.printStackTrace(); return false; } return true; } }