rabbitmq五种模式
simple模式:不需要交换机,直连模式。一个队列只有一个消费者
work模式:一个队列多个消费者
direct模式:需要交换机,通过交换机的路由key,精确匹配queue,并发送至对应的queue
topic模式:通过路由与路由key,模糊匹配的模式。可用通配符。比如key.1会被绑定路由key.*的queue获取到
fanout: 广播模式,不需要路由key,给所有绑定到交换机的queue
配置文件
spring:
rabbitmq:
virtual-host: xxxxx
port: 5672
username: xxxxx
password: xxxxxxx
host: 192.168.178.100
publisher-returns: true
publisher-confirms: true
connection-timeout: 5000
tspTboxFormatdataChange: TSP-TBOX-FORMATDATA-CHANGE
tspTboxFormatdataQueue: TSP-TBOX-FORMATDATA-QUEUE
配置类
@Configuration
public class RabbitMQConfig {
@Bean("tspTboxFormatdataQueue")
public Queue tspTboxFormatdataQueue(){
return new Queue(tspTboxFormatdataQueue, true); //队列持久
}
@Bean("tspTboxFormatdataChange")
public Exchange tspTboxFormatdataChange(){
return new TopicExchange(tspTboxFormatdataChange, true, false);
}
@Bean
public Binding tspTboxFormatdataBinding(@Qualifier("tspTboxFormatdataQueue") Queue queue,@Qualifier("tspTboxFormatdataChange") Exchange exchange) {
return BindingBuilder.bind(queue).to(exchange).with("#").noargs();
}
//需要消息自动序列化成json则设置
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
rabbitTemplate.setMessageConverter(jackson2JsonMessageConverter());
return rabbitTemplate;
}
@Bean
public Jackson2JsonMessageConverter jackson2JsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
}
生产者
@Component
public class RabbitMqProducer implements RabbitTemplate.ConfirmCallback {
private RabbitTemplate rabbitTemplate;
public void sendMessage(String exchange, String routingkey, Object message) {
log.info("队列{} to send message:{}",routingkey, message);
rabbitTemplate.convertAndSend(exchange, routingkey, message);
}
@Override
public void confirm(CorrelationData correlationData, boolean b, String s) {
}
@Autowired
public void setRabbitTemplate(RabbitTemplate rabbitTemplate) {
this.rabbitTemplate = rabbitTemplate;
}
}
消费者
@Component
public class TBoxRawDataQueueConsumer {
@RabbitListener(queues = "TBOX-TSP-REALTIME-RAWDATA-QUEUE")
public void process(Channel channel, Message message) throws IOException {
Boolean flag=false;
try {
if (!StringUtils.isEmpty(message)) {
String s = new String(message.getBody(), StandardCharsets.UTF_8.name());
log.info("TBoxRawDataQueueListener:{}", s);
}
} catch (Exception ex) {
log.error("TBoxRawDataQueueListener{}", ex);
}
}
}
rabbitmq必须在项目中必须有消费者才能自动创建队列和交换机;
但是不是所有的项目都需要消费者;
可以进行如下配置也可以实现自动创建队列和交换机:
在RabbitMQConfig中增加rabbitAdmin如下所示
//创建RabbitAdmin对象
@Bean("rabbitAdmin")
public RabbitAdmin rabbitAdmin() {
RabbitAdmin rabbitAdmin = new RabbitAdmin(connectionFactory);
//是否自动创建队列和交换器
rabbitAdmin.setAutoStartup(true);
rabbitAdmin.declareExchange(tspTboxFormatdataChange());
rabbitAdmin.declareQueue(tspTboxFormatdataQueue());
return rabbitAdmin;
}
本人发现初始化RabbitAdmin后会和rabbitmq创建连接并一直连接状态,因比较忙未查找原因,有大神解释一下
附:送上mq全部配置
spring:
rabbitmq:
host: 127.0.0.1 #ip
port: 5672 #端口
username: guest #账号
password: guest #密码
virtualHost: #链接的虚拟主机
addresses: 127.0.0.1:5672 #多个以逗号分隔,与host功能一样。
requestedHeartbeat: 60 #指定心跳超时,单位秒,0为不指定;默认60s
publisherConfirms: true #发布确认机制是否启用
publisherReturns: #发布返回是否启用
connectionTimeout: #链接超时。单位ms。0表示无穷大不超时
### ssl相关
ssl:
enabled: #是否支持ssl
keyStore: #指定持有SSL certificate的key store的路径
keyStoreType: #key store类型 默认PKCS12
keyStorePassword: #指定访问key store的密码
trustStore: #指定持有SSL certificates的Trust store
trustStoreType: #默认JKS
trustStorePassword: #访问密码
algorithm: #ssl使用的算法,例如,TLSv1.1
verifyHostname: #是否开启hostname验证
### cache相关
cache:
channel:
size: #缓存中保持的channel数量
checkoutTimeout: #当缓存数量被设置时,从缓存中获取一个channel的超时时间,单位毫秒;如果为0,则总是创建一个新channel
connection:
mode: #连接工厂缓存模式:CHANNEL 和 CONNECTION
size: #缓存的连接数,只有是CONNECTION模式时生效
### listener
listener:
type: #两种类型,SIMPLE,DIRECT
## simple类型
simple:
concurrency: #最小消费者数量
maxConcurrency: #最大的消费者数量
transactionSize: #指定一个事务处理的消息数量,最好是小于等于prefetch的数量
missingQueuesFatal: #是否停止容器当容器中的队列不可用
## 与direct相同配置部分
autoStartup: #是否自动启动容器
acknowledgeMode: #表示消息确认方式,其有三种配置方式,分别是none、manual和auto;默认auto
prefetch: #指定一个请求能处理多少个消息,如果有事务的话,必须大于等于transaction数量
defaultRequeueRejected: #决定被拒绝的消息是否重新入队;默认是true(与参数acknowledge-mode有关系)
idleEventInterval: #container events发布频率,单位ms
##重试机制
retry:
stateless: #有无状态
enabled: #是否开启
maxAttempts: #最大重试次数,默认3
initialInterval: #重试间隔
multiplier: #对于上一次重试的乘数
maxInterval: #最大重试时间间隔
direct:
consumersPerQueue: #每个队列消费者数量
missingQueuesFatal:
#...其余配置看上方公共配置
## template相关
template:
mandatory: #是否启用强制信息;默认false
receiveTimeout: #`receive()`接收方法超时时间
replyTimeout: #`sendAndReceive()`超时时间
exchange: #默认的交换机
routingKey: #默认的路由
defaultReceiveQueue: #默认的接收队列
## retry重试相关
retry:
enabled: #是否开启
maxAttempts: #最大重试次数
initialInterval: #重试间隔
multiplier: #失败间隔乘数
maxInterval: #最大间隔
非固定队列名
因项目需要消费mq需要判断当前车辆是否登入该服务才可以给车辆下发控制数据,但项目是多部署不能增加项目就增加配置,所以采用队列由IP和端口号组成,启动项目生成队列名,由mq自动创建队列和绑定关系,通过创建的队列名消费消息,将队列routingkey放入redis,生产者从redis获取routingkey,发送消息
创建队列和绑定关系
public String getQueue(){
InetAddress ip4 = null;
try {
ip4 = Inet4Address.getLocalHost();
return ip4.getHostAddress().replace(".","")+serverPort;
} catch (UnknownHostException e) {
log.info("获取IP地址失败{}",e);
return null;
}
}
@Bean
public Queue tspTboxBQueue(){
return new Queue(getQueue(), true); //队列持久
}
@Bean("tspTboxFormatdataChange")
public Exchange tspTboxFormatdataChange(){
return new TopicExchange(tspTboxFormatdataChange, true, false);
}
@Bean
public Binding tspTboxFormatdataBinding(@Qualifier("tspTboxFormatdataChange") Exchange exchange) {
return BindingBuilder.bind(tspQueue()).to(exchange).with(getQueue()).noargs();
}
增加消费者
@Component
public class TBoxRawDataQueueConsumer implements ChannelAwareMessageListener {
private TbxoRawDataService tbxoRawDataService;
@Autowired
public void setTbxoRawDataService(TbxoRawDataService tbxoRawDataService) {
this.tbxoRawDataService = tbxoRawDataService;
}
@Override
public void onMessage(Message message, Channel channel) throws Exception {
Boolean flag=false;
try {
if (!StringUtils.isEmpty(message)) {
String s = new String(message.getBody(), StandardCharsets.UTF_8.name());
log.info("TBoxRawDataQueueListener:{}", s);
flag=tbxoRawDataService.save(s);
log.info("执行Hbase保存{}",flag);
}
} catch (Exception ex) {
log.error("TBoxRawDataQueueListener{}", ex);
}
}
}
//创建监听器,监听队列
@Bean
public SimpleMessageListenerContainer mqMessageContainer(HandleService handleService) throws AmqpException, IOException {
SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory());
container.setQueueNames(mqMsgQueues());
container.setExposeListenerChannel(true);
container.setPrefetchCount(prefetchCount);//设置每个消费者获取的最大的消息数量
container.setConcurrentConsumers(concurrentConsumers);//消费者个数
container.setAcknowledgeMode(AcknowledgeMode.MANUAL);//设置确认模式为手工确认
container.setMessageListener(tBoxRawDataQueueConsumer );//监听处理类
return container;
}