有没有人有使用 NATS Streaming Server 和 Java 客户端的经验?具体来说,我不知道如何使用 Java 客户端检索订阅者离线时发送的消息。
我可以看到使用Go 客户端可以发布消息,然后添加订阅以检索所有已发布的消息。这在 NATS Streaming Getting Started文档中,它可以像宣传的那样工作。
发布多条消息。对于每个出版物,您应该得到一个结果。
$ cd $GOPATH/src/github.com/nats-io/go-nats-streaming/examples
go run stan-pub.go foo "msg one"
Published [foo] : 'msg one'
$ go run stan-pub.go foo "msg two"
Published [foo] : 'msg two'
$ go run stan-pub.go foo "msg three"
Published [foo] : 'msg three'
运行订阅者客户端。使用 --all 标志接收所有发布的消息。
$ go run stan-sub.go --all -c test-cluster -id myID foo
Connected to nats://localhost:4222 clusterID: [test-cluster] clientID: [myID]
subscribing with DeliverAllAvailable
Listening on [foo], clientID=[myID], qgroup=[] durable=[]
[#1] Received on [foo]: 'sequence:1 subject:"foo" data:"msg one" timestamp:1465962202884478817 '
[#2] Received on [foo]: 'sequence:2 subject:"foo" data:"msg two" timestamp:1465962208545003897 '
[#3] Received on [foo]: 'sequence:3 subject:"foo" data:"msg three" timestamp:1465962215567601196
我正在尝试使用NATS Java client来做到这一点。我不知道是因为我没有找到类似的方法调用,还是 Java 客户端中不存在该功能。
这是我尝试过的
import io.nats.client.Connection;
import io.nats.client.ConnectionFactory;
import io.nats.client.Constants;
import io.nats.client.Message;
import io.nats.client.SyncSubscription;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class NatsTest2 {
private static final SecureRandom random = new SecureRandom();
public static void main(String... args) throws Exception {
final ConnectionFactory factory = new ConnectionFactory(Constants.DEFAULT_URL);
try (final Connection conn = factory.createConnection()) {
// Simple Async Subscriber
final String expectMessage = "Yum, cookies " + System.currentTimeMillis();
works(conn, expectMessage);
broken(conn, expectMessage);
}
}
private static void works(Connection conn, String expectMessage) throws IOException, TimeoutException {
final String queue = Long.toString(random.nextLong());
System.out.print(queue + "=>");
try (final SyncSubscription subscription = conn.subscribeSync(queue)) {
conn.publish(queue, expectMessage.getBytes());
subscribe(subscription);
}
}
private static void broken(Connection conn, String expectMessage) throws IOException, TimeoutException {
final String queue = Long.toString(random.nextLong());
System.out.print(queue + "=>");
conn.publish(queue, expectMessage.getBytes());
try (final SyncSubscription subscription = conn.subscribeSync(queue)) {
subscribe(subscription);
}
}
private static void subscribe(SyncSubscription subscription) throws IOException, TimeoutException {
final Message message = subscription.nextMessage(1, TimeUnit.SECONDS);
System.out.println(new String(message.getData()));
}
}
这给出了输出
-8522002637987832314=>Yum, cookies 1473462495040
-3024385525006291780=>Exception in thread "main" java.util.concurrent.TimeoutException: Channel timed out waiting for items