<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>NGinn BPM</title>
	<atom:link href="http://nginn.org/blog/?feed=rss2" rel="self" type="application/rss+xml" />
	<link>http://nginn.org/blog</link>
	<description>Blog about NGinn BPM project, software architecture and programming</description>
	<lastBuildDate>Fri, 04 Nov 2011 07:36:27 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>Performance of NGinn-messagebus part 2 &#8211; updated results for an SSD disk</title>
		<link>http://nginn.org/blog/?p=510&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=performance-testing-updated-results-for-an-ssd-disk</link>
		<comments>http://nginn.org/blog/?p=510#comments</comments>
		<pubDate>Thu, 03 Nov 2011 18:32:38 +0000</pubDate>
		<dc:creator>RafalG</dc:creator>
				<category><![CDATA[EN]]></category>
		<category><![CDATA[messagebus]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[SQL]]></category>
		<category><![CDATA[ssd]]></category>

		<guid isPermaLink="false">http://nginn.org/blog/?p=510</guid>
		<description><![CDATA[Today I had a chance to test the performance of Nginn-messagebus on a nice laptop with an SSD disk. The test cases were the same as described in Performance testing of Nginn-messagebus so you can directly compare them and see &#8230; <a href="http://nginn.org/blog/?p=510">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2011-11-04 07:36:46 -->Today I had a chance to test the performance of Nginn-messagebus on a nice laptop with an SSD disk. The test cases were the same as described in <a href="http://nginn.org/blog/?p=488">Performance testing of Nginn-messagebus</a> so you can directly compare them and see what is the performance impact of using SSD disk instead of a standard one.<br />
Quick conclusion is that efficient disk I/O is the key to high performance. The testing machine had also a faster processor (core i7 2.2 GHz vs core i7 1.73 GHz in previous test), but it was the SSD disk that made a difference.<br />
<span id="more-510"></span>&#8216;s</p>
<p>Short summary of tests performed:</p>
<ul>
<li class="first-item">we tested sending messages, receiving them and request-reply case (receiving a message and replying to it)</li>
<li>each time the test was performed on 100 000 messages and we measured the time taken</li>
<li>Nginn-messagebus handles durable and transactional messages only so take it into consideration when comparing with other tools</li>
<li class="last-item">We tested local queue performance only (without sending messages to a remote database).</li>
</ul>
<p>You can find the test details <a href="http://nginn.org/blog/?p=488">here</a>.</p>
<h2 id="510_test_cases_1_and_2_-_sending_messages">Test cases 1 and 2 &#8211; sending messages <a class="heading-link" href="http://nginn.org/blog/?p=510#test_cases_1_and_2_-_sending_messages" title="Link to this section">¶</a></h2>
<p><strong> sending messages &#8211; 1 thread, no batching </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time</th>
<th>Msgs/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>00:00:37.62</td>
<td>2658</td>
</tr>
<tr>
<td>2</td>
<td>00:00:36.69</td>
<td>2725,2</td>
</tr>
</tbody>
</table>
<p><strong> sending messages &#8211; 1 thread, batches of 10 per transaction </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time</th>
<th>Msgs/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>00:00:38.81</td>
<td>2572,7</td>
</tr>
<tr>
<td>2</td>
<td>00:00:35.63</td>
<td>2805,9</td>
</tr>
<tr>
<td>3</td>
<td>00:00:33.39</td>
<td>2994,0</td>
</tr>
</tbody>
</table>
<p><strong> Multithreaded sending messages, 4 threads, batch size 10 </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time</th>
<th>Msgs/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>00:00:07.96</td>
<td>12554,2</td>
</tr>
<tr>
<td>2</td>
<td>00:00:07.83</td>
<td>12760</td>
</tr>
</tbody>
</table>
<p><strong> Multithreaded sending messages, 4 threads, no batching </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time</th>
<th>Msgs/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>00:00:09.44</td>
<td>10592,6</td>
</tr>
<tr>
<td>2</td>
<td>00:00:09.46</td>
<td>10562,4</td>
</tr>
</tbody>
</table>
<p><strong> Multithreaded sending messages, 8 threads, no batching </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time</th>
<th>Msgs/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>00:00:06.52</td>
<td>15327,1</td>
</tr>
<tr>
<td>2</td>
<td>00:00:06.47</td>
<td>15455,0</td>
</tr>
</tbody>
</table>
<p><strong> Multithreaded sending messages, 8 threads, batch size 10 </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time</th>
<th>Msgs/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>00:00:05.74</td>
<td>17420,60</td>
</tr>
<tr>
<td>2</td>
<td>00:00:05.75</td>
<td>17381,2</td>
</tr>
</tbody>
</table>
<h2 id="510_test_case_3_-_receiving_messages">Test case 3 &#8211; receiving messages <a class="heading-link" href="http://nginn.org/blog/?p=510#test_case_3_-_receiving_messages" title="Link to this section">¶</a></h2>
<p><strong> receiving messages &#8211; 1 thread </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time (secs)</th>
<th>Messages recv/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>126</td>
<td>793</td>
</tr>
<tr>
<td>2</td>
<td>129</td>
<td>775</td>
</tr>
</tbody>
</table>
<p><strong> receiving messages &#8211; 4 threads </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time (secs)</th>
<th>Messages recv/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>58</td>
<td>1724</td>
</tr>
<tr>
<td>2</td>
<td>58</td>
<td>1724</td>
</tr>
</tbody>
</table>
<p><strong> receiving messages &#8211; 8 threads </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time (secs)</th>
<th>Messages recv/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>52</td>
<td>1923</td>
</tr>
<tr>
<td>2</td>
<td>58</td>
<td>1724</td>
</tr>
</tbody>
</table>
<p><strong> receiving messages &#8211; 12 threads </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time (secs)</th>
<th>Messages recv/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>49</td>
<td>2040</td>
</tr>
<tr>
<td>2</td>
<td>50</td>
<td>2000</td>
</tr>
</tbody>
</table>
<h2 id="510_test_case_4_-_request.2Freply">Test case 4 &#8211; Request/reply <a class="heading-link" href="http://nginn.org/blog/?p=510#test_case_4_-_request.2Freply" title="Link to this section">¶</a></h2>
<p><strong> Request-reply, 12 threads </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time (secs)</th>
<th>Messages recv/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>55</td>
<td>1818</td>
</tr>
<tr>
<td>2</td>
<td>55</td>
<td>1818</td>
</tr>
</tbody>
</table>
<p><strong> Request-reply, 8 threads </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time (secs)</th>
<th>Messages recv/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>57</td>
<td>1754</td>
</tr>
<tr>
<td>2</td>
<td>56</td>
<td>1785</td>
</tr>
</tbody>
</table>
<p><strong> Request-reply, 4 threads </strong></p>
<table>
<thead>
<tr>
<th>Run</th>
<th>Total time (secs)</th>
<th>Messages recv/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>67</td>
<td>1492</td>
</tr>
<tr>
<td>2</td>
<td>68</td>
<td>1470</td>
</tr>
</tbody>
</table>
<h2 id="510_and_some_final_thoughts">And some final thoughts <a class="heading-link" href="http://nginn.org/blog/?p=510#and_some_final_thoughts" title="Link to this section">¶</a></h2>
<ul>
<li class="first-item">The numbers are very good, both for sending and for receiving. NGinn-messagebus offers very good transactional processing performance,probably better than MSMQ (for transactional and durable messages only)</li>
<li>Although the tests showed quite good peak performance, they did not tell us anything about sustainable performance &#8211; that is, how many messages per second we are able to process when the load is sustained for a long period of time.</li>
<li>Send performance was very good, but we did not test how fast the data is removed from the queue. The cleanup did not kick in in such short testing.</li>
<li>We tested local database only, without transferring the messages to a remote database. Such functionality is present in NGinn-messagebus but currently is not very fast because messages are sent one by one. Further optimization is needed here and also a more elaborate testing environment for evaluating the performance.</li>
<li class="last-item">
<p>It would be very interesting to perform similar tests for SQL Service Broker and for MSMQ and compare the results. I suppose SSB would be not that fast when sending messages but it would be much better in transferring messages to a remote database and might be faster in receiving (because with SSB we don&#8217;t have to use polling to retrieve the messages). MSMQ is fast but usually you have to use a distributed transaction when you want to process the message in a transactional way and this kills performance.</p>
</li>
</ul>
]]></content:encoded>
			<wfw:commentRss>http://nginn.org/blog/?feed=rss2&#038;p=510</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>Performance testing of Nginn-messagebus</title>
		<link>http://nginn.org/blog/?p=488&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=performance-testing-of-nginn-messagebus</link>
		<comments>http://nginn.org/blog/?p=488#comments</comments>
		<pubDate>Thu, 03 Nov 2011 14:17:08 +0000</pubDate>
		<dc:creator>RafalG</dc:creator>
				<category><![CDATA[EN]]></category>
		<category><![CDATA[messagebus]]></category>
		<category><![CDATA[performance]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://nginn.org/blog/?p=488</guid>
		<description><![CDATA[Today&#8217;s post is going to be about performance of nginn-messagebus and its underlying SQL message queues. I prepared several test cases for sending messages, receiving them and duplex (request-reply) communication and measured the performance in each case. In every scenario &#8230; <a href="http://nginn.org/blog/?p=488">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2011-11-03 14:18:08 -->Today&#8217;s post is going to be about performance of nginn-messagebus and its underlying SQL message queues. I prepared several test cases for sending messages, receiving them and duplex (request-reply) communication and measured the performance in each case. In every scenario we are looking only at the number of messages processed (sent, received) per second.<br />
The tests are repeated for different configuration options (batch size, number of processing threads) to give us insight on how these parameters affect the overall performance.</p>
<p><span id="more-488"></span></p>
<h2 id="488_test_setup">Test setup <a class="heading-link" href="http://nginn.org/blog/?p=488#test_setup" title="Link to this section">¶</a></h2>
<p>All tests were performed on a Dell Latitude E6510 laptop with 8 Gb of RAM, Intel Core i7 740QM processor (8 cores reported) and a single 500 GB 5400 RPM hard drive. Operating system was Windows 7 Professional x64. SQL Server 2008 developer edition.<br />
This means that these results will not tell you too much about what performance to expect from nginn-messagebus on a real server machine, but you can expect that the numbers will be much better for real hardware. As soon as I have a decent testing machine I will post updated test results for comparison.</p>
<h2 id="488_test_1._sending_messages_to_local_queue">Test 1. Sending messages to local queue <a class="heading-link" href="http://nginn.org/blog/?p=488#test_1._sending_messages_to_local_queue" title="Link to this section">¶</a></h2>
<p>In this scenario we are publishing or sending messages to a local queue. It means that messages are inserted directly into the underlying queue table so what we are really testing is SQL server insert performance. Here&#8217;s the test code:</p>
<pre class="code">        static void TestSending2()
        {
            var mc = Configure(&quot;sql://nginn/MQ_PT1&quot;, true);
            IMessageBus mb = mc.Resolve&lt;IMessageBus&gt;();
            Thread.Sleep(1000);
            Console.WriteLine(&quot;Starting TestSending2&quot;);
            DateTime dt = DateTime.Now;
            int N = 100000;
            int B = 10;
            var to = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TimeSpan.FromSeconds(30) };
            for (int i = 0; i &lt; N / B; i++)
            {
                using (var sc = new TransactionScope(TransactionScopeOption.Required, to))
                {
                    for (int j = 0; j &lt; B; j++)
                    {
                        mb.Send(&quot;sql://nginn/MQ_PT1&quot;, new TestMessage1 { Id = (i * B + j).ToString() });
                    }
                    sc.Complete();
                }
            }
            TimeSpan ts = DateTime.Now - dt;
            Console.WriteLine(&quot;Sent {0} messages in {1}, {2} msgs/second&quot;, N, ts, N / ts.TotalSeconds);
        }</pre>
<p>This code sends 100000 messages in a single thread, as individual messages or in batches (<code>B</code> variable is the batch size) to local <code>sql://nginn/MQ_PT1</code> queue). Each batch is sent as a single transaction. Messages are left in the queue (no one is consuming them during the test). Here are the test results for single message sending (B = 1) and for batches of 10 messages (B = 10). The numbers mean messages sent per second.</p>
<p><strong>Sending single messages:</strong></p>
<table>
<tr>
<th>Run#</th>
<td>Test time</td>
<td>Messages sent/sec</td>
</tr>
<tr>
<td>1</td>
<td>00:01:52.53</td>
<td>1094,7</td>
</tr>
<tr>
<td>2</td>
<td>00:01:23.72</td>
<td>1194,4</td>
</tr>
<tr>
<td>3</td>
<td>00:01:53.52</td>
<td>880,6</td>
</tr>
<tr>
<td>4</td>
<td>00:01:34.25</td>
<td>1060,6</td>
</tr>
</table>
<p><strong>Sending in batches of 10 messages:</strong></p>
<table>
<tr>
<th>Run#</th>
<td>Test time</td>
<td>Messages sent/sec</td>
</tr>
<tr>
<td>1</td>
<td>00:01:31.34</td>
<td>1094,7</td>
</tr>
<tr>
<td>2</td>
<td>00:01:11.79</td>
<td>1392,8</td>
</tr>
<tr>
<td>3</td>
<td>00:01:20.14</td>
<td>1247,7</td>
</tr>
<tr>
<td>4</td>
<td>00:01:15.29</td>
<td>1328,1</td>
</tr>
</table>
<p>As you can see, batching the messages improves the performance but the improvement is only about 30% compared to sending of single messages.</p>
<h2 id="488_test_2.3A_multi-threaded_sending_of_messages">Test 2: multi-threaded sending of messages <a class="heading-link" href="http://nginn.org/blog/?p=488#test_2.3A_multi-threaded_sending_of_messages" title="Link to this section">¶</a></h2>
<p>This is basically the same test as the previous one (sending messages to a local queue) but in this case we are sending 100000 messages using multiple threads. The test was performed for 4 and 8 threads and for single messages in transaction vs batches of 10 messages. </p>
<p>Here&#8217;s the testing code:</p>
<pre class="code">static long _cnt = 0;
static IMessageBus Bus { get; set; }
static int N;
static int B;

/// &lt;summary&gt;
/// batched sending
/// &lt;/summary&gt;
static void TestMTSending2(int batchSize, int threads)
{
    var mc = Configure(&quot;sql://nginn/MQ_PT1&quot;, true);
    Bus = mc.Resolve&lt;IMessageBus&gt;();
    Thread.Sleep(1000);
    Console.WriteLine(&quot;Starting TestMTSending2&quot;);
    DateTime dt = DateTime.Now;
    N = 100000;
    B = batchSize;
    int T = threads;
    List&lt;Thread&gt; proc = new List&lt;Thread&gt;();
    for (int t = 0; t&lt;T; t++)
    {
        var th = new Thread(new ThreadStart(ThreadedSend));
        proc.Add(th);
    }
    foreach (var th in proc)
    {
        th.Start();
    }
    foreach (var th in proc)
    {
        th.Join();
    }

    TimeSpan ts = DateTime.Now - dt;
    Console.WriteLine(&quot;TestMTSending2 sent {0} messages in {1}, {2} msgs/second&quot;, N, ts, N / ts.TotalSeconds);
}

static void ThreadedSend()
{
    var to = new TransactionOptions { IsolationLevel = IsolationLevel.ReadCommitted, Timeout = TimeSpan.FromSeconds(30) };
    while (true)
    {
        using (var sc = new TransactionScope(TransactionScopeOption.Required, to))
        {
            for (int j = 0; j &lt; B; j++)
            {
                var i = Interlocked.Increment(ref _cnt);
                if (i &gt;= N) return;
                Bus.Send(&quot;sql://nginn/MQ_PT1&quot;, new TestMessage1 { Id = i.ToString() });
            }
            sc.Complete();
        }
    }
}</pre>
<p>And the results are</p>
<p><strong>4 sending threads, individual messages (B=1):</strong></p>
<table>
<thead>
<tr>
<th>Run#</th>
<th>Test time</th>
<th>Messages sent/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>00:00:28.13</td>
<td>3553,7</td>
</tr>
<tr>
<td>2</td>
<td>00:00:25.45</td>
<td>3928,4</td>
</tr>
</tbody>
</table>
<p>As you can see, introducing 4 threads boosted the performance 4-fold. </p>
<p><strong>4 sending threads, batches of 10 messages (B=10):</strong></p>
<table>
<thead>
<tr>
<th>Run#</th>
<th>Test time</th>
<th>Messages sent/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>00:00:19.25</td>
<td>5194,7</td>
</tr>
<tr>
<td>2</td>
<td>00:00:18.69</td>
<td>5348,1</td>
</tr>
<tr>
<td>3</td>
<td>00:00:17.56</td>
<td>5692,4</td>
</tr>
</tbody>
</table>
<p><strong>8 sending threads, batches of 10 messages:</strong></p>
<table>
<thead>
<tr>
<th>Run#</th>
<th>Test time</th>
<th>Messages sent/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>00:00:18.75</td>
<td>5331,0</td>
</tr>
<tr>
<td>2</td>
<td>00:00:21.09</td>
<td>4740,1</td>
</tr>
<tr>
<td>3</td>
<td>00:00:18.48</td>
<td>5410,6</td>
</tr>
</tbody>
</table>
<p><strong>8 sending threads, single messages (B=1):</strong></p>
<table>
<thead>
<tr>
<th>Run#</th>
<th>Test time</th>
<th>Messages sent/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>00:00:15.17</td>
<td>6591,5</td>
</tr>
<tr>
<td>2</td>
<td>00:00:18.47</td>
<td>5413,8</td>
</tr>
<tr>
<td>3</td>
<td>00:00:15.26</td>
<td>6552,2</td>
</tr>
</tbody>
</table>
<p>In this case we have &#8216;peaked&#8217; at about 6500 messages sent/second when sending single messages in 8 threads. </p>
<h2 id="488_test_3.3A_receiving_messages">Test 3: Receiving messages <a class="heading-link" href="http://nginn.org/blog/?p=488#test_3.3A_receiving_messages" title="Link to this section">¶</a></h2>
<p>In this test we will be receiving 100000 messages that were sent in previous tests. The received message is delivered to its handler that does nothing (only logs the fact that the message has been delivered). We will be varying the number of receiving threads.</p>
<p>The code:</p>
<pre class="code">//this function just waits until all messages are received
static void TestReceiving1()
{
    var mc = Configure(&quot;sql://nginn/MQ_PT1&quot;, false);
    IMessageBus mb = mc.Resolve&lt;IMessageBus&gt;();
    Console.WriteLine(&quot;Now receiving. Enter to exit&quot;);
    Console.ReadLine();
}

public class TestMessageHandler1 : IMessageConsumer&lt;TestMessage1&gt;
{
    private static Logger log = LogManager.GetCurrentClassLogger();

    public void Handle(TestMessage1 message)
    {
        log.Debug(&quot;Handling {0}&quot;, message.Id);
        //do nothing
    }
}</pre>
<p>In this case the processing time is recorded in the database (there&#8217;s <code>last_processed</code> column in the queue table that contains the time when message was processed). Based on that column we can calculate the overall message receiving performance.</p>
<p><strong>Single threaded receive</strong></p>
<table>
<thead>
<tr>
<th>Run#</th>
<th>Test time (sec)</th>
<th>Messages received/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>226</td>
<td>442</td>
</tr>
<tr>
<td>2</td>
<td>214</td>
<td>467</td>
</tr>
</tbody>
</table>
<p><strong>4 receiving threads</strong></p>
<table>
<thead>
<tr>
<th>Run#</th>
<th>Test time (sec)</th>
<th>Messages received/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>97</td>
<td>1030</td>
</tr>
<tr>
<td>2</td>
<td>91</td>
<td>1098</td>
</tr>
<tr>
<td>3</td>
<td>96</td>
<td>1041</td>
</tr>
</tbody>
</table>
<p><strong>8 receiving threads</strong></p>
<table>
<thead>
<tr>
<th>Run#</th>
<th>Test time (sec)</th>
<th>Messages received/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>79</td>
<td>1265</td>
</tr>
<tr>
<td>2</td>
<td>88</td>
<td>1136</td>
</tr>
<tr>
<td>3</td>
<td>99</td>
<td>1010</td>
</tr>
</tbody>
</table>
<p><strong>12 receiving threads</strong></p>
<table>
<thead>
<tr>
<th>Run#</th>
<th>Test time (sec)</th>
<th>Messages received/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>78</td>
<td>1282</td>
</tr>
<tr>
<td>2</td>
<td>85</td>
<td>1176</td>
</tr>
</tbody>
</table>
<h2 id="488_test_4_-_request-reply_scenario">Test 4 &#8211; Request-Reply scenario <a class="heading-link" href="http://nginn.org/blog/?p=488#test_4_-_request-reply_scenario" title="Link to this section">¶</a></h2>
<p>In this test for each received message we will be sending a single reply message. This is basically the same test as (3) but with the addition of a reply.</p>
<p>The code:</p>
<pre class="code">public class TestMessage1Reply
{
    public string RequestId { get; set; }
}

public class TestMessageHandler1 : IMessageConsumer&lt;TestMessage1&gt;
{
    private static Logger log = LogManager.GetCurrentClassLogger();

    public IMessageBus MessageBus { get; set; }

    public void Handle(TestMessage1 message)
    {
        log.Debug(&quot;Handling {0}&quot;, message.Id);
        MessageBus.Send(&quot;sql://nginn/MQ_PT2&quot;, new TestMessage1Reply { RequestId = message.Id });
    }
}</pre>
<p>The only difference is that now we are sending a <code>TestMessage1Reply</code> message when receiving <code>TestMessage1</code>.</p>
<p><strong>8 receiving threads</strong></p>
<table>
<thead>
<tr>
<th>Run#</th>
<th>Test time (sec)</th>
<th>Messages received/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>109</td>
<td>917</td>
</tr>
<tr>
<td>2</td>
<td>108</td>
<td>925</td>
</tr>
<tr>
<td>3</td>
<td>104</td>
<td>961</td>
</tr>
</tbody>
</table>
<p><strong>12 receiving threads</strong></p>
<table>
<thead>
<tr>
<th>Run#</th>
<th>Test time (sec)</th>
<th>Messages received/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>110</td>
<td>909</td>
</tr>
<tr>
<td>2</td>
<td>99</td>
<td>1010</td>
</tr>
<tr>
<td>3</td>
<td>98</td>
<td>1020</td>
</tr>
</tbody>
</table>
<p><strong>4 receiving threads</strong></p>
<table>
<thead>
<tr>
<th>Run#</th>
<th>Test time (sec)</th>
<th>Messages received/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>115</td>
<td>869</td>
</tr>
<tr>
<td>2</td>
<td>111</td>
<td>900</td>
</tr>
<tr>
<td>3</td>
<td>119</td>
<td>840</td>
</tr>
</tbody>
</table>
<p><strong>1 receiving thread</strong></p>
<table>
<thead>
<tr>
<th>Run#</th>
<th>Test time (sec)</th>
<th>Messages received/sec</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>295</td>
<td>338</td>
</tr>
</tbody>
</table>
<h2 id="488_conclusions.2C_further_optimization">Conclusions, further optimization <a class="heading-link" href="http://nginn.org/blog/?p=488#conclusions.2C_further_optimization" title="Link to this section">¶</a></h2>
<p>These performance numbers very good considering the hardware used for testing. They show that nginn-messagebus performance should be more than enough for most OLTP applications and that it could be significantly improved with proper hardware setup.<br />
Monitoring the machine resource utilization during tests showed that the main limiting factor was the hard disk write performance. SQL server could perform better if it could write to disk faster &#8211; in all tests the disk average disk write queue was between 1 and 6. CPU utilization was at about 50% in most intensive testing.<br />
Summing up, the performance of nginn-messagebus depends almost exclusively on performance of the underlying SQL server database and can be improved with many SQL server optimization techniques. </p>
<h2 id="488_exclusions">Exclusions <a class="heading-link" href="http://nginn.org/blog/?p=488#exclusions" title="Link to this section">¶</a></h2>
<p>All these tests were performed with local queues (stored in a local, directly accessible database). If we were sending messages to a remote database (with store &#038; forward in a local db) the performance would be much worse because currently NGinn-messagebus is not very effective in transporting messages between databases. This limitation stems from the fact that nginn-messagebus does not use batching when moving messages to a remote destination and sends each message in a separate transaction. This is probably the most important area to optimize in near future.</p>
]]></content:encoded>
			<wfw:commentRss>http://nginn.org/blog/?feed=rss2&#038;p=488</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Http in NGinn Messagebus &#8211; message gateway, servlets and Json services</title>
		<link>http://nginn.org/blog/?p=460&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=http-in-nginn-messagebus-message-gateway-servlets-and-json-services</link>
		<comments>http://nginn.org/blog/?p=460#comments</comments>
		<pubDate>Tue, 25 Oct 2011 19:43:08 +0000</pubDate>
		<dc:creator>RafalG</dc:creator>
				<category><![CDATA[EN]]></category>
		<category><![CDATA[http]]></category>
		<category><![CDATA[json]]></category>
		<category><![CDATA[messagebus]]></category>
		<category><![CDATA[rpc]]></category>

		<guid isPermaLink="false">http://nginn.org/blog/?p=460</guid>
		<description><![CDATA[Introduction to http functionalities of NGinn messagebus &#8211; http message transport, json-rpc and http interface extensions. What&#8217;s it for ¶ NGInn messagebus can be configured to send messages between endpoints using http. It&#8217;s not the most efficient message transport method &#8230; <a href="http://nginn.org/blog/?p=460">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2011-10-26 21:23:37 -->Introduction to http functionalities of NGinn messagebus &#8211; http message transport, json-rpc and http interface extensions.<br />
<span id="more-460"></span> </p>
<h3 id="460_what.27s_it_for">What&#8217;s it for <a class="heading-link" href="http://nginn.org/blog/?p=460#what.27s_it_for" title="Link to this section">¶</a></h3>
<p>NGInn messagebus can be configured to send messages between endpoints using http. It&#8217;s not the most efficient message transport method (performance similar to web service calls) but it allows you to send messags across the network when the destination database is not directly accessible. This function is called &#8216;http message gateway&#8217; and in order to use it you have to enable the http listener in NGinn Messagebus configuration.</p>
<h3 id="460_configuration">Configuration <a class="heading-link" href="http://nginn.org/blog/?p=460#configuration" title="Link to this section">¶</a></h3>
<p>The following configuration code will enable embedded http server</p>
<pre class="code">var ct = MessageBusConfigurator.Begin()
    .SetConnectionStrings(dbConnectionStrings)
    .SetEndpoint(endpointName)
    (...)
    .ConfigureHttpReceiver(&quot;http://MyMachine:8090/&quot;)
    (...)
    .FinishConfiguration();</pre>
<p>The <code>ConfigureHttpReceiver</code> call tells NGinn-mesagebus to listen on port 8090 on local IP associated with MyMachine name. If you need to listen on all IP addresses of the machine you should specify <code>http://+:8090/</code> as the listener address.</p>
<h3 id="460_using_the_http_gateway">Using the http gateway <a class="heading-link" href="http://nginn.org/blog/?p=460#using_the_http_gateway" title="Link to this section">¶</a></h3>
<p>Sending messages to remote endpoints with http is as easy as specifying http address as the endpoint name &#8211; like that:</p>
<pre class="code">IMessageBus bus (...);
bus.Send(&quot;http://YourMachine:9080/&quot;, new TestMessage { Id = &quot;AB9932&quot; });</pre>
<p>If you are sending messages with http you should configure the http listener at your endpoint because any replies to your messages will be sent back also with http.<br />
NGinn-messagebus implements store &#038; forward for all outgoing messages so even if the remote http endpoint is not accessible the <code>Send</code> will succeed and the message will sit in the local database until the receiver becomes available.</p>
<h3 id="460_monitoring_and_remote_control">Monitoring and remote control <a class="heading-link" href="http://nginn.org/blog/?p=460#monitoring_and_remote_control" title="Link to this section">¶</a></h3>
<p>Since we already have the http server it can be used for many other tasks. One of such tasks is monitoring the health of the service.<br />
If you navigate to <code>http://localhost:8090/health/</code> you will see the information about current status of message bus (and othere services, if present) and you can use this address with automatic monitoring tools like Nagios.<br />
And if you open <code>http://localhost:8090/businfo</code> you will see a simple page with information about current configuration and with an option to pause message processing. There is also a performance statistics view that allows you to collect performance data, but it will be described in another post.</p>
<h3 id="460_json_rpc">Json RPC <a class="heading-link" href="http://nginn.org/blog/?p=460#json_rpc" title="Link to this section">¶</a></h3>
<p>NGinn-messagebus provides a synchronous Json-based RPC mechanism that allows you to call services remotely. As everything in this project it&#8217;s based on concept of messages and their handlers.<br />
First &#8211; the message. It defines the service contract:</p>
<pre class="code">    public class TestMessage1
    {
        public int Id { get; set; }
    }</pre>
<p>Second &#8211; service message handler. You have to implement IMessageHandlerService interface:</p>
<pre class="code">    public class TestService : IMessageHandlerService&lt;TestMessage1&gt;
    {
        public object Handle(TestMessage1 message)
        {
            if (message.Id == 100) throw new Exception(&quot;hundred&quot;);
            return new TestMessage1 { Id = message.Id + 1 };
        }
    }</pre>
<p>And that&#8217;s it, we have defined a service that handles <code>TestMessage1</code> &#8211; it&#8217;s very similar to defining message handlers, the only difference is that a service can return a value. We don&#8217;t define a contract for the return value &#8211; the caller is responsible for specifying the expected return type, as we&#8217;ll see further.<br />
Before the service can be called you have to register it in the NGinn messagebus container &#8211; for example like that:</p>
<pre class="code">var cfg = MessageBusConfigurator.Begin()
    .RegisterHttpMessageServicesFromAssembly(typeof(Program).Assembly)
(...)</pre>
<p>Calling the services.<br />
Service can be called by sending HTTP POST with a Json message in the body to service handler URL:<br />
<code>http://localhost:9080/call/TestMessage1</code>. Or we can use a helper class from the NGinn.Messagebus namespace:</p>
<pre class="code">ServiceClient sc = new ServiceClient();
sc.BaseUrl = &quot;http://localhost:9080/call/&quot;;
var m1 = sc.CallService&lt;TestMessage1&gt;(new TestMessage1 { Id = 99 });
var m2 = sc.CallService&lt;TestMessage1&gt;(new TestMessage1 { Id = 100 });</pre>
<p>This code calls the TestMessage1 service twice. The generic parameter to <code>ServiceClient.CallService</code> method is the expected return value type. It&#8217;s used for deserializing the Json response.</p>
<h3 id="460_other_uses">Other uses <a class="heading-link" href="http://nginn.org/blog/?p=460#other_uses" title="Link to this section">¶</a></h3>
<p>You are free to add your own &#8216;servlets&#8217; to NGinn messagebus, you have just to inherit from the <code>ServletBase</code> class:</p>
<pre class="code">[UrlPattern(@&quot;^/hello/&quot;)]
public class HelloWorldServlet : ServletBase
{
    public override void HandleRequest(IRequestContext ctx)
    {
        ctx.Output.WriteLine(&quot;Hello, world&quot;);
    }
}</pre>
<p>This servlet will respond to <code>http://localhost:9080/hello/</code> requests.<br />
You also need to register your servlet during NGinn messagebus configuration:</p>
<pre class="code">MessageBusConfigurator.Begin()
                .SetConnectionStrings(dbConnectionStrings)
                .SetEndpoint(endpointName)
                .RegisterHttpHandlersFromAssembly(typeof(Program).Assembly)
(...)</pre>
<p><code>RegisterHttpHandlersFromAssembly</code> registers all servlet types that have an <code>UrlPattern</code> attribute.</p>
]]></content:encoded>
			<wfw:commentRss>http://nginn.org/blog/?feed=rss2&#038;p=460</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Sagas in NGinn MessageBus</title>
		<link>http://nginn.org/blog/?p=340&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=sagas-in-nginn-messagebus</link>
		<comments>http://nginn.org/blog/?p=340#comments</comments>
		<pubDate>Mon, 24 Oct 2011 19:16:10 +0000</pubDate>
		<dc:creator>RafalG</dc:creator>
				<category><![CDATA[EN]]></category>
		<category><![CDATA[messagebus]]></category>
		<category><![CDATA[saga]]></category>

		<guid isPermaLink="false">http://nginn.org/blog/?p=340</guid>
		<description><![CDATA[There&#8217;s quite a new feature in NGinn-messagebus: support for Sagas. Every other message bus implementation for .Net had it so time has come to add it also to nginn-messagebus. Please read on if you want to know what are sagas &#8230; <a href="http://nginn.org/blog/?p=340">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2011-10-24 21:38:43 -->There&#8217;s quite a new feature in NGinn-messagebus: support for Sagas. Every other message bus implementation for .Net had it so time has come to add it also to nginn-messagebus. Please read on if you want to know what are sagas and how to use them.<br />
<span id="more-340"></span></p>
<h3 id="340_what_are_sagas">What are sagas <a class="heading-link" href="http://nginn.org/blog/?p=340#what_are_sagas" title="Link to this section">¶</a></h3>
<p>Saga is a piece of data that represents current state of some long-running process, a process that reacts to incoming messages. Sagas in nginn-messagebus are initiated by a message and then can process other incoming messages. Each saga is a distinct instance of a process and therefore handles only messages that are sent to that instance &#8211; nginn-messagebus makes sure saga messages are delivered to proper saga instances. Sagas are persistent and transactional.</p>
<h3 id="340_but_why_are_they_a_part_of_the_message_bus.3F">But why are they a part of the message bus? <a class="heading-link" href="http://nginn.org/blog/?p=340#but_why_are_they_a_part_of_the_message_bus.3F" title="Link to this section">¶</a></h3>
<p>Just for your convenience. Long running processes and async messaging quite often go together. Sagas make it easy to implement such processes so you don&#8217;t have to implement process state persistence, message correlation, concurrency, versioning and so on.</p>
<h3 id="340_example_use_of_a_saga_-_sending_sms_messages">Example use of a saga &#8211; sending SMS messages <a class="heading-link" href="http://nginn.org/blog/?p=340#example_use_of_a_saga_-_sending_sms_messages" title="Link to this section">¶</a></h3>
<p>Let&#8217;s take a real world example of a process that can be implemented using a saga: Our task is to create a service for sending SMS messages to customers. After the message is sent our service should also collect a delivery report from the SMS gateway and send a status update to the application that has sent the SMS. If no delivery report is received in 3 days we should inform the application that the SMS has not been delivered.</p>
<p>Sending an SMS in our example is a long running process because after sending the message to the SMS gateway we need to wait for the delivery report for that message. The wait time can be quite long &#8211; up to 3 days &#8211; so the process is certainly a long-running one.</p>
<h3 id="340_implementation">Implementation <a class="heading-link" href="http://nginn.org/blog/?p=340#implementation" title="Link to this section">¶</a></h3>
<p>Basically, our SMS service sits between an application and the SMS gateway and acts as an intermediary in communication between the application and the SMS gateway. The &#8216;value added&#8217; by our service is handling of message delivery reports and a reliable API for sending SMS messages.</p>
<p>In our process of sending an SMS we&#8217;ll have to handle the following events:</p>
<ol>
<li class="first-item">Application sends an SMS (this initiates the process)</li>
<li>SMS service sends an SMS to the SMS gateway</li>
<li>SMS gateway sends us a delivery report</li>
<li>We (SMS service) send the delivery report to the application</li>
<li class="last-item">
<p>Delivery time-out occurs (no delivery report received)</p>
</li>
</ol>
<p>Each of these events will be represented by a message. Disclaimer: we wont&#8217;t go into details of how the communication with the SMS gateway is implemented &#8211; let&#8217;s just assume that proper messages are published to the messagebus by some component responsible for communication and that&#8217;s all.</p>
<p>So, let&#8217;s start with defining our messages:</p>
<pre class="code">/// &lt;summary&gt;
/// Application's request to send an SMS
/// &lt;/summary&gt;
public class SendSMSRequest
{
    public string MSISDN { get; set; }
    public string Text { get; set; }
    public string MessageId { get; set; }
}

/// &lt;summary&gt;
/// SMS delivery report for the application
/// &lt;/summary&gt;
public class SMSDeliveryReport
{
    public bool Delivered { get; set; }
    public string Reason { get; set; }
    public string MessageId { get; set; }
}

/// &lt;summary&gt;
/// Send a SMS to the SMS gateway
/// &lt;/summary&gt;
public class SendSMSToGateway
{
    public string MSISDN { get; set; }
    public string Text { get; set; }
    public string SMSId { get; set; }
}

/// &lt;summary&gt;
/// SMS gateway's delivery status message
/// &lt;/summary&gt;
public class GatewayDeliveryReport
{
    public bool Success { get; set; }
    public string SMSId { get; set; }
}

/// &lt;summary&gt;
/// Message for handling delivery report timeout
/// &lt;/summary&gt;
public class SMSDeliveryTimeout
{
    public string MessageId { get; set; }
}</pre>
<p>Now we&#8217;ll implement a saga that orchestrates all these messages. This is a saga class that doesn&#8217;t yet handle any messages but holds some state (a SmsState? object):</p>
<pre class="code">public class SmsSaga : Saga&lt;SmsSaga.SmsState&gt;
{
    public class SmsState
    {
        public DateTime MessageSentDate { get; set; }
    }
}</pre>
<p>Now we&#8217;ll add message handlers to it. Let&#8217;s start with the SendSMSRequest message that initiates the whole process:</p>
<pre class="code">public class SmsSaga : Saga&lt;SmsSaga.SmsState&gt;, InitiatedBy&lt;SendSMSRequest&gt;
{
    public class SmsState
    {
        public DateTime MessageSentDate { get; set; }
        public bool DeliveryReportReceived { get; set; }
    }

    public IMessageBus MessageBus { get; set; }

    protected override void Configure()
    {
        //tell the message bus that saga ID will be passed in the MessageId field fo SendSMSRequest message
        SagaId&lt;SendSMSRequest&gt;(x =&gt; x.MessageId);
    }

    public void Handle(SendSMSRequest message)
    {
        //update saga state
        Data.MessageSentDate = DateTime.Now;
        Data.DeliveryReportReceived = false;

        //send a request to the SMS gateway
        MessageBus.NewMessage(new SendSMSToGateway { MSISDN = message.MSISDN, SMSId = message.MessageId, Text = message.Text })
            .Send(&quot;sql://gateway/Queue&quot;);

        //and schedule a timeout message to be delivered in 3 days from now
        MessageBus.NewMessage(new SMSDeliveryTimeout { MessageId = message.MessageId })
            .SetDeliveryDate(DateTime.Now.AddDays(3))
            .Publish();

    }
}</pre>
<p>Lot of things are happening here. First of all, we implemented the InitiatedBy<SendSmsRequest> interface that adds the Handle(SendSMSRequest) method. This interface informs message bus that it should create a new instance of SmsSaga when a SendSMSRequest message arrives. Apart from that, we have implemented a Configure method. This method&#8217;s purpose is to define how messages handled by the saga should be used for identifying the saga instance. In our case we told message bus that the saga ID is in SendSMSRequest.MessageId field. Now we only have to take care that the MessageId is unique.</p>
<p>Now let&#8217;s take a look what SmsSaga is doing after receiving the SendSMSRequest. First, we update the saga state (in the Data property). Then we send a request to the SMS gateway (the SendSMSToGateway message). And finally, we publish the SMSDeliveryTimeout message to our local message queue and schedule it for delivery 3 days from now. That&#8217;s all &#8211; now we are waiting for the delivery report from the SMS gateway or the timeout &#8211; whichever occurs first. So, let&#8217;s add the implementation of these two cases:</p>
<pre class="code">public class SmsSaga : Saga&lt;SmsSaga.SmsState&gt;,
    InitiatedBy&lt;SendSMSRequest&gt;,
    IHandleSagaMessage&lt;GatewayDeliveryReport&gt;,
    IHandleSagaMessage&lt;SMSDeliveryTimeout&gt;
{
    public class SmsState
    {
        public DateTime MessageSentDate { get; set; }
        public bool DeliveryReportReceived { get; set; }
        public string SenderEndpoint { get; set; }
    }

    public IMessageBus MessageBus { get; set; }

    protected override void Configure()
    {
        //tell the message bus that saga ID will be passed in the MessageId field of SendSMSRequest message
        SagaId&lt;SendSMSRequest&gt;(x =&gt; x.MessageId);
        SagaId&lt;GatewayDeliveryReport&gt;(x =&gt; x.SMSId);
        SagaId&lt;SMSDeliveryTimeout&gt;(x =&gt; x.MessageId);
    }

    public void Handle(SendSMSRequest message)
    {
        //update saga state
        Data.MessageSentDate = DateTime.Now;
        Data.DeliveryReportReceived = false;
        Data.SenderEndpoint = MessageBus.CurrentMessageInfo.Sender; //store the sender's address for later use

        //send a request to the SMS gateway
        MessageBus.NewMessage(new SendSMSToGateway { MSISDN = message.MSISDN, SMSId = message.MessageId, Text = message.Text })
            .Send(&quot;sql://gateway/Queue&quot;);

        //and schedule a timeout message to be delivered in 3 days from now
        MessageBus.NewMessage(new SMSDeliveryTimeout { MessageId = message.MessageId })
            .SetDeliveryDate(DateTime.Now.AddDays(3))
            .Publish();

    }

    public void Handle(GatewayDeliveryReport message)
    {
        if (!Data.DeliveryReportReceived)
        {
            Data.DeliveryReportReceived = true;
            //send the report to the application
            MessageBus.NewMessage(new SMSDeliveryReport { Delivered = message.Success, Reason = message.Success ? &quot;&quot; : &quot;Delivery failure&quot;, MessageId = Id })
                .Send(Data.SenderEndpoint);
        }
        //we could complete the saga here but let's wait for the timeout message
        //so it is processed without an error
    }

    public void Handle(SMSDeliveryTimeout message)
    {
        if (!Data.DeliveryReportReceived)
        {
            //inform the application about timeout
            MessageBus.NewMessage(new SMSDeliveryReport { Delivered = false, Reason = &quot;Timeout&quot;, MessageId = this.Id })
                .Send(Data.SenderEndpoint);
        }
        SetCompleted(); //mark the saga as completed so it can be removed from the db
    }
}</pre>
<p>Now the implementation is complete. We implemented two additional IHandleSagaMessage interfaces for GatewayDeliveryReport and SMSDeliveryTimeout messages. We also added saga &#8216;resolvers&#8217; for these messages in the Configure method. Our saga is complete after the SMSDeliveryTimeout message is received. The handler of that message calls SetCompleted at the end to inform message bus that the saga is completed and can be deleted from the database (an no further messages are expected). We could also complete the saga after receiving the GatewayDeliveryReport message but then the saga would be deleted before receiving SMSDeliveryTimeout message and there would be an error reported for that message.</p>
<p>And basically, that&#8217;s all you need to know to implement sagas with nginn-messagebus.</p>
<h3 id="340_saga_id_and_correlation">Saga Id and correlation <a class="heading-link" href="http://nginn.org/blog/?p=340#saga_id_and_correlation" title="Link to this section">¶</a></h3>
<p>As you have seen in the application above, the Id assigned to the saga was retrieved from the initiating SendSMSRequest message and then it was present in all other message used in this scenario. This was the common identifier for all messages in that particular process instance and in this particular case the saga Id was the same as the message Id assigned by the application. The benefit was that everyone was using the same identifier so no mapping had to be done.</p>
<p>Sometimes, however, you will not specify saga Id in the initiating message &#8211; in this case nginn-messagebus will generate new, unique saga Id on receiving the message and this Id will be then used for correlating all other messages in that saga. This means that if the initiating application needs to &#8216;talk to&#8217; the saga later it must know the saga&#8217;s Id. The id can be passed back in the reply to the initating message.</p>
<p>There&#8217;s one more way of correlating sagas and messages: NGinn-messagebus allows you to specify an additional identifier (&#8216;CorrelationId?&#8217;) for any message sent:</p>
<pre class="code">MessageBus.NewMessage(new SomeMessage())
    .SetCorrelationId(&quot;298128993932320&quot;)
    .Publish();</pre>
<p>If the message correlation id is specified and no other mappings have been defined in the saga&#8217;s Configure method, the message correlation Id will be used as the saga Id. It will also become the saga Id if specified for the initiating message.</p>
<h3 id="340_sagas_and_transactions">Sagas and transactions <a class="heading-link" href="http://nginn.org/blog/?p=340#sagas_and_transactions" title="Link to this section">¶</a></h3>
<p>Sagas are updated as a result of receiving a saga message and therefore all modifications are a part of the message receiving transaction. There&#8217;s one great thing about nginn-messagebus and sagas: if the saga state is kept in the same database as the message queues (the default setup) your saga handling code will not require a distributed transaction and this means a great performance.</p>
]]></content:encoded>
			<wfw:commentRss>http://nginn.org/blog/?feed=rss2&#038;p=340</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Publishing messages directly from SQL server</title>
		<link>http://nginn.org/blog/?p=376&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=publishing-messages-directly-from-sql-server</link>
		<comments>http://nginn.org/blog/?p=376#comments</comments>
		<pubDate>Mon, 24 Oct 2011 14:58:23 +0000</pubDate>
		<dc:creator>RafalG</dc:creator>
				<category><![CDATA[EN]]></category>
		<category><![CDATA[messagebus]]></category>
		<category><![CDATA[SQL]]></category>

		<guid isPermaLink="false">http://nginn.org/blog/?p=376</guid>
		<description><![CDATA[Do you know what is the simplest (and fastest BTW) way to send a message from SQL server using nginn-messagebus? Just insert your message to nginn-messagebus queue and nginn-messagebus will pick it up from there. Simple, isn&#8217;t it? And what &#8230; <a href="http://nginn.org/blog/?p=376">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p><!-- Cached "rss-item" item from 2011-10-25 06:53:36 -->Do you know what is the simplest (and fastest BTW) way to send a message from SQL server using nginn-messagebus? Just insert your message to nginn-messagebus queue and nginn-messagebus will pick it up from there. Simple, isn&#8217;t it?<br />
And what is it useful for? Well, it could be used to notify an application that some data in the database has been modified.<br />
<span id="more-376"></span><br />
To implement such function we will use an update trigger:</p>
<pre class="code">CREATE TRIGGER On_Document_Update
   ON  Documents
   AFTER INSERT, UPDATE
AS
BEGIN
	INSERT INTO MQ_FeedNotify([from_endpoint]
           ,[to_endpoint]
           ,[subqueue]
           ,[insert_time]
           ,[retry_count]
           ,[retry_time]
           ,[msg_text])
    select
		'sql://db/MQ_FeedNotify',
		'sql://db/MQ_FeedNotify',
        'I',
        getdate(),
        0,
        getdate(),
        '{&quot;$type&quot;:&quot;MyApplication.DocumentUpdated,MyApplication&quot;, &quot;DocumentId&quot; : &quot;' + convert(varchar, Id) + '&quot; }'
	from Inserted
END
GO</pre>
<p>This piece of SQL makes sure that every time a record is updated or added to Documents table our application will be notified with a message published to MQ_FeedNotify table.<br />
It&#8217;s a very simple and elegant way (IMHO) to deliver notifications from SQL to a .Net application and it&#8217;s also very effective one &#8211; especially when you are handling batch updates. And you don&#8217;t have to worry about transactions or interfacing the outside world from sql server &#8211; everything is provided by SQL server and nginn-messagebus.</p>
<p>You are not limited to using triggers of course, message sending logic can be placed in a stored procedure or a plain sql statement. But SQL offers triggers for almost everything so it&#8217;s a natural way to detect some events and notify the outside world about them. And some triggers provide quite interesting information &#8211; like the Logon triggers in SQL Server 2008 that could be used for detecting database access. </p>
<p>Of course there are other ways of sending messages to a queue from SQL. You could implement your own queue table and C# code that reads from it, but nginn-messagebus does it already and has been verified in production. You could also send messages with SQL Message Broker &#8211; this is a message queuing mechanism built into SQL server. I don&#8217;t know it well enough to compare it to nginn-messagebus but with SMB you would also have to implement some C# code that delivers received messages to the application so again &#8211; consider using nginn-messagebus. Other options? Well, you could use some tricks like calling external scripts from SQL code or even embedding CLR code into SQL, but these look like dirty hacks compared to methods discussed above.</p>
]]></content:encoded>
			<wfw:commentRss>http://nginn.org/blog/?feed=rss2&#038;p=376</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
		<item>
		<title>NGinn MessageBus is public</title>
		<link>http://nginn.org/blog/?p=254&#038;utm_source=rss&#038;utm_medium=rss&#038;utm_campaign=nginn-messagebus-is-public</link>
		<comments>http://nginn.org/blog/?p=254#comments</comments>
		<pubDate>Tue, 02 Mar 2010 14:29:09 +0000</pubDate>
		<dc:creator>RafalG</dc:creator>
				<category><![CDATA[EN]]></category>

		<guid isPermaLink="false">http://nginn.vipserv.org/blog_nginn/?p=254</guid>
		<description><![CDATA[Few days ago I have open-sourced the NGinn-MessageBus project at http://code.google.com/p/nginn-messagebus/. NGinn MessageBus is an implementation of so called &#8216;Service Bus&#8217;, that is a message-oriented, asynchronous communication framework for distributed applications. I have implemented NGinn MessageBus as the infrastructure for &#8230; <a href="http://nginn.org/blog/?p=254">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
			<content:encoded><![CDATA[<p>Few days ago I have open-sourced the NGinn-MessageBus project at <a href="http://code.google.com/p/nginn-messagebus/">http://code.google.com/p/nginn-messagebus/</a>. NGinn MessageBus is an implementation of so called &#8216;Service Bus&#8217;, that is a message-oriented, asynchronous communication framework for distributed applications. I have implemented NGinn MessageBus as the infrastructure for the NGinn BPM project, but since it has evolved into quite independent component I decided to publish it as a separate project. NGinn MessageBus has functionality similar to other open-source service buses for .Net (like NServiceBus, MassTransit or Rhino ServiceBus) but is smaller and simpler and, what is most important, uses SQL Server for storing message queues.</p>
<p>NGinn MessageBus provides publish-subscribe message distribution and supports transactional and durable messages only (as for now, because it&#8217;s still in development). All messages and subscriber information is persisted in SQL database and no other message transport mechanism is used. A message queue in NGinn MessageBus is simply a database table where messages are written and read in FIFO (more or less) manner. You might wonder why I decided to use SQL instead of well known messaging implementations like MSMQ, and here are the reasons:</p>
<ul>
<li>All application data in single database. As NGinn.BPM stores process state in SQL database it made a perfect sense to have all other data, including queued messages, in the same database. It simplifies maintaninance, backups and other management tasks.</li>
<li>NGinn MessageBus provides &#8216;scheduled message&#8217; functionality allowing you to schedule a message to be delivered at specified moment in future. This function is heavily used by NGinn BPM and there are lots of scheduled messages sitting in database and waiting to be delivered. It&#8217;s easy to handle this in a random-access database and very difficult to do it when you have a FIFO queue with sequential access only.</li>
<li>The performance is good, in some situations much better than what I was able to get with MSMQ. For example, sending messages in a distributed transaction is faster in NGinn MessageBus than in MSMQ. NGinn BPM uses distributed transactions everywhere so this was important.</li>
</ul>
<p>NGinn MessageBus is built around the concept of an Endpoint. Endpoint is an address to where messages can be delivered or from where they can be sent. Endpoint corresponds to a single message queue, with the same name (actually, the queue name is the endpoint). Usually you have one endpoint per process and in case of distributed applications each process has its own endpoint, and hence its own queue. If you have a single process you are using NGinn Message Bus in a &#8216;local&#8217; mode, where messages are sent and received in the same queue. To extend it to distributed mode you have to set up several endpoints and provide message distribution rules by subscribing. One endpoint can subscribe at another endpoint for messages of particular type. After subscription is done all messages published at the publisher endpoint will be delivered to that endpoint locally and to all endpoints that have subscribed for particular message type.</p>
<p>NGinn Message Bus is built in a decentralized architecture &#8211; there is no central message router component, each pair of endpoints can communicate directly independent of any other endpoints.</p>
<p>From the application perspective you access NGinn MessageBus through the IMessageBus interface that provides functions for sending messages and also manages the process of receiving incoming messages and dispatching them to their handlers. NGinn Message Bus uses an IOC container to resolve message handlers so you have to register your message handling components in the container. Currently NGinn MessageBus project provides a configuration tool to set it up with the Castle Windsor container, but it&#8217;s possible to use other containers as well.</p>
<h2>Some code examples</h2>
<p>First of all, let&#8217;s see how to configure NGinn Message Bus with the Castle Windsor container. The source code contains a test project with very similar example:</p>
<p>&nbsp;</p>
<pre class="brush: csharp; gutter: true">Dictionary connStrings = new Dictionary();
connStrings["testdb1"] = "Data Source=(local);Initial Catalog=NGinn;User Id=nguser;Password=PASS";
connStrings["testdb2"] = "Data Source=(local);Initial Catalog=NGinn;User Id=nguser;Password=PASS";
IWindsorContainer wc1 = ConfigureMessageBus("sql://testdb1/MQueue1", connStrings);
IWindsorContainer wc2 = ConfigureMessageBus("sql://testdb2/MQueue2", connStrings);

IMessageBus mb1 = wc1.Resolve();
mb1.SubscribeAt("sql://testdb2/MQueue2", typeof(TestMessage1));

IMessageBus mb2 = wc2.Resolve();</pre>
<p>The code above configures two instances of message bus component, for two different endpoints. Note that in order to configure a message bus endpoint we must specify the endpoint name in the form of sql://[connection alias]/[table name] and give the list of connection string aliases. Here we have two connection string aliases (testdb1 and testdb2), both pointing to the same database. So in the database we will have two message queue tables created, named MQueue1 and MQueue2 (NGinn MessageBus will create them automatically if the credentials provided in connection string allow for table creation).<br />
There is also a call to mb1.SubscribeAt(&#8220;endpoint&#8221;, Message type) that tells message bus 1 (represented by sql://testdb1/MQueue1) to subscribe at endpoint sql://testdb2/MQueue2 to all messages of type TestMessage1.</p>
<p>And here is the &#8216;ConfigureMessageBus&#8217; method code that performs actual configuration:</p>
<pre class="brush: csharp; gutter: true">static IWindsorContainer ConfigureMessageBus(string endpointName, IDictionary dbConnectionStrings)
{
IWindsorContainer wc = Configure.Begin()
.SetConnectionStrings(dbConnectionStrings)
.SetEndpoint(endpointName)
.UseSqlSubscriptions()
.AddMessageHandler(typeof(TestHandler))
.BuildContainer();
return wc;

}</pre>
<p>Now, after we have configured the message bus here is how to send some messages:</p>
<pre class="brush: csharp; gutter: true">
IMessageBus mb2 = wc2.Resolve();

using (System.Transactions.TransactionScope ts = new System.Transactions.TransactionScope())
{
for (int i = 0; i &lt; 10; i++)
{
mb2.NewMessage(new TestMessage1("M" + i))
.SetDeliveryDate(DateTime.Now.AddSeconds(1 + i))
.SetLabel("Test XX" + i)
.Publish();
}
ts.Complete();
}</pre>
<p>We open a transaction and then publish 10 messages. For each message we specify the delivery date (optional) and label (also optional). Messages are published to local endpoint, then they will be distributed according to currently configured subscriptions.</p>
<p>Finally, some code showing how to set up a message handler. Please take look above at the ConfigureMessageBus snippet. You&#8217;ll notice the line</p>
<p>.AddMessageHandler(typeof(TestHandler))</p>
<p>which registers a message handler component. This component looks like this:</p>
<pre class="brush: csharp; gutter: true">public class TestHandler : IMessageConsumer {
private Logger log;

public TestHandler()
{
log = LogManager.GetLogger("TestHandler_" + this.GetHashCode());
}
#region IMessageConsumer Members

public void Handle(TestMessage1 message)
{
log.Info("TestMessage1 {0} ARRIVED", message.Id);
System.Threading.Thread.Sleep(1000);
}

#endregion</pre>
<p>As you can see, message handler has to implement IMessageConsumerinterface which defines the &#8216;Handle&#8217; method. Single component can implement the IMessageConsumer interface multiple times to be able to handle multiple types of messages.</p>
<p>And basically that&#8217;s it.</p>
]]></content:encoded>
			<wfw:commentRss>http://nginn.org/blog/?feed=rss2&#038;p=254</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>

