SpringBoot监听RabbitMQ消息

1.pom文件

	<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-amqp</artifactId>
	</dependency>

2.yml配置

mq:
  host: 192.168.2.101
  port: 5672
  username: root
  password: root
  virtualhost: /
  exchange: amq.direct
  queue.fromGw: gws.from-gw.wm
  queue.toGw: gws.to-gw.wm

3.配置类

@Configuration
public class RabbitConfig {


    @Value("${mq.queue.fromGw}")
    public String queue_fromGw;//设备上传


    @Value("${mq.queue.toGw}")
    public String queue_toGw;//下发命令


    @Bean
    public Queue fromGw() {
        return new Queue(queue_fromGw);
    }


    @Bean
    public Queue toGw() {
        return new Queue(queue_toGw);
    }


    
    @Bean
    ConnectionFactory connectionFactory(@Value("${mq.port}") int port,
                                        @Value("${mq.host}") String host,
                                        @Value("${mq.username}") String userName,
                                        @Value("${mq.password}") String password,
                                        @Value("${mq.virtualhost}") String vhost) {
        CachingConnectionFactory connectionFactory = new CachingConnectionFactory();
        connectionFactory.setHost(host);
        connectionFactory.setVirtualHost(vhost);
        connectionFactory.setPort(port);
        connectionFactory.setUsername(userName);
        connectionFactory.setPassword(password);
        return connectionFactory;
    }

    @Bean
    public SimpleMessageListenerContainer modbusMessageContainer(WaMingQueueListener receiver,ConnectionFactory connectionFactory) throws AmqpException, IOException {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueueNames(queue_fromGw);
        container.setExposeListenerChannel(true);
//        container.setAcknowledgeMode(AcknowledgeMode.MANUAL);//设置确认模式为手工确认
        container.setMessageListener(receiver);//监听处理类
        return container;
    }
}

4.监听类

@Component
public class WaMingQueueListener implements ChannelAwareMessageListener {
	@Override
	public void onMessage(Message message, Channel channel) throws Exception {
		try {
			String msg = new String(message.getBody());
			log.info("device_message received[WaMing] :" + msg);
		} catch (Exception e) {
			log.error("process message err:", e);
		}
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值