SpringBoot监听RabbitMQ消息

阿里 阅读:647 2021-04-01 11:07:23 评论:0

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); 
		} 
	} 
} 
标签:RabbitMQ
声明

1.本站遵循行业规范,任何转载的稿件都会明确标注作者和来源;2.本站的原创文章,请转载时务必注明文章作者和来源,不尊重原创的行为我们将追究责任;3.作者投稿可能会经我们编辑修改或补充。

关注我们

一个IT知识分享的公众号