SpringBoot 集成 RabbitMQ 学习

SpringBoot 集成 RabbitMQ 学习

新建RabbitMQ环境

在linux服务器中通过docker快速搭建RabbtMQ服务
查询rabbitMQ镜像:

management版本,不指定默认为最新版本latest

 docker search rabbitmq:management

但因为我的镜像地址出现问题,报错

docker search rabbitmq:management
Error response from daemon: Get "https://index.docker.io/v1/search?q=rabbitmq%3Amanagement&n=25": dial tcp: lookup index.docker.io on [::1]:53: read udp [::1]:39632->[::1]:53: read: connection refused

一开始以为是自己的镜像地址出问题,后面尝试多边终于在网上找到解决办法

vi /etc/resolv.conf 

再文本中追加

nameserver 8.8.4.4
nameserver 8.8.8.8

此处贴出链接:
https://blog.csdn.net/qq_43416157/article/details/116788106

docker pull rabbitmq:management

拉取
Docker容器操作:
ok,上面命令执行后,镜像就已经拉取到本地仓库了,然后可以进行容器操作,启动rabbitMQ

docker run -d -p 5672:5672 -p 15672:15672 --restart=always --name rabbitmq rabbitmq:management

-d 后台运行
-p 隐射端口
–name 指定rabbitMQ名称
-e RABBITMQ_DEFAULT_USER 指定用户账号
-e RABBITMQ_DEFAULT_PASS 指定账号密码

执行如上命令后访问:http://ip:15672/
默认账号密码:guest/guest
rabbitmq manager 页面
至此,RabbitMQ 的环境已经搭建完毕

搭建SpringBoot 服务

配置文件
  1. pom.xml
<!-- rabbit-mq -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
  1. application.yml
spring:
  rabbitmq:
    host: localhost
    port: 5672
    username: guest
    password: guest
    virtual-host: /
    listener:
      simple:
        acknowledge-mode: manual # 手动应答
        concurrency: 5 # 消费端最小并发数
        max-concurrency: 10 # 消费端最大并发数
        prefetch: 5 # 一次请求中预处理的消息数量
    cache:
      channel:
        size: 50 # 缓存的channel数量
### 自定义配置
mq:
  defaultExchange: amqpExchange # 默认交换器
  queue: queue # 队列名
  routeKey: queue_key # 路由key
  1. MQProperties
@Component
@ConfigurationProperties(prefix = "mq")
public class MQProperties {
    private String defaultExchange;
    private String routeKey;
    private String queue;

    public String getDefaultExchange() {
        return defaultExchange;
    }

    public void setDefaultExchange(String defaultExchange) {
        this.defaultExchange = defaultExchange;
    }

    public String getRouteKey() {
        return routeKey;
    }

    public void setRouteKey(String routeKey) {
        this.routeKey = routeKey;
    }

    public String getQueue() {
        return queue;
    }

    public void setQueue(String queue) {
        this.queue = queue;
    }
}
  1. RabbitMQ配置
@Configuration
@EnableRabbit
public class RabbitMQConfig {
    @Autowired
    private MQProperties mqProperties;

    @Bean
    public Queue queue() {
        boolean durable = true;
        boolean exclusive = false;
        boolean autoDelete = false;
        return new Queue(mqProperties.getQueue(), durable, exclusive, autoDelete);
    }

    @Bean
    public DirectExchange defaultExchange() {
        boolean durable = true;
        boolean autoDelete = false;
        return new DirectExchange(mqProperties.getDefaultExchange(), durable, autoDelete);
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue())
                .to(defaultExchange())
                .with(mqProperties.getRouteKey());
    }
}
  1. RabbitMQ生产者
@RunWith(SpringRunner.class)
@SpringBootTest
public class RabbitMQTest {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private MQProperties mqProperties;

    @Test
    public void testSendMessage() {
        rabbitTemplate.convertAndSend(mqProperties.getDefaultExchange(), 
	        mqProperties.getRouteKey(), "发送了一条信息");
    }
}
  1. RabbitMQ消费者
@Service
public class RabbitMQService {
    private static final Logger LOGGER = LoggerFactory.getLogger(RabbitMQService.class);

    @RabbitListener(queues = "${mq.queue}")
    public void receive(String payload, Channel channel,
                        @Header(AmqpHeaders.DELIVERY_TAG) long tag) {
        LOGGER.info("消费内容为:{}", payload);
        RabbitMQUtils.askMessage(channel, tag, LOGGER);
    }
}
  1. 手动应答简单工具类
public final class RabbitMQUtils {

    public static void askMessage(Channel channel, long tag, final Logger logger) {
        askMessage(channel, tag, logger, false);
    }

    public static void askMessage(Channel channel, long tag, final Logger logger, boolean multiple) {
        try {
            channel.basicAck(tag, multiple);
        } catch (IOException e) {
            logger.error("RabbitMQ,IO异常,异常原因为:{}", e.getMessage());
        }
    }

    public static void rejectMessage(Channel channel, long tag, final Logger logger) {
        rejectMessage(channel, tag, logger, false, false);
    }

    public static void rejectAndBackMQ(Channel channel, long tag, final Logger logger) {
        rejectMessage(channel, tag, logger, false, true);
    }

    public static void rejectMessage(Channel channel, long tag, final Logger logger, boolean multiple, boolean request) {
        try {
            channel.basicNack(tag, multiple, request);
        } catch (IOException e) {
            logger.error("RabbitMQ,IO异常,异常原因为:{}", e.getMessage());
        }
    }
}

参考资料:https://www.cnblogs.com/switchvov/p/15070110.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值