不在数据库中存储数据

问题描述:

我想实现简单的聊天,但只在服务器工作期间存储它们。我不想将它们存储在数据库中,就像在List或Map中一样。如何?不在数据库中存储数据

+0

你可以采取一个文件和读/从那里写。 – Jan

该解决方案适用于“简单”聊天。

关于如何构建这个之前没有太多的信息,所以我只是解释一下如何拥有一个可以注入其他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(); 

} 

一旦考虑再次继续,这确实只适用于简单的应用。如果它被分发了,那么每个应用程序的实例会有不同的聊天记录,您可以查看分布式缓存。

无论如何不要超出简单的这个实现。

如果你看看这里,它会给你一个弹簧引导工作的几个缓存的想法。

​​