springboot实现连续对话,并将对话内容保存到mysql中
时间: 2024-03-20 19:43:23 浏览: 51
springboot集成mysql
可以使用SpringBoot中的WebSocket实现连续对话,并使用Spring Data JPA将对话内容保存到MySQL数据库中。
首先,需要在SpringBoot中添加WebSocket的依赖:
```
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-websocket</artifactId>
</dependency>
```
然后,在SpringBoot中创建一个WebSocket配置类,配置WebSocket的相关参数和处理器:
```java
@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {
@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
registry.addHandler(chatHandler(), "/chat").setAllowedOrigins("*");
}
@Bean
public WebSocketHandler chatHandler() {
return new ChatHandler();
}
}
```
创建一个WebSocket处理器ChatHandler,用于处理WebSocket连接和消息:
```java
public class ChatHandler extends TextWebSocketHandler {
@Autowired
private ChatService chatService;
@Override
public void afterConnectionEstablished(WebSocketSession session) throws Exception {
// 新建一个对话
Chat chat = new Chat();
chat.setStartTime(new Date());
chatService.saveChat(chat);
session.getAttributes().put("chatId", chat.getId());
}
@Override
public void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
// 获取当前对话
Long chatId = (Long) session.getAttributes().get("chatId");
Chat chat = chatService.getChatById(chatId);
// 处理消息
String content = message.getPayload();
chat.addMessage(content);
chatService.saveChat(chat);
// 发送消息给所有连接的客户端
for (WebSocketSession client : chat.getClients()) {
if (client.isOpen()) {
client.sendMessage(message);
}
}
}
@Override
public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
// 获取当前对话
Long chatId = (Long) session.getAttributes().get("chatId");
Chat chat = chatService.getChatById(chatId);
// 更新对话结束时间
chat.setEndTime(new Date());
chatService.saveChat(chat);
// 移除客户端
chat.removeClient(session);
}
}
```
创建一个Chat实体类,用于存储对话信息和消息:
```java
@Entity
public class Chat {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Date startTime;
private Date endTime;
@OneToMany(mappedBy = "chat", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Message> messages = new ArrayList<>();
@Transient
private List<WebSocketSession> clients = new ArrayList<>();
// ...
}
```
创建一个Message实体类,用于存储消息内容和时间:
```java
@Entity
public class Message {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String content;
private Date time;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "chat_id")
private Chat chat;
// ...
}
```
创建一个ChatService,用于操作Chat和Message实体类,实现对话和消息的保存和查询:
```java
@Service
public class ChatService {
@Autowired
private ChatRepository chatRepository;
public Chat saveChat(Chat chat) {
return chatRepository.save(chat);
}
public Chat getChatById(Long id) {
return chatRepository.findById(id).orElse(null);
}
public Message saveMessage(Message message) {
return messageRepository.save(message);
}
public List<Message> getMessagesByChatId(Long chatId) {
return messageRepository.findByChatId(chatId);
}
}
```
最后,在前端页面中使用JavaScript连接WebSocket,并发送消息到服务器:
```javascript
var socket = new WebSocket("ws://localhost:8080/chat");
socket.onopen = function(event) {
console.log("WebSocket连接已建立");
};
socket.onmessage = function(event) {
console.log("收到消息:" + event.data);
};
socket.onclose = function(event) {
console.log("WebSocket连接已关闭");
};
function sendMessage() {
var message = document.getElementById("message").value;
socket.send(message);
}
```
以上就是使用SpringBoot实现连续对话,并将对话内容保存到MySQL中的方法。
阅读全文