我想实现简单的聊天,但只在服务器工作期间存储它们。我不想将它们存储在数据库中,就像在List或Map中一样。怎么样?
答案 0 :(得分:2)
此解决方案适用于"简单"你解释说,聊天。
关于你之前是如何构建它的信息并不多,所以我将解释如何使用一个可以注入其他bean的Application scoped 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 storeChatMessage(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.storeChatMessage(chatMessage);
...When you want your chat call historyService.getChatHistory();
}
再次请记住,这只适用于简单的应用程序。如果它已分发,那么每个应用程序实例将有不同的聊天历史记录,您可以查看分布式缓存。
在任何情况下都不要超越简单的实现。
如果你看一下它会让你知道几个与spring boot一起使用的缓存。