OCaml client for the NATS messaging system.
Warning
In active development! You can view the progress here.
Basics
- CONNECT
- INFO
- PUB
- HPUB
- HMSG
- SUB/UNSUB
- MSG
- PING/PONG
- OK/ERR
Features
- Drain mechanism
- Request mechanism
The project provides several packages with different implementations for any contexts.
Package | Description | Require OCaml |
---|---|---|
nats-client |
implementation independent protocol abstracts | >= 4.14 (LTS) |
nats-client-lwt |
lwt.unix -based client implementation |
Currently only a development version is available. You can pin it using the OPAM package manager.
$ opam pin nats-client-lwt.dev https://github.com/romanchechyotkin/nats.ocaml.git
This example shows how to publish to a subject and handle its messages.
open Lwt.Infix
let main =
(* Create a switch for automatic dispose resources. *)
Lwt_switch.with_switch @@ fun switch ->
(* Connect to a NATS server by address 127.0.0.1:4222 with ECHO flag. *)
let%lwt client =
Nats_client_lwt.connect ~switch ~settings:[ `Echo ]
(Uri.of_string "nats://127.0.0.1:4222")
in
(* Publish 'hello' message to greet.joe subject. *)
Nats_client_lwt.pub client ~subject:"greet.joe" "hello";%lwt
(* Subscribe to greet.* subject. *)
let%lwt subscription =
Nats_client_lwt.sub ~switch client ~subject:"greet.*" ()
in
(* Publishes 'hello' message to three subjects. *)
Lwt_list.iter_s
(fun subject -> Nats_client_lwt.pub client ~subject "hello")
[ "greet.sue"; "greet.bob"; "greet.pam" ];%lwt
(* Handle first three incoming messages to the greet.* subject. *)
Lwt_stream.nget 3 subscription.messages
>>= Lwt_list.iter_s (fun (message : Nats_client.Protocol.msg) ->
Lwt_io.printlf "'%s' received on %s" message.payload.contents
message.subject)
let () = Lwt_main.run main
Take it from examples/natsbyexample/publish_subscribe.ml
.
$ docker start -a nats-server
$ dune exec ./examples/natsbyexample/publish_subscribe.exe
'hello' received on greet.sue
'hello' received on greet.bob
'hello' received on greet.pam
See more examples at examples/
directory.
Messaging
- Core Publish-Subscribe
- Request-Reply
- JSON for Message Payloads
- Protobuf for Message Payloads
- Concurrent Message Processing
- Iterating Over Multiple Subscriptions
The is an open source project under the Apache 2.0 license. Contributions are very welcome! Let's build a great ecosystem together! Please be sure to read the CONTRIBUTING.md before your first commit.