Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ramonsmits/ee0b535da34fad8657e0 to your computer and use it in GitHub Desktop.
Save ramonsmits/ee0b535da34fad8657e0 to your computer and use it in GitHub Desktop.
Throttle NServiceBus throughput when a custom check fails using the scheduler
using System;
using NServiceBus;
using NServiceBus.Logging;
class ThrottleThroughputWhenCheckFailsUsingScheduler : IWantToRunWhenBusStartsAndStops
{
NServiceBus.Unicast.UnicastBus bus;
Schedule schedule;
ILog Log = LogManager.GetLogger(typeof(CheckBreaker));
bool throttled;
int throttledLimit = 1;
int unthrottledLimit = 0;
public CheckBreaker(Schedule schedule, IBus bus)
{
this.schedule = schedule;
this.bus = (NServiceBus.Unicast.UnicastBus)bus;
}
public void Start()
{
schedule.Every(TimeSpan.FromSeconds(5), "MyCustomTask", SomeCustomMethod);
}
public void Stop()
{
}
void SomeCustomMethod()
{
var result = Check();
Log.DebugFormat("Check: {0}", result);
Log.DebugFormat("Throttled: {0}", throttled);
var transport = bus.Transport;
if (result && throttled)
{
transport.ChangeMaximumMessageThroughputPerSecond(unthrottledLimit);
throttled = false;
Log.InfoFormat("Disabled throttling");
}
if (!result && !throttled)
{
transport.ChangeMaximumMessageThroughputPerSecond(throttledLimit);
throttled = true;
Log.InfoFormat("Enabled throttling");
}
}
int count;
bool Check()
{
return count++ % 4 == 0;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment