Debian Codegraph @

micro/README.md

raw
1 # NATS micro [![GoDoc](https://pkg.go.dev/badge/github.com/nats-io/nats.go/micro.svg)](https://pkg.go.dev/github.com/nats-io/nats.go/micro)
2
3 - [Overview](#overview)
4 - [Basic usage](#basic-usage)
5 - [Endpoints and groups](#endpoints-and-groups)
6 - [Discovery and Monitoring](#discovery-and-monitoring)
7 - [Examples](#examples)
8 - [Documentation](#documentation)
9
10 ## Overview
11
12 The `micro` package in the NATS.go library provides a simple way to create
13 microservices that leverage NATS for scalability, load management and
14 observability.
15
16 ## Basic usage
17
18 To start using the `micro` package, import it in your application:
19
20 ```go
21 import "github.com/nats-io/nats.go/micro"
22 ```
23
24 The core of the `micro` package is the Service. A Service aggregates endpoints
25 for handling application logic. Services are named and versioned. You create a
26 Service using the `micro.AddService()` function, passing in the NATS connection
27 and Service configuration.
28
29 ```go
30 nc, _ := nats.Connect(nats.DefaultURL)
31
32 // request handler
33 echoHandler := func(req micro.Request) {
34 req.Respond(req.Data())
35 }
36
37 srv, err := micro.AddService(nc, micro.Config{
38 Name: "EchoService",
39 Version: "1.0.0",
40 // base handler
41 Endpoint: &micro.EndpointConfig{
42 Subject: "svc.echo",
43 Handler: micro.HandlerFunc(echoHandler),
44 },
45 })
46 ```
47
48 After creating the service, it can be accessed by publishing a request on
49 endpoint subject. For given configuration, run:
50
51 ```sh
52 nats req svc.echo "hello!"
53 ```
54
55 To get:
56
57 ```sh
58 17:37:32 Sending request on "svc.echo"
59 17:37:32 Received with rtt 365.875µs
60 hello!
61 ```
62
63 ## Endpoints and groups
64
65 Base endpoint can be optionally configured on a service, but it is also possible
66 to add more endpoints after the service is created.
67
68 ```go
69 srv, _ := micro.AddService(nc, config)
70
71 // endpoint will be registered under "svc.add" subject
72 err = srv.AddEndpoint("svc.add", micro.HandlerFunc(add))
73 ```
74
75 In the above example `svc.add` is an endpoint name and subject. It is possible
76 have a different endpoint name then the endpoint subject by using
77 `micro.WithEndpointSubject()` option in `AddEndpoint()`.
78
79 ```go
80 // endpoint will be registered under "svc.add" subject
81 err = srv.AddEndpoint("Adder", micro.HandlerFunc(echoHandler), micro.WithEndpointSubject("svc.add"))
82 ```
83
84 Endpoints can also be aggregated using groups. A group represents a common
85 subject prefix used by all endpoints associated with it.
86
87 ```go
88 srv, _ := micro.AddService(nc, config)
89
90 numbersGroup := srv.AddGroup("numbers")
91
92 // endpoint will be registered under "numbers.add" subject
93 _ = numbersGroup.AddEndpoint("add", micro.HandlerFunc(addHandler))
94 // endpoint will be registered under "numbers.multiply" subject
95 _ = numbersGroup.AddEndpoint("multiply", micro.HandlerFunc(multiplyHandler))
96 ```
97
98 ## Customizing queue groups
99
100 For each service, group and endpoint the queue group used to gather responses
101 can be customized or disabled. If not provided a default queue group will be
102 used (`q`). Customizing queue groups can be useful to e.g. implement fanout
103 request pattern or hedged request pattern (to reduce tail latencies by only
104 waiting for the first response for multiple service instances).
105
106 Let's say we have multiple services listening on the same subject, but with
107 different queue groups:
108
109 ```go
110 for i := 0; i < 5; i++ {
111 srv, _ := micro.AddService(nc, micro.Config{
112 Name: "EchoService",
113 Version: "1.0.0",
114 QueueGroup: fmt.Sprintf("q-%d", i),
115 // base handler
116 Endpoint: &micro.EndpointConfig{
117 Subject: "svc.echo",
118 Handler: micro.HandlerFunc(echoHandler),
119 },
120 })
121 }
122 ```
123
124 In the client, we can send request to `svc.echo` to receive responses from all
125 services registered on this subject (or wait only for the first response):
126
127 ```go
128 sub, _ := nc.SubscribeSync("rply")
129 nc.PublishRequest("svc.echo", "rply", nil)
130 for start := time.Now(); time.Since(start) < 5*time.Second; {
131 msg, err := sub.NextMsg(1 * time.Second)
132 if err != nil {
133 break
134 }
135 fmt.Println("Received ", string(msg.Data))
136 }
137 ```
138
139 Queue groups can be overwritten by setting them on groups and endpoints as well:
140
141 ```go
142 srv, _ := micro.AddService(nc, micro.Config{
143 Name: "EchoService",
144 Version: "1.0.0",
145 QueueGroup: "q1",
146 })
147
148 g := srv.AddGroup("g", micro.WithGroupQueueGroup("q2"))
149
150 // will be registered with queue group 'q2' from parent group
151 g.AddEndpoint("bar", micro.HandlerFunc(func(r micro.Request) {}))
152
153 // will be registered with queue group 'q3'
154 g.AddEndpoint("bar", micro.HandlerFunc(func(r micro.Request) {}), micro.WithEndpointQueueGroup("q3"))
155 ```
156
157 Similarly, queue groups can be disabled on service config, group and endpoint levels. If disabled,
158 a standard NATS subscription will be created for the endpoint.
159
160 ```go
161 // disable queue group for the service
162 srv, _ := micro.AddService(nc, micro.Config{
163 Name: "EchoService",
164 Version: "1.0.0",
165 QueueGroupDisabled: true,
166 })
167
168 // create a group with queue group disabled
169 srv.AddGroup("g", micro.WithEndpointQueueGroupDisabled())
170
171 // create an endpoint with queue group disabled
172 srv.AddEndpoint("bar", micro.HandlerFunc(func(r micro.Request) {}), micro.WithEndpointQueueGroupDisabled())
173 ```
174
175 When disabling queue groups, same inheritance rules apply as for customizing
176 queue groups. (service config -> group -> endpoint)
177
178 ## Discovery and Monitoring
179
180 Each service is assigned a unique ID on creation. A service instance is
181 identified by service name and ID. Multiple services with the same name, but
182 different IDs can be created.
183
184 Each service exposes 3 endpoints when created:
185
186 - PING - used for service discovery and RTT calculation
187 - INFO - returns service configuration details (used subjects, service metadata
188 etc.)
189 - STATS - service statistics
190
191 Each of those operations can be performed on 3 subjects:
192
193 - all services: `$SRV.<operation>` - returns a response for each created service
194 and service instance
195 - by service name: `$SRV.<operation>.<service_name>` - returns a response for
196 each service with given `service_name`
197 - by service name and ID: `$SRV.<operation>.<service_name>.<service_id>` -
198 returns a response for a service with given `service_name` and `service_id`
199
200 For given configuration
201
202 ```go
203 nc, _ := nats.Connect("nats://localhost:4222")
204 echoHandler := func(req micro.Request) {
205 req.Respond(req.Data())
206 }
207
208 config := micro.Config{
209 Name: "EchoService",
210 Version: "1.0.0",
211 Endpoint: &micro.EndpointConfig{
212 Subject: "svc.echo",
213 Handler: micro.HandlerFunc(echoHandler),
214 },
215 }
216 for i := 0; i < 3; i++ {
217 srv, err := micro.AddService(nc, config)
218 if err != nil {
219 log.Fatal(err)
220 }
221 defer srv.Stop()
222 }
223 ```
224
225 Service IDs can be discovered by:
226
227 ```sh
228 nats req '$SRV.PING.EchoService' '' --replies=3
229
230 13:03:04 Sending request on "$SRV.PING.EchoService"
231 13:03:04 Received with rtt 1.302208ms
232 {"name":"EchoService","id":"x3Yuiq7g7MoxhXdxk7i4K7","version":"1.0.0","metadata":{},"type":"io.nats.micro.v1.ping_response"}
233
234 13:03:04 Received with rtt 1.317ms
235 {"name":"EchoService","id":"x3Yuiq7g7MoxhXdxk7i4Kt","version":"1.0.0","metadata":{},"type":"io.nats.micro.v1.ping_response"}
236
237 13:03:04 Received with rtt 1.320291ms
238 {"name":"EchoService","id":"x3Yuiq7g7MoxhXdxk7i4Lf","version":"1.0.0","metadata":{},"type":"io.nats.micro.v1.ping_response"}
239 ```
240
241 A specific service instance info can be retrieved:
242
243 ```sh
244 nats req '$SRV.INFO.EchoService.x3Yuiq7g7MoxhXdxk7i4K7' '' | jq
245
246 13:04:19 Sending request on "$SRV.INFO.EchoService.x3Yuiq7g7MoxhXdxk7i4K7"
247 13:04:19 Received with rtt 318.875µs
248 {
249 "name": "EchoService",
250 "id": "x3Yuiq7g7MoxhXdxk7i4K7",
251 "version": "1.0.0",
252 "metadata": {},
253 "type": "io.nats.micro.v1.info_response",
254 "description": "",
255 "endpoints": [
256 {
257 "name": "default",
258 "subject": "svc.echo",
259 "queue_group": "q",
260 "metadata": null
261 }
262 ]
263 }
264 ```
265
266 To get statistics for this service:
267
268 ```sh
269 nats req '$SRV.STATS.EchoService.x3Yuiq7g7MoxhXdxk7i4K7' '' | jq
270
271 13:04:46 Sending request on "$SRV.STATS.EchoService.x3Yuiq7g7MoxhXdxk7i4K7"
272 13:04:46 Received with rtt 678.25µs
273 {
274 "name": "EchoService",
275 "id": "x3Yuiq7g7MoxhXdxk7i4K7",
276 "version": "1.0.0",
277 "metadata": {},
278 "type": "io.nats.micro.v1.stats_response",
279 "started": "2024-09-24T11:02:55.564771Z",
280 "endpoints": [
281 {
282 "name": "default",
283 "subject": "svc.echo",
284 "queue_group": "q",
285 "num_requests": 0,
286 "num_errors": 0,
287 "last_error": "",
288 "processing_time": 0,
289 "average_processing_time": 0
290 }
291 ]
292 }
293 ```
294
295 ## Examples
296
297 For more detailed examples, refer to the `./test/example_test.go` directory in
298 this package.
299
300 ## Documentation
301
302 The complete documentation is available on
303 [GoDoc](https://godoc.org/github.com/nats-io/nats.go/micro).