SpringBoot监听RabbitMQ消息

1.pom文件

	
			org.springframework.boot
			spring-boot-starter-amqp
	

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);
		}
	}
}

你可能感兴趣的:(java,java,后端)