使用RabbitMQ异步执行业务

文章目录

使用RabbitMQ异步执行业务

1.导入依赖
<!-- 引入RabbitMq依赖 -->
<dependency>
	<groupId>org.springframework.boot</groupId>
	<artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
2.编写RabbitMQ配置文件
# rabbitmq配置
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=root
spring.rabbitmq.password=root
spring.rabbitmq.virtual-host=/handsomeforum
# 手动指定ack
spring.rabbitmq.listener.simple.acknowledge-mode=manual
# 开启confirm机制
spring.rabbitmq.publisher-confirm-type=simple
# 开启return机制
spring.rabbitmq.publisher-returns=true
3.编写RabbitMQ配置类
package com.handsome.rabbitmq;

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author Handsome
 * @Date 2022/7/4 10:12
 * @Version 1.0
 */
@SuppressWarnings({"all"})
	@Configuration
	public class RabbitMQConfig {
	// 1.创建交换机
	@Bean
		public TopicExchange getTopicExchange() {
		return new TopicExchange("handsomeforum-topic-exchange", true, false);
	}

	// 2.创建队列
	@Bean
		public Queue getQueue() {
		return new Queue("handsomeforum-queue", true, false, false, null);
	}

	// 3.将交换机和队列绑定在一起
	@Bean
		public Binding getBinding() {
		return BindingBuilder.bind(getQueue()).to(getTopicExchange()).with("handsomeforum.*");
	}

}
4.设置Return和Confirm机制
package com.handsome.rabbitmq;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.connection.CorrelationData;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;

/**
 * @Author Handsome
 * @Date 2022/7/4 12:11
 * @Version 1.0
 */
@SuppressWarnings({"all"})
@Component
@Slf4j
public class PublisherConfirmAndReturnConfig implements RabbitTemplate.ConfirmCallback, RabbitTemplate.ReturnCallback {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @PostConstruct
    private void initMethod() {
        rabbitTemplate.setConfirmCallback(this);
        rabbitTemplate.setReturnCallback(this);
    }

    @Override
    public void confirm(CorrelationData correlationData, boolean ack, String cause) {
        if (ack) {
            log.info("消息已经送到Exchange中~");
        } else {
            log.error("消息没有送到Exchange中~");
        }
    }

    @Override
    public void returnedMessage(Message message, int replyCode, String replyText, String exchange, String routingKey) {
        log.error("消息没有送到Queue中~");
    }
}
5.将消息发送到交换机
// 发消息给mq异步更新文章浏览量
Map mqMap = new HashMap<>();
mqMap.put("bid", bid);
rabbitTemplate.convertAndSend("handsomeforum-topic-exchange",
"handsomeforum.readblog",
JSONObject.toJSONString(mqMap));
6.消费者消费消息
package com.handsome.rabbitmq;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.handsome.pojo.Blog;
import com.handsome.pojo.Question;
import com.handsome.pojo.UserLogin;
import com.handsome.service.BlogService;
import com.handsome.service.QuestionService;
import com.handsome.service.UserLoginService;
import com.handsome.service.VerifyMailboxService;
import com.handsome.utils.HandsomeUtils;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import javax.mail.internet.MimeMessage;
import java.io.IOException;

/**
 * @Author Handsome
 * @Date 2022/7/4 10:24
 * @Version 1.0
 */
@SuppressWarnings({"all"})
@Component
@Slf4j
public class Consumer {

    // 配置文件中取值
    @Value(value = "${handsome.myMailbox}")
    private String myMailbox;

    @Autowired
    JavaMailSenderImpl mailSender;
    @Autowired
    VerifyMailboxService verifyMailboxService;

    @Autowired
    UserLoginService userLoginService;
    @Autowired
    BlogService blogService;
    @Autowired
    QuestionService questionService;

    // 自动ack
//    @RabbitListener(queues = "handsomeforum-queue")
//    public void getMessage(Object message) {
//        System.out.println("接收到的消息->" + message);
//    }

    @RabbitListener(queues = "handsomeforum-queue")
    public void getMessage(@Payload String msg, Channel channel, Message message) throws IOException {
        // 1.获取routingKey
        String routingKey = message.getMessageProperties().getReceivedRoutingKey();
        // 2.使用switch
        switch (routingKey) {
            // 更新文章浏览量
            case "handsomeforum.readblog":
                JSONObject readblogObject = JSON.parseObject(msg);
                String bid = (String) readblogObject.get("bid");
                Blog blog = blogService.getOne(new QueryWrapper<Blog>().eq("bid", bid));
                blog.setViews(blog.getViews() + 1);
                // todo: redis缓存. 防止阅读重复
                blogService.updateById(blog);
                // 手动ack       channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                break;
        }
    }
}
7.RabbitMQ的作用

RabbitMQ即一个消息队列,主要是用来实现应用程序的异步和解耦,同时也能起到消息缓冲,消息分发的作用。
使用RabbitMQ实现异步更新文章浏览量,提升阅读文章时的响应速度。从直接更新数据库耗时450ms到异步更新数据库耗时50ms,明显提升接口性能,非常的nice~

RabbitMq忘记用户名和密码怎么办?

1.启动RabbitMq容器

2.进入RabbitMq容器

3.创建账号

rabbitmqctl add_user newadmin newpassword
4.设置用户角色

rabbitmqctl set_user_tags newadmin administrator
5.设置用户权限

rabbitmqctl set_permissions -p / newadmin "." "." ".*"
6.newadmin为新管理员账号 newpassword为密码 进行登录

7.登录成功

8.找回原用户名

9.更新root用户密码

10.用root用户登录

11.删除newadmin用户

12.成功找回root用户,非常非常的nice~

我的学习论坛

HandsomeForum:用Java编写的学习论坛,打造我们自己的圈子!(http://huangjunjie.vip:66)
文章链接(使用RabbitMQ异步执行业务):http://huangjunjie.vip:66/blog/read/66incxp18s5nfhqgwt
文章链接(RabbitMq忘记用户名和密码怎么办?):http://huangjunjie.vip:66/question/read/0y4jzhrj5ipdu86wd1

### RabbitMQ异步消息处理实现方式 RabbitMQ 是一种强大的消息队列系统,能够支持多种异步消息传递场景。其核心理念在于通过生产者-消费者模型分离任务的创建与执行过程[^5]。 #### 生产者端:发送消息至队列 在 RabbitMQ 中,生产者负责向指定队列发送消息。以下是基于 Spring Boot 集成 RabbitMQ 的简单示例代码: ```java import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class MessageProducer { @Autowired private RabbitTemplate rabbitTemplate; public void sendMessage(String queueName, String message) { rabbitTemplate.convertAndSend(queueName, message); System.out.println("Sent message: " + message); } } ``` 上述代码展示了如何利用 `RabbitTemplate` 将一条消息发送到指定队列中[^4]。 #### 消费者端:接收并处理消息 消费者通过监听特定队列中的消息来进行后续操作。以下是一个典型的消费者实现示例: ```java import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Component; @Component public class MessageConsumer { @RabbitListener(queues = "exampleQueue") public void handleMessage(String message) { System.out.println("Received message: " + message); // 对接收到的消息进行业务逻辑处理 } } ``` 此代码片段说明了如何使用 `@RabbitListener` 注解绑定一个队列,并定义回调函数用于处理接收到的消息。 #### 负载均衡的任务调度 当存在多个消费者实例时,RabbitMQ 可自动分配任务给不同的消费者节点,从而达到负载均衡的效果。这种特性非常适合于大规模分布式系统的任务分发场景[^2]。 #### 处理异常情况下的事务和确认机制 为了保障消息投递的成功率,RabbitMQ 提供了事务及手动应答模式等功能。例如,在消费失败的情况下可以选择重新入队或者丢弃该条记录;而对于重要程度较高的业务,则建议启用持久化存储选项以防止因服务崩溃而导致的数据丢失现象发生。 ### 总结 综上所述,借助 RabbitMQ 我们可以很方便地搭建起一套完整的异步消息通信框架,无论是简单的通知推送还是复杂的工作流编排都能得到良好支持[^3]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值