Giter VIP home page Giter VIP logo

hangfire.azure.servicebusqueue's Introduction

Hangfire.Azure.ServiceBusQueue

Official Site Latest version Build status License MIT

What is it?

Adds support for using Azure Service Bus Queues with Hangfire's SQL storage provider to reduce latency and remove the need to poll the database for new jobs.

All job data continues to be stored and maintained within SQL storage, but polling is removed in favour of pushing the job ids through the service bus.

Installation

Hangfire.Azure.ServiceBusQueue is available as a NuGet package. Install it using the NuGet Package Console window:

PM> Install-Package Hangfire.Azure.ServiceBusQueue

Compatibility

Hangfire v1.7+ introduced breaking changes to the SQL Server integration points and requires at least version 4.0.0 of this library. If you are on an older version of Hangfire please use a lower version of Hangfire.Azure.ServiceBusQueue

Usage

To use the queue it needs to be added to your existing SQL Server storage configuration.

For .NETCore and beyond, you can use the IGlobalConfiguration extension .UseServiceBusQueues:

//You can use .UseServiceBusQueues only after .UseSqlStorage()

// Uses default options (no prefix or configuration) with the "default" queue only
services.AddHangfire(configuration => configuration
    .UseSqlServerStorage("<sql connection string>")
    .UseServiceBusQueues("<azure servicebus connection string>")
    
// Uses default options (no prefix or configuration) with the "critical" and "default" queues
services.AddHangfire(configuration => configuration
    .UseSqlServerStorage("<sql connection string>")
    .UseServiceBusQueues("<azure servicebus connection string>", "critical", "default")
    
// Configures queues on creation and uses the "crtical" and "default" queues
services.AddHangfire(configuration => configuration
    .UseSqlServerStorage("<sql connection string>")
    .UseServiceBusQueues("<azure servicebus connection string>", 
        queueOptions => {
            queueOptions.MaxSizeInMegabytes = 5120;
            queueOptions.DefaultMessageTimeToLive = new TimeSpan(0, 1, 0);
        } "critical", "default")
    
// Specifies all options
services.AddHangfire(configuration => configuration
    .UseSqlServerStorage("<sql connection string>")
    .UseServiceBusQueues(new ServiceBusQueueOptions
    {
        ConnectionString = connectionString,
                
        Configure = configureAction,
        
        // The actual queues used in Azure will have this prefix if specified
        // (e.g. the "default" queue will be created as "my-prefix-default")
        //
        // This can be useful in development environments particularly where the machine
        // name could be used to separate individual developers machines automatically
        // (i.e. "my-prefix-{machine-name}".Replace("{machine-name}", Environment.MachineName))
        QueuePrefix = "my-prefix-",
        
        // The queues to monitor. This *must* be specified, even to set just
        // the default queue as done here
        Queues = new [] { EnqueuedState.DefaultQueue },
        
        // By default queues will be checked and created on startup. This option
        // can be disabled if the application will only be sending / listening to 
        // the queue and you want to remove the 'Manage' permission from the shared
        // access policy.
        //
        // Note that the dashboard *must* have the 'Manage' permission otherwise the
        // queue length cannot be read
        CheckAndCreateQueues = false,
        
        // Typically a lower value is desired to keep the throughput of message processing high. A lower timeout means more calls to
        // Azure Service Bus which can increase costs, especially on an under-utilised server with few jobs.
        // Use a Higher value for lower costs in non production or non critical jobs
        LoopReceiveTimeout = TimeSpan.FromMilliseconds(500)
        
        // Delay between queue polling requests
        QueuePollInterval = TimeSpan.Zero
    }));

You can also use UseServiceBusQueues overloads:

var sqlStorage = new SqlServerStorage("<connection string>");

// The connection string *must* be for the root namespace and have the "Manage"
// permission if used by the dashboard
var connectionString = CloudConfigurationManager.GetSetting("Microsoft.ServiceBus.ConnectionString");

// You can configure queues on first creation using this action
Action<QueueDescription> configureAction = qd =>
{
    qd.MaxSizeInMegabytes = 5120;
    qd.DefaultMessageTimeToLive = new TimeSpan(0, 1, 0);
};

// Uses default options (no prefix or configuration) with the "default" queue only
sqlStorage.UseServiceBusQueues(connectionString);

// Uses default options (no prefix or configuration) with the "critical" and "default" queues
sqlStorage.UseServiceBusQueues(connectionString, "critical", "default"); 

// Configures queues on creation and uses the "crtical" and "default" queues
sqlStorage.UseServiceBusQueues(connectionString, configureAction, "critical", "default"); 
    
// Specifies all options
sqlStorage.UseServiceBusQueues(new ServiceBusQueueOptions
    {
        ConnectionString = connectionString,
                
        Configure = configureAction,
        
        // The actual queues used in Azure will have this prefix if specified
        // (e.g. the "default" queue will be created as "my-prefix-default")
        //
        // This can be useful in development environments particularly where the machine
        // name could be used to separate individual developers machines automatically
        // (i.e. "my-prefix-{machine-name}".Replace("{machine-name}", Environment.MachineName))
        QueuePrefix = "my-prefix-",
        
        // The queues to monitor. This *must* be specified, even to set just
        // the default queue as done here
        Queues = new [] { EnqueuedState.DefaultQueue },
        
        // By default queues will be checked and created on startup. This option
        // can be disabled if the application will only be sending / listening to 
        // the queue and you want to remove the 'Manage' permission from the shared
        // access policy.
        //
        // Note that the dashboard *must* have the 'Manage' permission otherwise the
        // queue length cannot be read
        CheckAndCreateQueues = false,
        
        // Typically a lower value is desired to keep the throughput of message processing high. A lower timeout means more calls to
        // Azure Service Bus which can increase costs, especially on an under-utilised server with few jobs.
        // Use a Higher value for lower costs in non production or non critical jobs
        LoopReceiveTimeout = TimeSpan.FromMilliseconds(500)
        
        // Delay between queue polling requests
        QueuePollInterval = TimeSpan.Zero
    });

GlobalConfiguration.Configuration
    .UseStorage(sqlStorage);

Questions? Problems?

Open-source project are developing more smoothly, when all discussions are held in public.

If you have any questions or problems related to Hangfire itself or this queue implementation or want to discuss new features, please visit the discussion forum. You can sign in there using your existing Google or GitHub account, so it's very simple to start using it.

If you've discovered a bug, please report it to the Hangfire GitHub Issues. Detailed reports with stack traces, actual and expected behavours are welcome.

License

Hangfire.Azure.ServiceBusQueues is released under the MIT License.

hangfire.azure.servicebusqueue's People

Contributors

barclayadam avatar danjus10 avatar giampaologabba avatar odinserj avatar tcbroad avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

hangfire.azure.servicebusqueue's Issues

Cancel All Outstanding Recurring Jobs

I'm using this nuget package in one of my websites, and it works great. So thanks for spending the time making this.

I have a question/query regarding RecurringJobs and app restarts/app pool recycles... I have the following code which adds a couple of cron jobs on app start.

RecurringJob.AddOrUpdate(() => new RecurringTasksService().DoSomething(), Cron.HourInterval(2));

Again they work great. However...

I was thinking what about app restarts? What happens to these recurring jobs when the app restarts (i.e. config changes, new code pushed to live etc...)... is the same job added again? Is the old job cancelled on app shutdown? I'm just concerned over time I'll end up with X times of the same recurring job.

So instead of working every 2 hours, because of the constant adding of the job on app start it's firing all the time...

LastHeartbeat SQL Issue

I apologise if I'm not understanding this add on correctly, but I thought adding this would move the polling/heartbeat away from SQL and into AzureServiceBus.

However, I have this running on my site and noticed I've been getting a SQL time out error every now and then which is attributed to "update [HangFire].Server set LastHeartbeat = @now where Id = @id". I can see Hangfire smashing the SQL db every second?

I was under the impression that this removed the need for the constant SQL heartbeat?

new netstandard version with Azure.Messaging.Servicebus ready

Hello,
first of all, great project! This is just what i needed :)

I have developed a new version of this plugin with the following updates:

  • NetStandard 2
  • using the new Azure.Messaging.Servicebus SDK (handling sync over async, as this sdk is fully async but hangfire api is not)
  • new linear policy with an overload for an array of TimeSpan (to define custom waits)
  • No overfetch for message paging in monitorin api
  • New setting for queuepolling (to be able to have an additional timeout in case of low read timeouts and multiple queues)
  • Some new tests

I'm planning to improve multi-queue multithreading (if multiple threads call Dequeue when there are multiple queues it would be better to assign an unique queue to each thread then start looping, instead to always loop from the first queue).

Are you interested in a big PR with all of this? I changed every single file in multiple places, i understand that this will require time to review everything.

All tests are passing and i'm approaching to use it in production

https://github.com/GiampaoloGabba/Hangfire.Azure.ServiceBusQueue

Upgraded to latest version and now get YSOD 'GetEnqueuedJobIds' does not have an implementation?

I have been using this for some time and it's been great. I thought I would upgrade to the latest version, I checked the docs and all seems the same in regards to setup. This is what I have (Which has been working).

var sqlStorage = new SqlServerStorage("umbracoDbDSN");
const string connectionString = "SB_Connnection_String";
sqlStorage.UseServiceBusQueues(new ServiceBusQueueOptions
{
	ConnectionString = connectionString,
	QueuePrefix = $"{website.SiteAlias}-{Environment.MachineName}",
	Queues = new[] {EnqueuedState.DefaultQueue}
});
GlobalConfiguration.Configuration.UseStorage(sqlStorage);
var options = new BackgroundJobServerOptions {WorkerCount = 6};
e.AppBuilder.UseHangfireServer(options);

Since I upgraded to latest version of this package AND latest version of Hangfire. I am getting this error.

Method 'GetEnqueuedJobIds' in type 'Hangfire.Azure.ServiceBusQueue.ServiceBusQueueMonitoringApi' from assembly 'Hangfire.Azure.ServiceBusQueue, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.

[TypeLoadException: Method 'GetEnqueuedJobIds' in type 'Hangfire.Azure.ServiceBusQueue.ServiceBusQueueMonitoringApi' from assembly 'Hangfire.Azure.ServiceBusQueue, Version=0.1.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.]
   Hangfire.Azure.ServiceBusQueue.ServiceBusQueueJobQueueProvider..ctor(ServiceBusQueueOptions options) +0
   Hangfire.Azure.ServiceBusQueue.ServiceBusQueueSqlServerStorageExtensions.UseServiceBusQueues(SqlServerStorage storage, ServiceBusQueueOptions options) +56
   FRF.Web.UmbracoApplicationEventHandler.UmbracoDefaultOwinStartupMiddlewareConfigured(Object sender, OwinMiddlewareConfiguredEventArgs e) in C:\**\UmbracoApplicationEventHandler.cs:185
   Umbraco.Web.UmbracoDefaultOwinStartup.OnMiddlewareConfigured(OwinMiddlewareConfiguredEventArgs args) +47
   Umbraco.Web.UmbracoDefaultOwinStartup.ConfigureMiddleware(IAppBuilder app) +70

Line 185 in the app start class is this

sqlStorage.UseServiceBusQueues(new ServiceBusQueueOptions

Slightly confused what the issue is?

Not working with new version of Hangfire

Hi there,

because of some bugfixes in Hangfire 1.5.0 we updated Hangfire to the newest Version 1.5.2. But it looks like the interfaces changed and this is not reflected in Hangfire.Azure.ServiceBusQueue

I forked an repaired this and going to create a pull-request for this.

Recurring Jobs are not sending a Service Bus Message

I am setting up some recurring tasks to run on queues that are setup to use Azure Service Bus.
When the recurring job is triggered manually (via the dashboard) the job is detected and executed immediately.
But when the job is left to execute at the allotted time, no Service Message is sent and instead a secondary, duplicate queue appears in the dashboard, containing the job - but it remains "Enqueued" indefinitely - as the background server setup to "watch" that queue doesn't know about, presumably because not Message came down via Service Bus.

My workaround at the moment is to have a dedicated, "recurring" queue, that is not using Service Bus, with each recuring job then triggering an normal Background job on the desired queue. But this creates an extra Job, a delay in execution and a polling load on the database that I was hoping to avoid completely.

Is there something I'm not doing correct in the setup of UseServiceBusQueues? All normal background jobs queue and execute correctly. I tried to follow the difference in code between Triggering and background job immediately and normal Cron based execution, but I could not follow the logic easily.

Thanks in advance.

On long job (more than 8 mins) hang fire task are cancelled

Hello,

I am just switching on HangFire.Azure.ServiceBusQueue, after the deployement I saw my long job are always cancelled after 8 mins.
The Task is cancelled.

I will rollback to HangFire.SqlServer to check if I have the same issue.

If you need help to identify the issue I can also help.

Many thank for all the work done on the HangFire project!

EDIT : after rollbacking on HangFire.SqlServer without HangFire.Azure.ServiceBusQueue everything is functionnal.

Weird issue with recent release of .net core sdk

Just install latest version of .net core sdk (3.1.102) and then create a new .net core console app 3.1 and you can't run dotnet restore if you install HangFire.Azure.ServiceBusQueue
You'll get an error as followings:

'.', hexadecimal value 0x00, is an invalid character. Line 1, position 1.

Method 'Enqueue' in type 'Hangfire.Azure.ServiceBusQueue.ServiceBusQueueJobQueue'

Method 'Enqueue' in type 'Hangfire.Azure.ServiceBusQueue.ServiceBusQueueJobQueue' from assembly 'Hangfire.Azure.ServiceBusQueue, Version=4.1.0.0, Culture=neutral, PublicKeyToken=null' does not have an implementation.

Got this error in .NET Core 2.2 project.
Nuget package version Hangfire.Azure.ServiceBusQueue 4.1.0
What is the problem?

Here is the relevant code from ConfigureServices(IServiceCollection services) method

            var sqlStorage = new     SqlServerStorage(SqlServerConnectionString);
            Action<QueueDescription> configureAction = qd =>
            {
                qd.MaxSizeInMegabytes = 5120;
                qd.DefaultMessageTimeToLive = new TimeSpan(0, 1, 0);
            };

                sqlStorage.UseServiceBusQueues(ServiceBusConnectionString);
                sqlStorage.UseServiceBusQueues(ServiceBusConnectionString, "critical", "default");
                sqlStorage.UseServiceBusQueues(ServiceBusConnectionString, configureAction, "critical", "default");

            sqlStorage.UseServiceBusQueues(new ServiceBusQueueOptions
            {
                ConnectionString = ServiceBusConnectionString,
                Configure = configureAction,
                QueuePrefix = "my-prefix-",
                Queues = new[] { EnqueuedState.DefaultQueue },
                CheckAndCreateQueues = false,
                LoopReceiveTimeout = TimeSpan.FromMilliseconds(500)
            });

            GlobalConfiguration.Configuration.UseStorage(sqlStorage);

            services.AddHangfire(configuration => configuration
                .SetDataCompatibilityLevel(CompatibilityLevel.Version_170)
                .UseSimpleAssemblyNameTypeSerializer()
                .UseRecommendedSerializerSettings()
                .UseSqlServerStorage(SqlServerConnectionString, 
                new SqlServerStorageOptions
                {
                    CommandBatchMaxTimeout = TimeSpan.FromMinutes(5),
                    SlidingInvisibilityTimeout = TimeSpan.FromMinutes(5),
                    QueuePollInterval = TimeSpan.Zero,
                    UseRecommendedIsolationLevel = true,
                    UsePageLocksOnDequeue = true,
                    DisableGlobalLocks = true
                }));

            services.AddHangfireServer();

Jobs get lost if the service bus is unavailable, dashboard page fails to load.

Currently, the BackgroundJob scheduler throws a "BackgroundJobClientException" , if the service bus is unavailable during the time in which the job was enqueued. Also the dashboard page fails to load too, if the service bus is unreachable.

This is a big issue and it decreases the reliability of Hangfire itself.

We cannot afford to lose critical jobs just because the gateway service was down.

How about maybe implementing an outbox to temporary hold the jobs in a local cache until the service bus is back online again.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.