c# - 在 Service Fabric 应用程序中运行时 WebJob SDK 不工作

标签 c# azure-service-fabric azure-webjobs

我想在作为 Service Fabric 应用程序运行的无状态服务中使用 WebJob SDK。不幸的是我无法让它正常运行。下面是重现问题的测试代码的一部分。永远不会调用“ProcessMethod“。触发函数“ProcessNotificationsInQueue”也从未执行(是的,队列中有项目)。尽管应用程序仍在运行,但应用程序的“健康状态”在 Service Fabric Explorer 中设置为“错误”。

DashboardConnectionString 和 StorageConnectionString 都有正确的值。

在控制台应用程序或 WorkerRole 中运行非常相似的代码时,我没有发现任何问题。

我错过了什么吗?是否有人已在 Service Fabric 应用程序中成功使用 WebJob SDK?

public sealed class TestStatelessService : StatelessService
{
    public TestStatelessService(StatelessServiceContext context)
        : base(context)
    { }

    /// <summary>
    /// Optional override to create listeners (e.g., TCP, HTTP) for this service replica to handle client or user requests.
    /// </summary>
    /// <returns>A collection of listeners.</returns>
    protected override IEnumerable<ServiceInstanceListener> CreateServiceInstanceListeners()
    {
        return new ServiceInstanceListener[0];
    }

    /// <summary>
    /// This is the main entry point for your service instance.
    /// </summary>
    /// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param>
    protected override async Task RunAsync(CancellationToken cancellationToken)
    {
        ConfigurationPackage configPackage = this.Context.CodePackageActivationContext.GetConfigurationPackageObject("Config");
        KeyedCollection<string, ConfigurationProperty> parameters = configPackage.Settings.Sections["MyConfigSection"].Parameters;

        JobHostConfiguration config = new JobHostConfiguration();
        config.DashboardConnectionString = parameters["AzureWebJobsDashboard"].Value;
        config.StorageConnectionString = parameters["AzureWebJobsStorage"].Value;
        config.Queues.BatchSize = 10;
        config.Queues.MaxDequeueCount = 8;
        config.Queues.MaxPollingInterval = TimeSpan.FromSeconds(30);
        var host = new JobHost(config);
        host.CallAsync(typeof(TestStatelessService).GetMethod("ProcessMethod"), cancellationToken);
        host.RunAndBlock();
    }

    [NoAutomaticTrigger]
    public async Task ProcessMethod(CancellationToken cancellationToken)
    {
        long iterations = 0;
        while (true)
        {
            cancellationToken.ThrowIfCancellationRequested();

            ServiceEventSource.Current.ServiceMessage(this, "Working-{0}", ++iterations);

            await Task.Delay(TimeSpan.FromSeconds(1), cancellationToken);
        }
    }

    [Timeout("00:03:00")]
    public static void ProcessNotificationsInQueue([QueueTrigger("newnotificationqueue")] Notification notification)
    {
       //Do something 
    }
}

最佳答案

host.CallAsync(typeof(TestStatelessService).GetMethod("ProcessMethod"), cancellationToken)

请注意 TestStatelessService 类没有定义无参数构造函数,因此您可以将 ProcessMethod 函数标记为静态。

根据你的描述,我按照这个tutorial创建 Azure Service Fabric 应用程序。根据您的代码,我在我的 Service Fabric 应用程序中成功测试了 WebJob SDK。这是我的代码示例,请尝试找出是否适合您。

TestStatelessService.cs

/// <summary>
/// This is the main entry point for your service instance.
/// </summary>
/// <param name="cancellationToken">Canceled when Service Fabric needs to shut down this service instance.</param>
protected override async Task RunAsync(CancellationToken cancellationToken)
{
    ConfigurationPackage configPackage = this.Context.CodePackageActivationContext.GetConfigurationPackageObject("Config");
    KeyedCollection<string, ConfigurationProperty> parameters = configPackage.Settings.Sections["MyConfigSection"].Parameters;

    JobHostConfiguration config = new JobHostConfiguration();
    config.DashboardConnectionString = parameters["AzureWebJobsDashboard"].Value;
    config.StorageConnectionString = parameters["AzureWebJobsStorage"].Value;
    config.Queues.BatchSize = 10;
    config.Queues.MaxDequeueCount = 8;
    config.Queues.MaxPollingInterval = TimeSpan.FromSeconds(30);
    var host = new JobHost(config);
    host.CallAsync(typeof(TestStatelessService).GetMethod("ProcessMethod"),cancellationToken);
    host.RunAndBlock();
}

[NoAutomaticTrigger]
public static async Task ProcessMethod(CancellationToken cancellationToken)
{
    long iterations = 0;
    while (true)
    {
        cancellationToken.ThrowIfCancellationRequested();
        //log
        Trace.TraceInformation(">>[{0}]ProcessMethod Working-{1}",DateTime.UtcNow.ToString("yyyy-MM-dd HH:mm:ss"),++iterations);
        //sleep for 5s
        await Task.Delay(TimeSpan.FromSeconds(5), cancellationToken);
    }
}

[Timeout("00:03:00")]
public static void ProcessNotificationsInQueue([QueueTrigger("newnotificationqueue")] CloudQueueMessage notification)
{
    Trace.TraceInformation(">ProcessNotificationsInQueue invoked with notification:{0}", notification.AsString);
}

结果

The “Health State” of the application is set to “Error” in the Service Fabric Explorer although the application is still running.

请尝试调试您这边的代码,找出详细的错误。

关于c# - 在 Service Fabric 应用程序中运行时 WebJob SDK 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39332081/

相关文章:

c# - 在 C# 中为自定义脚本语言创建语法检查器

c# - 使用 C# 在 ASP.NET 中解码条码图像

c# - 如何订阅依赖注入(inject)服务的事件

c# - 如何在不更改格式/间距的情况下在 C# 中编辑 XML?

azure - 部署 webjob 计划时出错 - 响应状态代码不表示成功 : 409 (Conflict)

powershell - VS2015 中的 Service Fabric,PowerShell 脚本执行失败

Azure KeyVaultAccessForbidden - "not enabled for deployment"

azure - Azure 负载均衡器如何支持 Service Fabric 集群的动态端口?

Azure:Web.config 连接字符串'参数不能为 null 或为空

用于查询 Azure Active Directory 的 Azure 服务