MyBatis+SpringMVC+SpringBootSpringboot核心技术SpringBoot极简教程 · Spring Boot

SpringBoot使用RabbitMQ

2018-09-08  本文已影响8人  褪色的记忆1994

1.引入rabbitmq依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
  1. 在application.yml中配置rabbitmq参数
spring:
  rabbitmq:
    host: xx.xx.xx.xx
    port: 5672
    username: xxxx
    password: xxxx
    virtual-host: /xxxx
    queue: xxx

其中host为rabbitmq的服务器地址,port为端口,username是用户名,password为密码,virtual-host为虚拟路径,queue为自定义的队列名称。

  1. 编写消息生产者
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class RabbitSender {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Value("${spring.rabbitmq.queue}")
    private String queue;

    public void send(String msg){
        amqpTemplate.convertAndSend(queue, msg);
    }
}

4.编写消息消费者

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class RabbitReceiver {

    private Logger logger = LoggerFactory.getLogger(RabbitReceiver.class);

    @RabbitListener(queues = "${spring.rabbitmq.queue}")
    @RabbitHandler
    public void process(byte[] msg){
        logger.info("msg:{}",new String(msg));
    }
}

个人博客:https://blog.xvjialing.xyz

github主页:https://github.com/xvjialing

微信公众号

微信公众号
上一篇下一篇

猜你喜欢

热点阅读