activeMQ配合使用camel可灵活配置消费者个数,代码也更简洁
需要引入的jar包
compile group: 'org.apache.camel', name: 'camel-spring-boot-starter', version: '2.18.3'
compile group: 'org.apache.camel', name: 'camel-jms', version: '2.18.3'
消费者-consumer
@Component
public class StoreRouter extends RouteBuilder{
@Override
public void configure() throws Exception {
//命名规则必须遵守Consumer.consumerName.VirtualTopic.topicName,简单来说只能有三个. 如需分割可使用-来分割
from("jms:queue:Consumer.consumer1.VirtualTopic.store-MessageProducer-storeRegister?concurrentConsumers=1").
to("bean:storeMessageConsumer?method=storeRegister").routeId("注册消息消费者");
}
}
@Component
public class StoreMessageConsumer {
private Logger logger = LoggerFactory.getLogger(StoreMessageConsumer.class);
/**
* 注册消息
*
* @throws IOException
*/
public void storeRegister(@Headers Map result) throws IOException {
try {
logger.info("消费注册消息,信息:"+ result.get("id"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
生产者-producer
引入jar包:
compile group: 'org.springframework.boot', name: 'spring-boot-starter-activemq', version: '1.4.2.RELEASE'
@Component
public class StoreMessageProducer {
private static Logger logger = LoggerFactory.getLogger(StoreMessageProducer.class);
//这里使用的是VirtualTopic,优点不赘诉
@Produce(uri = "jms:topic:VirtualTopic.store-MessageProducer-storeRegister")
private ProducerTemplate registTopicProducerTemplate;
public void storeRegister(String id) {
Map map = new HashMap();
map.put("id", id);
try {
storeRegistTopicProducerTemplate.sendBodyAndHeaders( "store:register", map);
} catch (Exception e) {
e.printStackTrace();
logger.error("注册 activeMQ发送出错", e);
}
}
}