• 使用RabbitMQ异步执行业务


    文章目录

    使用RabbitMQ异步执行业务

    1.导入依赖
    
    
    	org.springframework.boot
    	spring-boot-starter-amqp
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    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
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    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.*");
    	}
    
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    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中~");
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    5.将消息发送到交换机
    // 发消息给mq异步更新文章浏览量
    Map mqMap = new HashMap<>();
    mqMap.put("bid", bid);
    rabbitTemplate.convertAndSend("handsomeforum-topic-exchange",
    "handsomeforum.readblog",
    JSONObject.toJSONString(mqMap));
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    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().eq("bid", bid));
                    blog.setViews(blog.getViews() + 1);
                    // todo: redis缓存. 防止阅读重复
                    blogService.updateById(blog);
                    // 手动ack       channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
                    break;
            }
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    7.RabbitMQ的作用

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

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

    1.启动RabbitMq容器

    2.进入RabbitMq容器

    3.创建账号

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

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

    rabbitmqctl set_permissions -p / newadmin "." "." ".*"
    
    • 1
    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

  • 相关阅读:
    性能与效果平衡:选择适合项目的直播实时美颜SDK
    【Scan Kit】集成扫码服务时Android Studio总是报错OOM如何解决?
    github知识小结(2022/08/07)
    [LNOI2022] 吃(数学+贪心)
    23. 从零用Rust编写正反向代理,流控小姐姐的温柔一刀!
    备份网络架构Host-Based/Lan-Based/Lan-Free/Server-Free
    YOLOv5-Shufflenetv2
    Linux多线程
    elementui 修改 el_table 表格颜色,表格下方多了一条线问题
    AI天后,在线飙歌,人工智能AI孙燕姿模型应用实践,复刻《遥远的歌》,原唱晴子(Python3.10)
  • 原文地址:https://blog.csdn.net/web_15534274656/article/details/126577264