我使用发布者/订阅者模型以循环方式传递消息。在这里,我使用2个消费者来处理请求。我想在处理一个请求后停止一个消费者。我如何阻止一个消费者?如果是这样,剩下的请求将转给其他消费者。如果消费者无法发回,那么(持久性)数据会发生什么?它会丢失还是会传递给其他消费者?
public class Testing {
public static void main(String[] args) throws URISyntaxException, Exception {
BrokerService broker = BrokerFactory.createBroker(new URI(
"broker:(tcp://localhost:61616)"));
broker.start();
Connection connection = null;
try {
// Producer
ConnectionFactory connectionFactory = new ActiveMQConnectionFactory(
"tcp://localhost:61616");
connection = connectionFactory.createConnection();
Session session = connection.createSession(false,
Session.AUTO_ACKNOWLEDGE);
Queue queue = session.createQueue("customerQueue");
// Consumer
for (int i = 0; i < 2; i++) {
MessageConsumer consumer = session.createConsumer(queue);
if(i == 0)
{
consumer.setMessageListener(new ConsumerMessageListener("Consumer " + i));
}
consumer.setMessageListener(new TestingOnc("Consumer" + i));
}
broker.stop();
}
}
}
制片人打电话给我
public synchronized static void createMQRequestForPoster(Long zoneId, List<String> postJobs, int priority) throws JMSException {
Connection connection = null;
try {
connection = factory.createConnection();
connection.start();
Session session = connection.createSession(false,
Session.CLIENT_ACKNOWLEDGE);
Destination dest = session
.createQueue(SMCConstants.ACTIVEMQ_POST_REQUEST);
MessageProducer producer = session.createProducer(dest);
producer.setDeliveryMode(DeliveryMode.PERSISTENT);
logger.info("List of jobs adding into poster queue: "+postJobs.size());
for(String str : postJobs) {
TextMessage message = session.createTextMessage();
JSONObject obj = new JSONObject();
obj.put("priority", priority);
obj.put("zoneId", zoneId);
obj.put("postJobs", str);
logger.debug(obj.toString());
message.setText(obj.toString());
message.setIntProperty(ActiveMQReqProcessor.REQ_TYPE, 0);
producer.send(message);
}
} catch (JMSException | JSONException e) {
logger.warn("Failed to add poster request to ActiveMq", e);
} finally {
if(connection != null)
connection.close();
}
}
}
能够发送和接收消息。