" BrokerFactory"从xml文件中获取配置。 如何配置生产者?
遵循这个例子:
http://activemq.apache.org/hello-world.html
Iv使用以下内容进行生产者连接
ActiveMQConnectionFactory connectionFactory = ...
我无法找到更改其端口的位置 "Hello-World"之后很好,直到我想将经纪人生产者和消费者分开到不同的流程。
(我正在使用Java SE,在薄荷17上运行)
答案 0 :(得分:1)
我发布了我正在使用的Java代码,希望它有所帮助。 Producer和Consumer都在他们自己的Runnable类中。
制片人代码:
public void run(){
logger.debug("JMS Sender get started to send responses to activeMq...");
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(user, password, url);
connectionFactory.setUseAsyncSend(true);//faster than sync
connectionFactory.setOptimizeAcknowledge(true);
Connection connection;
try{
connection = connectionFactory.createConnection();
connection.start();
/** create an activeMq for responses **/
session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
destination = session.createQueue(jmsResponseQueueName);
MessageProducer responseProducer = session.createProducer(destination);
responseProducer.setDeliveryMode(DeliveryMode.PERSISTENT); //persistent mode
while (keepRunning){
// do time-consuming work here
}
}
catch (JMSException e){
logger.error("Exception occur when sender fails to connect to activeMQ:{}", e.getMessage());
}
catch (InterruptedException ie){
logger.error("Exception occur when take response from queue...{}", ie.getMessage());
}
}
消费者方:
@Override public void run(){
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory(jmsUser, jmsPassword, jmsUrl);
try {
Connection connection = connectionFactory.createConnection();
Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
Destination destination = session.createQueue(jmsQueueName);
MessageConsumer consumer = session.createConsumer(destination);
consumer.setMessageListener(this);
connection.start();
}
catch (JMSException jmse){
logger.error("JMSException occur: {}", jmse.getMessage());
}
}
/**
* Receiving incoming responses from activemq, and then store the received response
* into a linked blocking response queue.
* @param message
*/
@Override public void onMessage(Message message){
try {
if(message != null){
// consume the valid message
}
}
catch (JMSException exception){
logger.error("Exception is thrown when handle received message: {}", exception.getMessage());
}
catch (InterruptedException exception){
logger.error("Exception is thrown when handle received message: {}", exception.getMessage());
}
}
URL
是这样的,它包含port
:
"failover://(tcp://localhost:61616)?maxReconnectAttempts=0"
username
和password
默认为admin
。