springboot2.0 连接rabbitmq处理消息

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/ifrozen/article/details/79962962

1. 引入rabbitmq的starter

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

2. 配置rabbitmq连接

spring:
  rabbitmq:
    host: ${rabbitmq.host}
    port: ${rabbitmq.port}
    username: ${rabbitmq.i5x.username}
    password: ${rabbitmq.i5x.password}
    virtual-host: ${rabbitmq.i5x.vhost}

3. rabbitmq发消息

注入RabbitTemplate

@Autowired
private RabbitTemplate rabbitTemplate;

利用convertAndSend方法发消息即可

@Override
public void convertAndSend(String exchange, String routingKey, final Object message,
        final MessagePostProcessor messagePostProcessor) throws AmqpException {
    convertAndSend(exchange, routingKey, message, messagePostProcessor, null);
}

4. rabbitmq监听队列,接收消息

@RabbitListener:声明监听的队列等信息,也可以通过bindings新创建一个队列并监听之。
@RabbitHandler:写在方法上,可以根据不同的消息类型匹配不同的处理方法

@Component
@RabbitListener(bindings = @QueueBinding(
                value = @Queue(value = "${websocket.rabbitmq.queue.kanjia.name}", autoDelete = "true"),
                exchange = @Exchange(value = "${websocket.rabbitmq.exchange.topic}", type = ExchangeTypes.TOPIC, durable="true"),
                key = "${websocket.rabbitmq.queue.kanjia.routing-key}")
                )
public class RabbitMqKanJiaMsgReceiver {

    @RabbitHandler
    public void processMsg(String msg) {
        System.out.println(msg);
    }

    @RabbitHandler
    public void processApiMessage(ApiMessage msg) {
        System.out.println(msg);
    }

}

@RabbitListener中的名称可以使用${}表达式来获取配置文件的值

不写@Component注解,在app的启动类上写@EnableRabbit注解也可以。

阅读更多
想对作者说点什么?

博主推荐

换一批

没有更多推荐了,返回首页