webstock的实时推送消息和保存消息的java案例
时间: 2024-03-11 10:49:34 浏览: 150
消息推送实例
一个使用Java实现的实时推送消息和保存消息的案例是基于Spring Boot和WebSocket技术的在线聊天应用程序。
下面是一个简单的示例代码,演示如何使用Java和Spring Boot创建实时聊天应用程序:
1. 创建WebSocket配置类
```java
@Configuration
@EnableWebSocketMessageBroker
public class WebSocketConfig implements WebSocketMessageBrokerConfigurer {
@Override
public void configureMessageBroker(MessageBrokerRegistry config) {
config.enableSimpleBroker("/topic");
config.setApplicationDestinationPrefixes("/app");
}
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
registry.addEndpoint("/chat").withSockJS();
}
}
```
2. 创建控制器类
```java
@Controller
public class ChatController {
@MessageMapping("/chat.sendMessage")
@SendTo("/topic/public")
public ChatMessage sendMessage(@Payload ChatMessage chatMessage) {
return chatMessage;
}
}
```
3. 创建消息实体类
```java
public class ChatMessage {
private MessageType type;
private String content;
private String sender;
private String time;
// getters and setters
public enum MessageType {
CHAT,
JOIN,
LEAVE
}
}
```
4. 创建前端页面
```html
<!DOCTYPE html>
<html>
<head>
<title>WebSocket Chat</title>
<script src="/webjars/jquery/jquery.min.js"></script>
<script src="/webjars/sockjs-client/sockjs.min.js"></script>
<script src="/webjars/stomp-websocket/stomp.min.js"></script>
</head>
<body>
<div id="chat">
<div id="messages"></div>
<form id="messageForm">
<input type="text" id="messageInput" />
<button type="submit">Send</button>
</form>
</div>
<script type="text/javascript">
var stompClient = null;
function connect() {
var socket = new SockJS('/chat');
stompClient = Stomp.over(socket);
stompClient.connect({}, function(frame) {
console.log('Connected: ' + frame);
stompClient.subscribe('/topic/public', function(message) {
showMessage(JSON.parse(message.body));
});
});
}
function showMessage(message) {
var html = '<div class="message">';
html += '<span class="sender">' + message.sender + '</span>';
html += '<span class="time">' + message.time + '</span>';
html += '<p class="content">' + message.content + '</p>';
html += '</div>';
$('#messages').append(html);
}
$(function() {
connect();
$('#messageForm').on('submit', function(event) {
event.preventDefault();
var message = {
type: 'CHAT',
content: $('#messageInput').val(),
sender: 'User',
time: new Date().toISOString()
};
stompClient.send("/app/chat.sendMessage", {}, JSON.stringify(message));
$('#messageInput').val('');
});
});
</script>
</body>
</html>
```
通过上述代码,我们可以实现基于Java和Spring Boot的在线聊天应用程序。用户可以在前端页面上发送消息,并立即在所有其他用户的页面上看到新消息。所有消息都将保存在后端数据库中,以便用户可以随时查看消息历史记录。
阅读全文