class
NATS::Services
- NATS::Services
- Reference
- Object
Overview
The NATS Services API allows you to build microservices using NATS instead of HTTP. Since NATS has the concept of request/reply messages through a decentralized message broker, you don't need to deal with domain names, load-balancing, service meshes, or other concepts that you might have to implement in HTTP-based microservices. NATS takes care of all of those for you.
inventory = nats.services.add "inventory",
version: "0.1.0",
description: "Manage store inventory"
# Add the top-level subject namespace for the service
inventory.add_group "inventory" do |inv|
# Add a namespace specifically for managing products
inv.add_group "products" do |products|
# Create a product. Receives a CreateProductRequest and returns a Product.
# Example using the NATS CLI:
# nats req inventory.products.create '{"name":"Computer","description":"It is a computer","price_cents":200000}'
products.add_endpoint "create" do |request|
# Deserialize the request body and make a product out of it
product = CreateProductRequest.from_json(request.data_string).product
# Save the product to our KV store
products_kv[product.id.to_s] = product.to_json
# Reply with the serialized product
nats.reply request, product.to_json
end
# Return the product with the given id passed in the subject.
# Example: inventory.products.get.0197e31f-3ffa-7fd7-8512-a331a20e5ae3
# Equivalent to the following HTTP request:
# GET /inventory/products/0197e31f-3ffa-7fd7-8512-a331a20e5ae3
products.add_endpoint "show", subject: "get.*" do |request|
# Split the subject to get the id
_, _, _, product_id = request.subject.split('.')
# Fetch the product from the `inventory-products` KV bucket
nats.reply request, products_kv[product_id]
end
end
end
Defined in:
services.crConstant Summary
-
NAME_PATTERN =
/\A[\w\-]+\z/
Instance Method Summary
-
#add(name : String, *, version : String, description : String, metadata : Hash(String, String) = {} of String => String)
Register a service with the NATS server.
Instance Method Detail
def add(name : String, *, version : String, description : String, metadata : Hash(String, String) = {} of String => String)
#
Register a service with the NATS server.
inventory = nats.services.add "inventory",
version: "0.1.0",
description: "Manage inventory"