Skip to content

Instantly share code, notes, and snippets.

@santiaago
Created August 13, 2018 11:05
Show Gist options
  • Save santiaago/f01c46ab0104c3826ee86ec7236f14d4 to your computer and use it in GitHub Desktop.
Save santiaago/f01c46ab0104c3826ee86ec7236f14d4 to your computer and use it in GitHub Desktop.
Simple C# NATS example

Simple C# NATS example

  1. Run NATS
docker run -p 4444:4444 nats -p 4444
  1. Create Web Server
dotnet new webapi -n web
  1. Create Worker
dotnet new console -n worker
  1. Add NATS to both projects
dotnet add package NATS.Client --version 0.8.1
  1. Add ValuesController.cs to web project
  2. Add Program.cs to worker project
  3. Run Projects
  4. Run CURL command
curl --header "Content-Type: application/json" \
--request POST \
--data 'my value' \
http://localhost:5000/api/values
  1. Worker logs
worker listening...
worker listening...
worker received {Subject=worker;Reply=null;Payload=<hello, world: >}
worker listening...
worker listening...
  1. Server logs
Hosting environment: Production
Content root path: /yourpathto/web
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
api/values my value
using System;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using NATS.Client;
namespace worker
{
class Program
{
static void Main()
{
Console.WriteLine("Worker:");
ConnectionFactory cf = new ConnectionFactory();
Options opts = ConnectionFactory.GetDefaultOptions();
opts.Url = "nats://localhost:4444";
IConnection c = cf.CreateConnection(opts);
EventHandler<MsgHandlerEventArgs> h = (sender, args) =>
{
Console.WriteLine($"worker received {args.Message}");
};
IAsyncSubscription s = c.SubscribeAsync("worker", h);
while (true)
{
Console.WriteLine("worker listening...");
Thread.Sleep(TimeSpan.FromSeconds(5));
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using NATS.Client;
namespace web.Controllers
{
[Route("api/[controller]")]
public class ValuesController : Controller
{
// POST api/values
[HttpPost]
public IActionResult Post([FromBody]string value)
{
Console.WriteLine($"api/snaphost {value}");
ConnectionFactory cf = new ConnectionFactory();
Options opts = ConnectionFactory.GetDefaultOptions();
opts.Url = "nats://localhost:4444";
IConnection c = cf.CreateConnection(opts);
c.Publish("worker", Encoding.UTF8.GetBytes($"hello, world: {value}"));
c.Close();
return Ok();
}
}
}
@benyaminl
Copy link

Is there any example to use publish and request? Thank you

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment