Created
November 10, 2015 14:58
-
-
Save ramonsmits/ee0b535da34fad8657e0 to your computer and use it in GitHub Desktop.
Throttle NServiceBus throughput when a custom check fails using the scheduler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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