繁体   English   中英

C# Azure ServiceBus / Azure SQL - 在本地工作,部署到 Azure 时似乎不起作用

[英]C# Azure ServiceBus / Azure SQL - works locally, does not seem to work when deployed to Azure

刚刚开始使用 Azure。 有一个简单的 C# .NET Core 应用程序,它连接到 Azure ServiceBus、读取消息并将它们写入 Azure SQL 数据库。 在本地工作得很好 - 连接到远程 Azure 服务总线队列,读取消息,连接到远程 Azure SQL 数据库,写入记录。 同样的应用程序,当作为 WebApp 部署到 Azure 时,似乎“运行”,但不再从服务总线读取消息,并且不再向 Azure SQL 写入任何内容。

这是整个应用程序(即 Program.cs):

using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.Azure.ServiceBus;

using System.Data.SqlClient;

namespace ServiceBusReader
{
    class Program
    {
        const string ServiceBusConnectionString = "SB_CONNECTION_STRING";
        const string QueueName = "BasicQueue";
        static IQueueClient queueClient;

        static SqlConnection connection = null;

        public static async Task Main(string[] args)
        {

            System.Diagnostics.Trace.TraceError("Inside Main function...");

            queueClient = new QueueClient(ServiceBusConnectionString, QueueName);

            Console.WriteLine("======================================================");
            System.Diagnostics.Trace.TraceError("======================================================");
            Console.WriteLine("Press ENTER key to exit after receiving all the messages.");
            Console.WriteLine("======================================================");

                SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

                builder.DataSource = "XXXX.database.windows.net"; 
                builder.UserID = "USERID";            
                builder.Password = "PASSWORD";     
                builder.InitialCatalog = "mySampleDatabase";

                connection = new SqlConnection(builder.ConnectionString);
                connection.Open();

            // Register the queue message handler and receive messages in a loop
            RegisterOnMessageHandlerAndReceiveMessages();

            Console.ReadKey();

            await queueClient.CloseAsync();
        }

        static void RegisterOnMessageHandlerAndReceiveMessages()
        {
            // Configure the message handler options in terms of exception handling, number of concurrent messages to deliver, etc.
            var messageHandlerOptions = new MessageHandlerOptions(ExceptionReceivedHandler)
            {
                // Maximum number of concurrent calls to the callback ProcessMessagesAsync(), set to 1 for simplicity.
                // Set it according to how many messages the application wants to process in parallel.
                MaxConcurrentCalls = 1,

                // Indicates whether the message pump should automatically complete the messages after returning from user callback.
                // False below indicates the complete operation is handled by the user callback as in ProcessMessagesAsync().
                AutoComplete = false
            };

            // Register the function that processes messages.
            queueClient.RegisterMessageHandler(ProcessMessagesAsync, messageHandlerOptions);
        }

        static async Task ProcessMessagesAsync(Message message, CancellationToken token)
        {
            // Process the message.
            Console.WriteLine($"Received message: SequenceNumber:{message.SystemProperties.SequenceNumber} Body:{Encoding.UTF8.GetString(message.Body)}");

             string query = "INSERT INTO [SalesLT].[messages] (message) VALUES(@Message)"; 
             SqlCommand cmd = new SqlCommand(query, connection);
             System.Diagnostics.Trace.TraceError(Encoding.UTF8.GetString(message.Body));
             cmd.Parameters.AddWithValue("@Message", Encoding.UTF8.GetString(message.Body));

             cmd.ExecuteNonQuery();
             Console.WriteLine("Records Inserted Successfully...");
             System.Diagnostics.Trace.TraceError("Records Inserted Successfully...");

            // Complete the message so that it is not received again.
            // This can be done only if the queue Client is created in ReceiveMode.PeekLock mode (which is the default).
            await queueClient.CompleteAsync(message.SystemProperties.LockToken);

            // Note: Use the cancellationToken passed as necessary to determine if the queueClient has already been closed.
            // If queueClient has already been closed, you can choose to not call CompleteAsync() or AbandonAsync() etc.
            // to avoid unnecessary exceptions.
        }

        // Use this handler to examine the exceptions received on the message pump.
        static Task ExceptionReceivedHandler(ExceptionReceivedEventArgs exceptionReceivedEventArgs)
        {
            Console.WriteLine($"Message handler encountered an exception {exceptionReceivedEventArgs.Exception}.");
            var context = exceptionReceivedEventArgs.ExceptionReceivedContext;
            Console.WriteLine("Exception context for troubleshooting:");
            Console.WriteLine($"- Endpoint: {context.Endpoint}");
            Console.WriteLine($"- Entity Path: {context.EntityPath}");
            Console.WriteLine($"- Executing Action: {context.Action}");
            return Task.CompletedTask;
        }
    }
}

为了让它在 Azure 中工作,我是否应该在这个应用程序中做一些不同的事情?

您似乎正在尝试将 webjob 部署到 web 应用程序。 我可以知道您是否将其设置为Continuous类型? 如果您将其设置为Continuous ,则 webjob 将在部署后自动运行。

在此处输入图片说明

默认情况下,类型为Triggered ,您需要从门户手动启动 webjob。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM