NATS Server and Elixir integration
NATS have many client libraries available. There is one for Elixir too, so lets make a little experiment.
To make a new Elixir project, we can use mix with simple command.
mix new nats_demo
cd nats_demo
Elixir has iex console available, so we can play online and see results instantly. That’s really great for experimenting. Let’s see how nats support fits here. To use NATS in Elixir we can use Gnat library, which is quite mature. To use it, we can add {:gnat, “1.2.1”} dependency into mix.exs. Finally, run mix deps.get
from console and dependency is loaded.
To run an interactive console we call:
iex --werl -S mix
A window with elixir console is opened, and we can use Gnat library immediately. So let’s do it. Following commands below provide:
- connection to server and store connection PID into gnat variable
- then we can make subscription to desired queue. Messages coming for this subscription are being sent into self() process mailbox.
- to see messages coming from subscription simply call flush command. This way all messages from mailbox are listed and mailbox is cleared.
- now we can unsubscribe
{:ok, gnat} = Gnat.start_link(%{host: '127.0.0.1', port: 4222})
{:ok, subscription} = Gnat.sub(gnat, self(), "prices.*")
flush
Gnat.unsub(gnat, subscription)
It’s quite easy, and we can experiment interactively with other Gnat APIs by following https://github.com/nats-io/nats.ex