Created
January 17, 2014 08:38
-
-
Save sixeyed/8470181 to your computer and use it in GitHub Desktop.
Mutator for NServiceBus which compresses large messages (>1Kb)
This file contains hidden or 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 Sixeyed.NServiceBus.Mutators; | |
using log4net.Config; | |
using Microsoft.Practices.Unity; | |
using NServiceBus; | |
using NServiceBus.Features; | |
using nsb = NServiceBus; | |
namespace Sixeyed.NServiceBus | |
{ | |
public static class DefaultBus | |
{ | |
public static nsb.Configure Configure(IUnityContainer container, bool enableLargeMessageCompression) | |
{ | |
SetLoggingLibrary.Log4Net(() => XmlConfigurator.Configure()); | |
var config = nsb.Configure.With() | |
.Log4Net() | |
.UnityBuilder(container) | |
.UnicastBus(); | |
if (enableLargeMessageCompression) | |
{ | |
nsb.Configure.Component<LargeMessageCompressingMutator>(DependencyLifecycle.InstancePerCall); | |
} | |
return config; | |
} | |
} | |
} |
This file contains hidden or 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 NServiceBus; | |
using NServiceBus.MessageMutator; | |
using System.IO; | |
using System.IO.Compression; | |
namespace Sixeyed.NServiceBus.Mutators | |
{ | |
public class LargeMessageCompressingMutator : IMutateTransportMessages | |
{ | |
public void MutateOutgoing(object[] messages, TransportMessage transportMessage) | |
{ | |
if (transportMessage.Body.Length <= 1024) return; | |
using (var outStream = new MemoryStream()) | |
{ | |
using (var compressedStream = new GZipStream(outStream, CompressionMode.Compress)) | |
{ | |
using (var inStream = new MemoryStream(transportMessage.Body)) | |
{ | |
inStream.CopyTo(compressedStream); | |
compressedStream.Flush(); | |
} | |
} | |
transportMessage.Body = outStream.ToArray(); | |
} | |
transportMessage.Headers["Sixeyed.Properties.IsCompressed"] = "true"; | |
} | |
public void MutateIncoming(TransportMessage transportMessage) | |
{ | |
if (!transportMessage.Headers.ContainsKey("Sixeyed.Properties.IsCompressed")) | |
return; | |
using (var outStream = new MemoryStream()) | |
{ | |
using (var inStream = new MemoryStream(transportMessage.Body)) | |
{ | |
using (var uncompressedStream = new GZipStream(inStream, CompressionMode.Decompress)) | |
{ | |
uncompressedStream.CopyTo(outStream); | |
outStream.Flush(); | |
} | |
} | |
transportMessage.Body = outStream.ToArray(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment