2015-10-26 180 views
-1

我想實現簡單的聊天,但只在服務器工作期間存儲它們。我不想將它們存儲在數據庫中,就像在List或Map中一樣。如何?不在數據庫中存儲數據

+0

你可以採取一個文件和讀/從那裏寫。 – Jan

回答

2

該解決方案適用於「簡單」聊天。

關於如何構建這個之前沒有太多的信息,所以我只是解釋一下如何擁有一個可以注入其他bean來處理存儲聊天的Application範圍bean。

您可以配置服務來存儲此信息。

ChatHistoryService.java

@Service 
@Scope("application")//This is the key this will keep the chatHistory alive for the length of the running application(As long as you don't have multiple instances deployed(But as you said it's simple so it shouldn't) 
public class ChatHistoryService { 

    List<String> chatHistory = new LinkedList<>();//Use LinkedList to maintain order of input 

    public void storeChatHistory(String chatString) { 
     chatHistory.add(chatString); 
    } 

    public List<String> getChatHistory() { 
     //I would highly suggest creating a defensive copy of the chat here so it can't be modified. 
     return Collections.unmodifiableList(chatHistory); 
    } 

} 

YourChatController.java

@Controller 
public class YourChatController { 

    @Autowired 
    ChatHistoryService historyService; 

    ...I'm assuming you already have chat logic but you aren't storing the chat here is where that would go 

    ...When chat comes in call historyService.storeChatHistory(chatMessage); 

    ...When you want your chat call historyService.getChatHistory(); 

} 

一旦考慮再次繼續,這確實只適用於簡單的應用。如果它被分發了,那麼每個應用程序的實例會有不同的聊天記錄,您可以查看分佈式緩存。

無論如何不要超出簡單的這個實現。

如果你看看這裏,它會給你一個彈簧引導工作的幾個緩存的想法。

​​