我正在尝试学习如何使用Disruptor.NET消息框架,但我找不到任何实际的例子。有很多文章都有关于它是如何工作的图片,但我找不到任何实际的内容,并向您展示如何实现这些方法。会是什么样的例子?
答案 0 :(得分:29)
我为Disruptor-net找不到一个可行的'Hello World'感到沮丧,我一直在努力,直到我找到一个工作 - 见下文。希望它是相当不言自明的。 Console.WriteLine
行很容易看到事情的运作方式 - 例如,RingBuffer在启动时创建每个条目实例(这是有意义的)。
希望这有助于任何在.NET上寻求Disruptor帮助的人。
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Disruptor;
using Disruptor.Dsl;
namespace DisruptorTest
{
public sealed class ValueEntry
{
public long Value { get; set; }
public ValueEntry()
{
Console.WriteLine("New ValueEntry created");
}
}
public class ValueAdditionHandler : IEventHandler<ValueEntry>
{
public void OnNext(ValueEntry data, long sequence, bool endOfBatch)
{
Console.WriteLine("Event handled: Value = {0} (processed event {1}", data.Value, sequence);
}
}
class Program
{
private static readonly Random _random = new Random();
private static readonly int _ringSize = 16; // Must be multiple of 2
static void Main(string[] args)
{
var disruptor = new Disruptor.Dsl.Disruptor<ValueEntry>(() => new ValueEntry(), _ringSize, TaskScheduler.Default);
disruptor.HandleEventsWith(new ValueAdditionHandler());
var ringBuffer = disruptor.Start();
while (true)
{
long sequenceNo = ringBuffer.Next();
ValueEntry entry = ringBuffer[sequenceNo];
entry.Value = _random.Next();
ringBuffer.Publish(sequenceNo);
Console.WriteLine("Published entry {0}, value {1}", sequenceNo, entry.Value);
Thread.Sleep(250);
}
}
}
}
答案 1 :(得分:3)
有关Disruptor模式的详细博客文章, The Latency Issue 。它演示了如何开始并详细使用Disruptor。