简体   繁体   English

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

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

Just starting to work with Azure.刚刚开始使用 Azure。 Have a simple C# .NET Core app, which connects to Azure ServiceBus, reads messages, and writes them to Azure SQL database.有一个简单的 C# .NET Core 应用程序,它连接到 Azure ServiceBus、读取消息并将它们写入 Azure SQL 数据库。 Works locally just fine - connects to remote Azure Service Bus Queue, reads messages, connect to remote Azure SQL db, writes records.在本地工作得很好 - 连接到远程 Azure 服务总线队列,读取消息,连接到远程 Azure SQL 数据库,写入记录。 Same exact app, when deployed to Azure as a WebApp, appears to "run", but no longer reads messages from Services Bus, and no longer writes anything to Azure SQL.同样的应用程序,当作为 WebApp 部署到 Azure 时,似乎“运行”,但不再从服务总线读取消息,并且不再向 Azure SQL 写入任何内容。

Here is the entire app (ie Program.cs):这是整个应用程序(即 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;
        }
    }
}

Should I do anything differently in this app in order to make it work in Azure?为了让它在 Azure 中工作,我是否应该在这个应用程序中做一些不同的事情?

It seems that you are trying to deploy a webjob to web app.您似乎正在尝试将 webjob 部署到 web 应用程序。 May I know if you have set it to Continuous type?我可以知道您是否将其设置为Continuous类型? If you have set it to Continuous , the webjob will automatically run after deployment.如果您将其设置为Continuous ,则 webjob 将在部署后自动运行。

在此处输入图片说明

By default, the type is Triggered and you need to manually start the webjob from portal.默认情况下,类型为Triggered ,您需要从门户手动启动 webjob。

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

相关问题 简单的WebClient在本地工作,但在部署到Azure时无法工作 - Simple WebClient works locally, but not when deployed to Azure 如何在本地使用 Azure ServiceBus - How do I Work with Azure ServiceBus Locally C#文件上传在本地工作; 不在Azure上 - C# File Upload works locally; not on Azure 将映像上传到Azure Blob存储-本地工作,部署后失败 - Uplod images to azure blob storage - Works locally, fails when deployed Web api在本地工作,但在部署到Azure时则不能 - Web api working locally but not when deployed to Azure 如何清除C#(Microsoft.Azure.ServiceBus v3 +)中的Azure ServiceBus主题订阅? - How to purge a Azure ServiceBus Topics Subscrption in C# (Microsoft.Azure.ServiceBus v3+)? c#Web API在本地可用,但发布后在Azure中不起作用 - c# web API locally work, but does not work in Azure after publish Azure上的C#MVC应用程序:新部署时站点工作正常,但闲置后失败 - C# MVC app on Azure: Site works fine when freshly deployed but fails after being left idle Blob 触发的 Azure 函数在部署后不起作用,但在本地运行,并且没有任何错误迹象 - Blob triggered Azure function doesn't work deployed but works locally, and no sign of any error 部署后,Azure 函数中的依赖注入失败但在本地工作 - Dependency Injection failing in Azure function once deployed but works locally
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM