Search code examples
nats.ionats-jetstream

Why NATS doesn't map subjects?


I run a NATS server in Docker

docker-compose.yaml

services:
  nats:
    container_name: nats-server

    image: 'nats:2.10.9-alpine3.19'

    healthcheck:
      test: ["CMD", "curl", "-f", "http://localhost:8222/healthz"]

    ports:
    - "8230:8222" # exposing 8230 to the host
    - "4230:4222" # exposing 4230 to the host

    volumes:
    - "./nats/data/single:/data"
    - "./nats/config:/config"

    command:
    - "--js"
    - "--sd=/data"
    - "--http_port=8222"
    - "--name=nats-server"
    - "--cluster_name=local-cluster"
    - "--config=/config/nats.config"  # !! UPDATED

I created a stream

nats -s localhost:4230 \
  stream add \
  --retention=work \
  --subjects="events.>" eventsw

Then I create a mapping

nats -s localhost:4230 \
    server mapping "events.foo" "events.boo"

NATS proposes to test mapping:

[local-nats] ? Subject events.foo
events.boo

Looks that everything is correct. Then I run two subscribers:

nats -s localhost:4230 sub "events.foo"
nats -s localhost:4230 sub "events.boo"

and finally I send a message:

nats -s localhost:4230 \
  pub "events.foo" \
  ololo

And result is coming to an initial subject – events.foo. So mapping actually doesn't happen. It was assumed that the message will come to events.boo.

What I do wrong?


Solution

  • Subject mapping is configured by NATS server config. You can read about it more here.

    In short:

    1. docker-compose.yaml should contain one more command line: - "--config=/config/nats.config"

    When you run compose nats.config will appear in ./nats/config folder.

    1. config file must be extended with the following section:
    mappings = {
      # Simple direct mapping.  Messages published to foo are mapped to bar.
      foo: bar
    
      "events.foo": "events.boo"
    }
    
    1. Restart NATS.

    Now messages published to events.foo will be forwarded to events.boo.

    1. Enjoy.

    P.S. [Here] doc says that we can run nats-server --signal reload to update server configuration. But I failed with this