Web在线聊天室(10) --- 插入消息

Posted 满眼*星辰

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Web在线聊天室(10) --- 插入消息相关的知识,希望对你有一定的参考价值。

插入消息

消息格式

{
	"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);
        }
    }

实现效果

发送一条啦啦啦的消息
在这里插入图片描述
然后查询数据库

在这里插入图片描述
确实有了这条消息

以上是关于Web在线聊天室(10) --- 插入消息的主要内容,如果未能解决你的问题,请参考以下文章

Web在线聊天室(12) --- 收发消息(单例模式+阻塞式队列)

Web在线聊天室(12) --- 收发消息(单例模式+阻塞式队列)

Web在线聊天室 --- 详细设计

Web在线聊天室(11) --- 登陆后显示历史消息

Web在线聊天室(11) --- 登陆后显示历史消息

ASP.NET SignalR 与 LayIM2.0 配合轻松实现Web聊天室 之 用 Redis 实现用户在线离线状态消息处理