【问题标题】:C# Azure ServiceBus / Azure SQL - works locally, does not seem to work when deployed to AzureC# Azure ServiceBus / Azure SQL - 在本地工作,部署到 Azure 时似乎不工作
【发布时间】:2020-05-05 11:34:46
【问题描述】:

刚开始使用 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 中工作吗?

【问题讨论】:

  • 您需要启用日志记录才能看到发生了什么

标签: c# azure .net-core azure-sql-database azure-webapps


【解决方案1】:

您似乎正在尝试将网络作业部署到网络应用程序。请问您是否已将其设置为Continuous 类型?如果您已将其设置为Continuous,则 webjob 将在部署后自动运行。

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

【讨论】:

    猜你喜欢
    • 2023-01-15
    • 2016-06-20
    • 2012-09-17
    • 2013-01-05
    • 1970-01-01
    • 2012-09-25
    • 2020-10-19
    • 2013-10-20
    相关资源
    最近更新 更多