【发布时间】:2014-01-21 10:24:29
【问题描述】:
我一直在尝试使用 activemq 和 java 从 tcp 服务器订阅多个主题。
据谷歌告诉我,我可以使用通配符或复合目的地来做到这一点但是主题的命名方式对通配符非常不友好。当我尝试将目的地设置为“topic1,topic2”时,我不断收到错误消息,说我无权访问这些主题,而如果我只听 topic1 或 topic2,订阅工作顺利。
有些人还建议我可以更改 activemq.xml 文件以在其中设置代理,但我不明白这些是如何工作的。如果这是解决方案,也许有人可以抽出宝贵的时间向我解释一下?
感谢您的宝贵时间。
最好的问候
更具体的代码附在这里:
import javax.jms.*;
import org.apache.activemq.ActiveMQConnection;
import org.apache.activemq.ActiveMQConnectionFactory;
import org.apache.log4j.BasicConfigurator;
public class Consumer {
// URL of the JMS server
private static String url = "tcp://datafeeds.networkrail.co.uk:61619";
private static String username = "my username";
private static String password = "my password";
private static String topic = "topic1";
public static void main(String[] args) throws JMSException {
BasicConfigurator.configure();
// Getting JMS connection from the server
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(url);
Connection connection = connectionFactory.createConnection(username,password);
connection.start();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createTopic(topic);
MessageConsumer consumer = session.createConsumer(destination);
while (true)
{
//System.out.println("Waiting for message...");
Message message = consumer.receive();
if (message != null && message instanceof TextMessage) {
TextMessage txtMsg = (TextMessage)message;
System.out.println("Received: " + txtMsg.getText());
}
}
//System.out.println("Closing connection");
//consumer.close();
//session.close();
//connection.close();
}}
【问题讨论】:
-
你是什么意思,你想从 tcp 服务器订阅主题?使用 ActiveMQ-JMS-client,您只能订阅 ActiveMQ-JMS-brokers,请澄清。
-
我所做的是设置一个activemqconnection工厂并将url设置为我正在收听的tcp地址和主题。我的问题是我目前只能听一个主题,而我需要听多个主题。希望我已经澄清了这个问题。谢谢。
-
看代码肯定有帮助。如果你可以听一个主题,你应该有一个 Session 对象。使用它来为其他主题创建消费者。
-
我在帖子中附上了代码,希望能解释问题。虽然不是最佳选择,但我发现用 '*' 替换 'topic1' 确实允许我订阅所有主题,我仍然有兴趣学习如何订阅我需要的确切主题。
-
请参考stackoverflow.com/questions/35715767/…以获得更好的解释以及代码示例。