需要为activemq java代码

时间:2016-10-14 13:48:16

标签: java activemq

我正在尝试编写一个连接到activeMQ队列的简单java代码,我发现this资源在线,它基本上遵循activeMQ站点中的Hello World示例。我正在尝试在队列名称旁边指定用户名和密码,我无法在线找到任何有用的资源,所以任何帮助都将受到高度赞赏。

我在生产者代码中进行了以下更改,我不确定如何指定工厂名称以及我是否正确指定了用户名和密码?

            // First create a connection
            InitialContext initCtx = new InitialContext();
            javax.jms.ConnectionFactory qcf = (javax.jms.ConnectionFactory) initCtx.lookup(factoryName);
            Connection connection = qcf.createConnection("admin","admin");
            connection.start();

1 个答案:

答案 0 :(得分:1)

这是一个例子

        Properties props = new Properties();
        props.put(Context.INITIAL_CONTEXT_FACTORY,
                "org.apache.activemq.jndi.ActiveMQInitialContextFactory");
        props.setProperty(Context.PROVIDER_URL,
                "tcp://localhost:61616");
        props.put("topic." + "TOPICNAME", "TOPICNAME");
        InitialContext ic = new InitialContext(props);
        ConnectionFactory cf1 = (ConnectionFactory) ic.lookup("ConnectionFactory");
        writeDestination = (Topic) ic.lookup("TOPICNAME");
        writeDestConnection = cf1.createConnection("user", "pwd");
        writeDestConnection.setClientID("durableSubscriber_" + "TOPICNAME");
        writeDestSession = writeDestConnection.createSession(false,Session.AUTO_ACKNOWLEDGE);
        writeDestProducer = writeDestSession.createProducer(writeDestination);
        writeDestConnection.start();
        TextMessage message = writeDestSession.createTextMessage(json);
        message.setStringProperty("clientID", "ifYouNeed");
        writeDestProducer.send(message);

http://activemq.apache.org/jndi-support.html

这是另一个没有jndi的例子:

    public static void main(String[] args) throws JMSException {
    Connection conn = null;
    try {
        ActiveMQConnectionFactory cf = new ActiveMQConnectionFactory("tcp://localhost:61616");
        conn = cf.createConnection("user", "pwd");
        Session session = conn.createSession(false, Session.AUTO_ACKNOWLEDGE);
        MessageConsumer consumer = session.createConsumer(session.createQueue("queueName"));
        conn.start();
        TextMessage msg = null;
        while ((msg = (TextMessage) consumer.receive()) != null) {
            System.out.println("Received message is: " + msg.getText());
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (conn != null) {
            try {
                conn.close();
            } catch (Exception e) {
            }
        }
    }
}