Last active
October 18, 2016 19:59
-
-
Save danielwertheim/0bac13e1dd8a05588506153bfaf59bcd to your computer and use it in GitHub Desktop.
NATSConsumer
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
class Program { | |
static void Main(string[] args) | |
{ | |
const string subject = "test"; | |
var cnInfo = new ConnectionInfo(new Host("demo.nats.io")) { | |
AutoRespondToPing = true | |
}; | |
Action<MsgOp> handler = msg => { | |
Console.WriteLine("R:" + Encoding.UTF8.GetString(msg.Payload)); | |
}; | |
using (var client = new NatsClient("test", cnInfo)) | |
{ | |
using (var consumer = new NatsConsumer(client)) | |
{ | |
consumer.Subscribe(subject, handler); | |
client.Connect(); | |
while (true) | |
{ | |
Console.WriteLine("Send: "); | |
var message = Console.ReadLine(); | |
if (string.IsNullOrWhiteSpace(message)) | |
break; | |
client.Pub(subject, message); | |
} | |
} | |
client.Disconnect(); | |
} | |
} | |
} |
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
class Program { | |
static void Main(string[] args) | |
{ | |
var factory = new MessageRouteFactory(); | |
var routes = factory.Create( | |
typeof(Program).Assembly, | |
typeof(ICommandHandler<>)); | |
var router = new SequentialAsyncMessageRouter( | |
(handlerType, envelope) => Activator.CreateInstance(handlerType), | |
routes); | |
Action<MsgOp> handler = async msg => { | |
var tmp = JsonConvert.DeserializeObject(msg.GetPayloadAsString(), Type.GetType(msg.Subject)); | |
await router.RouteAsync(tmp); | |
}; | |
var cnInfo = new ConnectionInfo(new Host("192.168.2.20")) { | |
AutoRespondToPing = true, | |
Credentials = new Credentials("test", "p@ssword123"), | |
Verbose = true | |
}; | |
using (var client = new NatsClient("test", cnInfo)) | |
{ | |
client.Connect(); | |
using (var consumer = new NatsConsumer(client)) | |
{ | |
foreach (var ns in routes.Select(r => r.MessageType.Namespace).Distinct()) | |
consumer.Subscribe($"{ns}.>", handler); | |
while (true) | |
{ | |
Console.WriteLine("Student:"); | |
var student = Console.ReadLine(); | |
if (string.IsNullOrWhiteSpace(student)) | |
break; | |
Console.WriteLine("Course:"); | |
var course = Console.ReadLine(); | |
if (string.IsNullOrWhiteSpace(course)) | |
break; | |
var cmd = new RegisterStudent | |
{ | |
Student = student, | |
Course = course | |
}; | |
client.Pub(cmd.GetType().FullName, JsonConvert.SerializeObject(cmd)); | |
} | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment