Spring 不在数据库中存储数据

Spring 不在数据库中存储数据,spring,spring-mvc,spring-boot,spring-data,Spring,Spring Mvc,Spring Boot,Spring Data,我想实现简单的聊天,但只在服务器工作期间存储它们。我不想将它们存储在数据库中,就像在列表或地图中一样。如何?如您所述,此解决方案适用于“简单”聊天 关于您以前是如何构建的,没有太多的信息,所以我只想解释如何拥有一个应用程序范围的bean,它可以注入到其他bean中来处理存储聊天 您可以配置服务来存储此信息 ChatHistoryService.java @Service @Scope("application")//This is the key this will keep the chatH

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

如您所述,此解决方案适用于“简单”聊天

关于您以前是如何构建的,没有太多的信息,所以我只想解释如何拥有一个应用程序范围的bean,它可以注入到其他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);
    }

}
再次请记住,这实际上只适用于简单的应用程序。如果它是分布式的,那么每个应用程序实例都会有不同的聊天历史记录,此时您可以查看分布式缓存

在任何情况下,都不要超越这个实现的简单性

如果你看这里,它会给你一个与SpringBoot一起工作的几个缓存的概念


您可以从那里获取一个文件并读取/写入它。
@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();

}