NATS 中文文档
  • 引言
  • 发布日志
  • NATS 2.0
  • 对比 NATS
  • FAQ
  • NATS Concepts
    • What is NATS
    • Subject-Based Messaging
    • Publish-Subscribe
    • Request-Reply
    • Queue Groups
    • Acknowledgements
    • Sequence Numbers
  • Developing With NATS
    • Introduction
    • Connecting
      • Connecting to the Default Server
      • Connecting to a Specific Server
      • Connecting to a Cluster
      • Connection Name
      • Setting a Connect Timeout
      • Ping/Pong Protocol
      • Turning Off Echo'd Messages
      • Miscellaneous functionalities
    • Automatic Reconnections
      • Disabling Reconnect
      • Set the Number of Reconnect Attempts
      • Avoiding the Thundering Herd
      • Pausing Between Reconnect Attempts
      • Listening for Reconnect Events
      • Buffering Messages During Reconnect Attempts
    • Securing Connections
      • Authenticating with a User and Password
      • Authenticating with a Token
      • Authenticating with an NKey
      • Authenticating with a Credentials File
      • Encrypting Connections with TLS
    • Receiving Messages
      • Synchronous Subscriptions
      • Asynchronous Subscriptions
      • Unsubscribing
      • Unsubscribing After N Messages
      • Replying to a Message
      • Wildcard Subscriptions
      • Queue Subscriptions
      • Draining Messages Before Disconnect
      • Structured Data
    • Sending Messages
      • Including a Reply Subject
      • Request-Reply Semantics
      • Caches, Flush and Ping
      • Sending Structured Data
    • Monitoring the Connection
      • Listen for Connection Events
      • Slow Consumers
    • Tutorials
      • Explore NATS Pub/Sub
      • Explore NATS Request/Reply
      • Explore NATS Queueing
      • Advanced Connect and Custom Dialer in Go
  • NATS Server
    • Installing
    • Running
      • Windows Service
    • Clients
    • Flags
    • Configuration
      • Securing NATS
        • Enabling TLS
        • Authentication
          • Tokens
          • Username/Password
          • TLS Authentication
          • NKeys
          • Authentication Timeout
        • Authorization
        • Multi Tenancy using Accounts
        • Decentralized JWT Authentication/Authorization
          • Account lookup using Resolver
          • Memory Resolver Tutorial
          • Mixed Authentication/Authorization Setup
      • Clustering
        • Configuration
        • TLS Authentication
      • Super-cluster with Gateways
        • Configuration
      • Leaf Nodes
        • Configuration
      • Logging
      • Monitoring
      • System Events
        • System Events & Decentralized JWT Tutorial
    • Managing A NATS Server
      • Upgrading a Cluster
      • Slow Consumers
      • Signals
    • NATS and Docker
      • Tutorial
      • Docker Swarm
      • Python and NGS Running in Docker
  • NATS Tools
    • Introduction
    • mkpasswd
    • nk
    • nsc
      • Basics
      • Streams
      • Services
      • Signing Keys
      • Revocation
      • Managed Operators
    • nats-account-server
      • Basics
      • Inspecting JWTs
      • Directory Store
      • Update Notifications
    • nats-top
      • Tutorial
    • nats-bench
  • NATS Streaming Concepts
    • Introduction
    • Relation to NATS
    • Client Connections
    • Channels
      • Message Log
      • Subscriptions
        • Regular
        • Durable
        • Queue Group
        • Redelivery
    • Store Interface
    • Store Encryption
    • Clustering
      • Supported Stores
      • Configuration
      • Auto Configuration
      • Containers
    • Fault Tolerance
      • Active Server
      • Standby Servers
      • Shared State
      • Failover
    • Partitioning
    • Monitoring
      • Endpoints
  • Developing With NATS Streaming
    • Introduction
    • Connecting to NATS Streaming
    • Publishing to a Channel
    • Receiving Messages from a Channel
    • Durable Subscriptions
    • Queue Subscriptions
    • Acknowledgements
    • The Streaming Protocol
  • NATS Streaming Server
    • Important Changes
    • Installing
    • Running
    • Configuring
      • Command Line Arguments
      • Configuration File
      • Store Limits
      • 持久化
        • 文件存储
        • SQL 存储
      • Securing
    • Process Signaling
    • Windows Service
    • Embedding NATS Streaming Server
    • Docker Swarm
  • NATS Protocol
    • Protocol Demo
    • Client Protocol
      • Developing a Client
    • NATS Cluster Protocol
  • 在 Kubernetes中使用NATS
    • 序言
    • 安装 NATS 和 NATS Streaming
    • 创建一个 Kubernetes 集群
    • 容错(Fault Tolerance)模式下的NATS Streaming 集群
    • NATS 和 Prometheus Operator
    • NATS 集群和证书管理
    • 使用 cfssl 来提高 NATS 集群的安全性
    • 使用负载均衡器(Load Balancer) 为NATS提供外部访问
    • 使用Helm在Digital Ocean 创建一个NATS 超级集群
    • 使用Helm从0到 K8s到 子节点
由 GitBook 提供支持
在本页

这有帮助吗?

  1. Developing With NATS
  2. Receiving Messages

Wildcard Subscriptions

上一页Replying to a Message下一页Queue Subscriptions

最后更新于4年前

这有帮助吗?

There is no special code to subscribe with a . Wildcards are a normal part of the subject name. However, it is a common technique to use the subject provided with the incoming message to determine what to do with the message.

For example, you can subscribe using * and then act based on the actual subject.

nc, err := nats.Connect("demo.nats.io")
if err != nil {
    log.Fatal(err)
}
defer nc.Close()

// Use a WaitGroup to wait for 2 messages to arrive
wg := sync.WaitGroup{}
wg.Add(2)

// Subscribe
if _, err := nc.Subscribe("time.*.east", func(m *nats.Msg) {
    log.Printf("%s: %s", m.Subject, m.Data)
    wg.Done()
}); err != nil {
    log.Fatal(err)
}

// Wait for the 2 messages to come in
wg.Wait()
Connection nc = Nats.connect("nats://demo.nats.io:4222");

// Use a latch to wait for 2 messages to arrive
CountDownLatch latch = new CountDownLatch(2);

// Create a dispatcher and inline message handler
Dispatcher d = nc.createDispatcher((msg) -> {
    String subject = msg.getSubject();
    String str = new String(msg.getData(), StandardCharsets.UTF_8);
    System.out.println(subject + ": " + str);
    latch.countDown();
});

// Subscribe
d.subscribe("time.*.east");

// Wait for messages to come in
latch.await();

// Close the connection
nc.close();
let nc = NATS.connect({
    url: "nats://demo.nats.io:4222"});

nc.subscribe('time.us.*', (msg, reply, subject) => {
    // converting timezones correctly in node requires a library
    // this doesn't take into account *many* things.
    let time = "";
    switch (subject) {
        case 'time.us.east':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/New_York"});
            break;
        case 'time.us.central':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Chicago"});
            break;
        case 'time.us.mountain':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Denver"});
            break;
        case 'time.us.west':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Los_Angeles"});
            break;
        default:
            time = "I don't know what you are talking about Willis";
    }
    t.log(subject, time);
});
nc = NATS()

await nc.connect(servers=["nats://demo.nats.io:4222"])

# Use queue to wait for 2 messages to arrive
queue = asyncio.Queue()
async def cb(msg):
  await queue.put_nowait(msg)

await nc.subscribe("time.*.east", cb=cb)

# Send 2 messages and wait for them to come in
await nc.publish("time.A.east", b'A')
await nc.publish("time.B.east", b'B')

msg_A = await queue.get()
msg_B = await queue.get()

print("Msg A:", msg_A)
print("Msg B:", msg_B)
require 'nats/client'
require 'fiber'

NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc|
  Fiber.new do
    f = Fiber.current

    nc.subscribe("time.*.east") do |msg, reply|
      f.resume Time.now
    end

    nc.publish("time.A.east", "A")
    nc.publish("time.B.east", "B")

    # Use the response
    msg_A = Fiber.yield
    puts "Msg A: #{msg_A}"

    msg_B = Fiber.yield
    puts "Msg B: #{msg_B}"

  end.resume
end
await nc.subscribe('time.us.*', (err, msg) => {
    // converting timezones correctly in node requires a library
    // this doesn't take into account *many* things.
    let time = "";
    switch (msg.subject) {
        case 'time.us.east':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/New_York"});
            break;
        case 'time.us.central':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Chicago"});
            break;
        case 'time.us.mountain':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Denver"});
            break;
        case 'time.us.west':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Los_Angeles"});
            break;
        default:
            time = "I don't know what you are talking about Willis";
    }
    console.log(msg.subject, time);
});
static void
onMsg(natsConnection *conn, natsSubscription *sub, natsMsg *msg, void *closure)
{
    printf("Received msg: %s - %.*s\n",
           natsMsg_GetSubject(msg),
           natsMsg_GetDataLength(msg),
           natsMsg_GetData(msg));

    // Need to destroy the message!
    natsMsg_Destroy(msg);
}


(...)

natsConnection      *conn = NULL;
natsSubscription    *sub  = NULL;
natsStatus          s;

s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);
if (s == NATS_OK)
    s = natsConnection_Subscribe(&sub, conn, "time.*.east", onMsg, NULL);

(...)


// Destroy objects that were created
natsSubscription_Destroy(sub);
natsConnection_Destroy(conn);

or do something similar with >:

nc, err := nats.Connect("demo.nats.io")
if err != nil {
    log.Fatal(err)
}
defer nc.Close()

// Use a WaitGroup to wait for 4 messages to arrive
wg := sync.WaitGroup{}
wg.Add(4)

// Subscribe
if _, err := nc.Subscribe("time.>", func(m *nats.Msg) {
    log.Printf("%s: %s", m.Subject, m.Data)
    wg.Done()
}); err != nil {
    log.Fatal(err)
}

// Wait for the 4 messages to come in
wg.Wait()

// Close the connection
nc.Close()
Connection nc = Nats.connect("nats://demo.nats.io:4222");

// Use a latch to wait for 4 messages to arrive
CountDownLatch latch = new CountDownLatch(4);

// Create a dispatcher and inline message handler
Dispatcher d = nc.createDispatcher((msg) -> {
    String subject = msg.getSubject();
    String str = new String(msg.getData(), StandardCharsets.UTF_8);
    System.out.println(subject + ": " + str);
    latch.countDown();
});

// Subscribe
d.subscribe("time.>");

// Wait for messages to come in
latch.await();

// Close the connection
nc.close();
let nc = NATS.connect({
    url: "nats://demo.nats.io:4222"});

nc.subscribe('time.>', (msg, reply, subject) => {
    // converting timezones correctly in node requires a library
    // this doesn't take into account *many* things.
    let time = "";
    switch (subject) {
        case 'time.us.east':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/New_York"});
            break;
        case 'time.us.central':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Chicago"});
            break;
        case 'time.us.mountain':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Denver"});
            break;
        case 'time.us.west':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Los_Angeles"});
            break;
        default:
            time = "I don't know what you are talking about Willis";
    }
    t.log(subject, time);
});
nc = NATS()

await nc.connect(servers=["nats://demo.nats.io:4222"])

# Use queue to wait for 4 messages to arrive
queue = asyncio.Queue()
async def cb(msg):
  await queue.put(msg)

await nc.subscribe("time.>", cb=cb)

# Send 2 messages and wait for them to come in
await nc.publish("time.A.east", b'A')
await nc.publish("time.B.east", b'B')
await nc.publish("time.C.west", b'C')
await nc.publish("time.D.west", b'D')

for i in range(0, 4):
  msg = await queue.get()
  print("Msg:", msg)

await nc.close()
require 'nats/client'
require 'fiber'

NATS.start(servers:["nats://127.0.0.1:4222"]) do |nc|
  Fiber.new do
    f = Fiber.current

    nc.subscribe("time.>") do |msg, reply|
      f.resume Time.now.to_f
    end

    nc.publish("time.A.east", "A")
    nc.publish("time.B.east", "B")
    nc.publish("time.C.west", "C")
    nc.publish("time.D.west", "D")

    # Use the response
    4.times do 
      msg = Fiber.yield
      puts "Msg: #{msg}"
    end
  end.resume
end
await nc.subscribe('time.>', (err, msg) => {
    // converting timezones correctly in node requires a library
    // this doesn't take into account *many* things.
    let time = "";
    switch (msg.subject) {
        case 'time.us.east':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/New_York"});
            break;
        case 'time.us.central':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Chicago"});
            break;
        case 'time.us.mountain':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Denver"});
            break;
        case 'time.us.west':
            time = new Date().toLocaleTimeString("en-us", {timeZone: "America/Los_Angeles"});
            break;
        default:
            time = "I don't know what you are talking about Willis";
    }
    t.log(msg.subject, time);
});
static void
onMsg(natsConnection *conn, natsSubscription *sub, natsMsg *msg, void *closure)
{
    printf("Received msg: %s - %.*s\n",
           natsMsg_GetSubject(msg),
           natsMsg_GetDataLength(msg),
           natsMsg_GetData(msg));

    // Need to destroy the message!
    natsMsg_Destroy(msg);
}


(...)

natsConnection      *conn = NULL;
natsSubscription    *sub  = NULL;
natsStatus          s;

s = natsConnection_ConnectTo(&conn, NATS_DEFAULT_URL);
if (s == NATS_OK)
    s = natsConnection_Subscribe(&sub, conn, "time.>", onMsg, NULL);

(...)


// Destroy objects that were created
natsSubscription_Destroy(sub);
natsConnection_Destroy(conn);

The following example can be used to test these two subscribers. The * subscriber should receive at most 2 messages, while the > subscriber receives 4. More importantly the time.*.east subscriber won't receive on time.us.east.atlanta because that won't match.

nc, err := nats.Connect("demo.nats.io")
if err != nil {
    log.Fatal(err)
}
defer nc.Close()

zoneID, err := time.LoadLocation("America/New_York")
if err != nil {
    log.Fatal(err)
}
now := time.Now()
zoneDateTime := now.In(zoneID)
formatted := zoneDateTime.String()

nc.Publish("time.us.east", []byte(formatted))
nc.Publish("time.us.east.atlanta", []byte(formatted))

zoneID, err = time.LoadLocation("Europe/Warsaw")
if err != nil {
    log.Fatal(err)
}
zoneDateTime = now.In(zoneID)
formatted = zoneDateTime.String()

nc.Publish("time.eu.east", []byte(formatted))
nc.Publish("time.eu.east.warsaw", []byte(formatted))
Connection nc = Nats.connect("nats://demo.nats.io:4222");
ZoneId zoneId = ZoneId.of("America/New_York");
ZonedDateTime zonedDateTime = ZonedDateTime.ofInstant(Instant.now(), zoneId);
String formatted = zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);

nc.publish("time.us.east", formatted.getBytes(StandardCharsets.UTF_8));
nc.publish("time.us.east.atlanta", formatted.getBytes(StandardCharsets.UTF_8));

zoneId = ZoneId.of("Europe/Warsaw");
zonedDateTime = ZonedDateTime.ofInstant(Instant.now(), zoneId);
formatted = zonedDateTime.format(DateTimeFormatter.ISO_ZONED_DATE_TIME);
nc.publish("time.eu.east", formatted.getBytes(StandardCharsets.UTF_8));
nc.publish("time.eu.east.warsaw", formatted.getBytes(StandardCharsets.UTF_8));

nc.flush(Duration.ZERO);
nc.close();
nc.publish('time.us.east');
nc.publish('time.us.central');
nc.publish('time.us.mountain');
nc.publish('time.us.west');
nc = NATS()

await nc.connect(servers=["nats://demo.nats.io:4222"])

await nc.publish("time.us.east", b'...')
await nc.publish("time.us.east.atlanta", b'...')

await nc.publish("time.eu.east", b'...')
await nc.publish("time.eu.east.warsaw", b'...')

await nc.close()
NATS.start do |nc|
   nc.publish("time.us.east", '...')
   nc.publish("time.us.east.atlanta", '...')

   nc.publish("time.eu.east", '...')
   nc.publish("time.eu.east.warsaw", '...')

   nc.drain
end
nc.publish('time.us.east');
nc.publish('time.us.central');
nc.publish('time.us.mountain');
nc.publish('time.us.west');
wildcard subject