以下是C#实现从消息队列中读取消息并记录到数据库中的示例代码:

using System;
using System.Data.SqlClient;
using System.Messaging;

namespace MessageQueueExample
{
    class Program
    {
        static void Main(string[] args)
        {
            // 消息队列路径
            string queuePath = @'.\Private$\MyQueue';

            // 连接字符串
            string connectionString = "Data Source=.;Initial Catalog=MyDatabase;Integrated Security=True;";

            // 创建消息队列
            if (!MessageQueue.Exists(queuePath))
            {
                MessageQueue.Create(queuePath);
            }

            // 连接数据库
            using (SqlConnection connection = new SqlConnection(connectionString))
            {
                connection.Open();

                // 从消息队列中读取消息
                using (MessageQueue queue = new MessageQueue(queuePath))
                {
                    queue.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });

                    while (true)
                    {
                        Message message = queue.Receive();

                        if (message != null)
                        {
                            // 将消息记录到数据库中
                            using (SqlCommand command = new SqlCommand("INSERT INTO Messages (Content) VALUES (@Content)", connection))
                            {
                                command.Parameters.AddWithValue("@Content", message.Body.ToString());
                                command.ExecuteNonQuery();
                            }
                        }
                    }
                }
            }
        }
    }
}

在上面的示例代码中,我们首先创建了一个消息队列,并在程序中连接到数据库。然后,我们使用MessageQueue类从消息队列中读取消息,并将消息内容插入到数据库中。在SqlCommand的构造函数中,我们使用参数化查询来避免SQL注入攻击。

需要注意的是,上面的代码是一个简单的示例。在实际应用中,可能需要处理一些异常情况,例如连接数据库失败、读取消息超时等。

C# 从消息队列读取消息并写入数据库

原文地址: https://www.cveoy.top/t/topic/lFIV 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录