插入消息
消息格式
{
"userId": 1,
"nickName": "蔡徐坤",
"channelId": 1,
"content": "这是消息正文"
}
服务器端onMessage方法
@OnMessage
public void onMessage(Session session, String message) {
// 1.遍历保存的所有session,每个都发送消息
MessageCenter.sendMessage(message);
// 2.消息还要保存在数据库,
// (1)反序列化json字符串为message对象
Message msg = Util.deserialize(message, Message.class);
// (2)message设置接收消息的时间
// msg.setSendTime(new Date());
// (3)插入数据库
int n = MessageDao.insert(msg);
System.out.println("接收到的消息:" + message);
}
操作数据库插入方法
/**
* 往数据库插入消息信息
*/
public static int insert(Message msg) {
Connection connection = null;
PreparedStatement statement = null;
try {
connection = Util.getConnection();
String sql = "insert into message values(null,?,?,?,?)";
statement = connection.prepareStatement(sql);
statement.setInt(1,msg.getUserId());
statement.setInt(2,msg.getChannelId());
statement.setString(3,msg.getContent());
statement.setTimestamp(4, new Timestamp(System.currentTimeMillis()));
int result = statement.executeUpdate();
return result;
}catch (Exception e) {
throw new AppException("保存消息出错", e);
}finally {
Util.close(connection,statement);
}
}
实现效果
发送一条啦啦啦的消息
然后查询数据库
确实有了这条消息