springboot整合 rabbitmq

本文详细介绍了如何在Spring Boot项目中整合RabbitMQ,包括设置配置、创建队列与交换机、实现工作模型、发布订阅模型、主题模型,以及确认和回报机制。通过在线-project和online-coupon服务的实例,展示了消息的发送与消费,并提供了监听类以接收不同类型的事件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

项目地址(gitee): https://gitee.com/qinenqi/online
springboot整合rabbitmq
小编参考rabbitmq
整合进自己的cloud系统,在此对 孔明1号 博主进行感谢
online-project 作为生产者
online-coupon 作为消费者

  1. online-common在公共服务中引入依赖
  <!-- rabbitMQ -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
  1. 在 online-project 、online-coupon服务的配置文件中 添加

# rabbitmq配置信息
# ip
spring.rabbitmq.host=127.0.0.1
# 端口
spring.rabbitmq.port=5672
# 用户名
spring.rabbitmq.username=guest
# 密码
spring.rabbitmq.password=guest
# 配置虚拟机
spring.rabbitmq.virtual-host=/
# 消息开启手动确认
spring.rabbitmq.listener.direct.acknowledge-mode=manual


# confirm机制   开启消息确认机制 confirm 异步
spring.rabbitmq.publisher-confirm-type=correlated
# 之前的旧版本 开启消息确认机制的方式
# spring.rabbitmq.publisher-confirms=true



# return机制  开启return机制
spring.rabbitmq.publisher-returns=true
  1. 新建 RabbitmqConfig ,rabbitmq的配置类
import org.springframework.amqp.core.*;
import org.springframework.boot.SpringBootConfiguration;
import org.springframework.context.annotation.Bean;

@SpringBootConfiguration
public class RabbitmqConfig {

    /**
     *  配置一个工作模型队列
     * @return
     */
    @Bean
    public Queue queueWork1() {
        return new Queue("queue_work");
    }


    /**
     *  发布订阅模式
     *  声明两个队列
     * @return
     */
    @Bean
    public Queue queueFanout1() {
        return new Queue("queue_fanout1");
    }
    @Bean
    public Queue queueFanout2() {
        return new Queue("queue_fanout2");
    }
    // 准备一个交换机
    @Bean
    public FanoutExchange exchangeFanout() {
        return new FanoutExchange("exchange_fanout");
    }

    /**
     *  将队列绑定到交换机上
     * @return
     */
    @Bean
    public Binding bindingExchange1() {
        Queue queue = queueFanout1();
        return BindingBuilder.bind(queue).to(exchangeFanout());
    }

    @Bean
    public Binding bindingExchange2() {
        Queue queue = queueFanout2();
        return BindingBuilder.bind(queue).to(exchangeFanout());
    }


    /**
     *  topic 模型
     * @return
     */
    @Bean
    public Queue queueTopic1() {
        return new Queue("queue_topic1");
    }
    @Bean
    public Queue queueTopic2() {
        return new Queue("queue_topic2");
    }
    @Bean
    public TopicExchange exchangeTopic() {
        return new TopicExchange("exchange_topic");
    }
    @Bean
    public Binding bindingTopic1() {
        Queue queue = queueTopic1();
        return BindingBuilder.bind(queue).to(exchangeTopic()).with("topic.#");
    }
    @Bean
    public Binding bindingTopic2() {
        Queue queue = queueTopic2();
        return BindingBuilder.bind(queue).to(exchangeTopic()).with("topic.*");
    }



    /**
     *  confirm机制
     *  测试confirm 机制,专门创建了一个队列
     * @return
     */
    @Bean
    public Queue queueConfirm() {
        return new Queue("queue_confirm");
    }



    /**
     *  return机制
     * @return
     */
    @Bean
    public Queue queueReturn() {
        return new Queue("queue_return");
    }
    @Bean
    public TopicExchange exchangeReturn() {
        return new TopicExchange("exchange_return");
    }
    @Bean
    public Binding bindingReturn() {
        Queue queue = queueReturn();
        return BindingBuilder.bind(queue).to(exchangeReturn()).with("return.*");
    }

}
  1. 在 online-project 新建 RabbitmqController RabbitmqService 和 RabbitmqServiceImpl

import com.example.onlineproject.service.RabbitmqService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/rabbitmqController")
public class RabbitmqController {
    @Autowired
    private RabbitmqService rabbitmqService;

    /**
     * work模型
     * @return
     */
    @RequestMapping("/sendWork")
    public Object sendWork() {
        rabbitmqService.sendWork();
        return "发送成功...";
    }

    /**
     *  发布订阅模型
     * @return
     */
    @RequestMapping("/sendPublish")
    public String sendPublish() {
        rabbitmqService.sendPublish();
        return "发送成功...";
    }

    /**
     *  topic模型
     * @return
     */
    @RequestMapping("/sendTopic")
    public String sendTopic() {
        rabbitmqService.sendTopic();
        return "发送成功...";
    }

    /**
     *  confirm机制
     * @return
     */
    @RequestMapping("/sendConfirm")
    public String sendConfirm() {
        rabbitmqService.sendConfirm();
        return "发送成功...";
    }


    /**
     *  return机制
     * @return
     */
    @RequestMapping("/sendReturn")
    public String sendReturn() {
        rabbitmqService.sendReturn();
        return "发送成功...";
    }



}

public interface RabbitmqService {

    public void sendWork();

    public void sendPublish();

    public void sendTopic();

    public void sendConfirm();

    public void sendReturn();
}


import com.example.onlinecommon.entry.User;
import com.example.onlineproject.mapper.RabbitmqMapper;
import com.example.onlineproject.service.RabbitmqService;
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.Service;

@Service
@Slf4j
public class RabbitmqServiceImpl implements RabbitmqService {

    @Autowired
    private RabbitmqMapper rabbitmqMapper;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Override
    public void sendWork() {
        for (int i = 0; i < 10; i++) {
            rabbitTemplate.convertAndSend("queue_work", "测试work模型: " + i);
        }
    }

    @Override
    public void sendPublish() {
        for (int i = 0; i < 5; i++) {
            rabbitTemplate.convertAndSend("exchange_fanout", "", "测试发布订阅模型:" + i);
        }
    }

    @Override
    public void sendTopic() {
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                rabbitTemplate.convertSendAndReceive("exchange_topic", "topic.km.topic", "测试发布订阅模型:" + i);
            } else {
                rabbitTemplate.convertSendAndReceive("exchange_topic", "topic.km", "测试发布订阅模型:" + i);

            }
        }
    }


    @Override
    public void sendConfirm() {
        rabbitTemplate.convertAndSend("queue_confirm", new User(1, "km", "km123"), new CorrelationData("" + System.currentTimeMillis()));
        rabbitTemplate.setConfirmCallback(confirmCallback);
    }
    // 配置 confirm 机制
    private final RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() {
        /**
         * @param correlationData 消息相关的数据,一般用于获取 唯一标识 id
         * @param b true 消息确认成功,false 失败
         * @param s 确认失败的原因
         */
        @Override
        public void confirm(CorrelationData correlationData, boolean b, String s) {
            if (b) {
                System.out.println("confirm 消息确认成功..." + correlationData.getId());
            } else {
                System.out.println("confirm 消息确认失败..." + correlationData.getId() + " cause: " + s);
            }
        }
    };


    @Override
    public void sendReturn() {
        rabbitTemplate.setReturnCallback(returnCallback);
        rabbitTemplate.convertAndSend("exchange_return", "return.km.km", "测试 return 机制");
    }

    // 配置 return 消息机制
    private final RabbitTemplate.ReturnCallback returnCallback = new RabbitTemplate.ReturnCallback() {
        /**
         *  return 的回调方法(找不到路由才会触发)
         * @param message 消息的相关信息
         * @param i 错误状态码
         * @param s 错误状态码对应的文本信息
         * @param s1 交换机的名字
         * @param s2 路由的key
         */
        @Override
        public void returnedMessage(Message message, int i, String s, String s1, String s2) {
            System.out.println(message);
            System.out.println(new String(message.getBody()));
            System.out.println(i);
            System.out.println(s);
            System.out.println(s1);
            System.out.println(s2);
        }
    };



}

  1. online-coupon 新建监听类 WorkReceiveListener TopicReceiveListener ReturnReceiveListener PublishReceiveListener ConfirmReceiveListener

import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
//import java.nio.channels.Channel;

// 2个消费者
@Component
public class WorkReceiveListener {

    @RabbitListener(queues = "queue_work")
    public void receiveMessage(String msg, Channel channel, Message message) {
        // 只包含发送的消息
        System.out.println("1接收到消息-coupon:" + msg);
        // channel 通道信息
        // message 附加的参数信息
    }

    @RabbitListener(queues = "queue_work")
    public void receiveMessage2(Object obj, Channel channel, Message message) {
        // 包含所有的信息
        System.out.println("2接收到消息-coupon:" + obj);
    }
}


import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


/**
 *  topic模型 监听
 */
@Component
public class TopicReceiveListener {

    @RabbitListener(queues = "queue_topic1")
    public void receiveMsg1(String msg) {
        System.out.println("消费者1接收到:" + msg);
    }

    @RabbitListener(queues = "queue_topic2")
    public void receiveMsg2(String msg) {
        System.out.println("消费者2接收到:" + msg);
    }
}

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class ReturnReceiveListener {

    @RabbitListener(queues = "queue_return")
    public void receiveMsg(String msg) {
        System.out.println("接收的消息为:" + msg);
    }
}


import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class PublishReceiveListener {

    @RabbitListener(queues = "queue_fanout1")
    public void receiveMsg1(String msg) {
        System.out.println("队列1接收到消息:" + msg);
    }

    @RabbitListener(queues = "queue_fanout2")
    public void receiveMsg2(String msg) {
        System.out.println("队列2接收到消息:" + msg);
    }
}

import com.example.onlinecommon.entry.User;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

@Component
public class ConfirmReceiveListener {

    @RabbitListener(queues = "queue_confirm")
    public void receiveMsg(User user) {
        System.out.println("接收到的消息为:" + user);
    }
}

  1. 请求接口(结合gateway 方式,请根据自己的情况进行修改)
    http://127.0.0.1:88/api/project/rabbitmqController/sendWork (work模型)
    http://127.0.0.1:88/api/project/rabbitmqController/sendPublish (发布订阅模型)
    http://127.0.0.1:88/api/project/rabbitmqController/sendTopic (topic模型)
    http://127.0.0.1:88/api/project/rabbitmqController/sendConfirm (confirm机制)
    http://127.0.0.1:88/api/project/rabbitmqController/sendReturn (return机制)
内容概要:本文深入探讨了Kotlin语言在函数式编程和跨平台开发方面的特性和优势,结合详细的代码案例,展示了Kotlin的核心技巧和应用场景。文章首先介绍了高阶函数和Lambda表达式的使用,解释了它们如何简化集合操作和回调函数处理。接着,详细讲解了Kotlin Multiplatform(KMP)的实现方式,包括共享模块的创建和平台特定模块的配置,展示了如何通过共享业务逻辑代码提高开发效率。最后,文章总结了Kotlin在Android开发、跨平台移动开发、后端开发和Web开发中的应用场景,并展望了其未来发展趋势,指出Kotlin将继续在函数式编程和跨平台开发领域不断完善和发展。; 适合人群:对函数式编程和跨平台开发感兴趣的开发者,尤其是有一定编程基础的Kotlin初学者和中级开发者。; 使用场景及目标:①理解Kotlin中高阶函数和Lambda表达式的使用方法及其在实际开发中的应用场景;②掌握Kotlin Multiplatform的实现方式,能够在多个平台上共享业务逻辑代码,提高开发效率;③了解Kotlin在不同开发领域的应用场景,为选择合适的技术栈提供参考。; 其他说明:本文不仅提供了理论知识,还结合了大量代码案例,帮助读者更好地理解和实践Kotlin的函数式编程特性和跨平台开发能力。建议读者在学习过程中动手实践代码案例,以加深理解和掌握。
内容概要:本文深入探讨了利用历史速度命令(HVC)增强仿射编队机动控制性能的方法。论文提出了HVC在仿射编队控制中的潜在价值,通过全面评估HVC对系统的影响,提出了易于测试的稳定性条件,并给出了延迟参数与跟踪误差关系的显式不等式。研究为两轮差动机器人(TWDRs)群提供了系统的协调编队机动控制方案,并通过9台TWDRs的仿真和实验验证了稳定性和综合性能改进。此外,文中还提供了详细的Python代码实现,涵盖仿射编队控制类、HVC增强、稳定性条件检查以及仿真实验。代码不仅实现了论文的核心思想,还扩展了邻居历史信息利用、动态拓扑优化和自适应控制等性能提升策略,更全面地反映了群体智能协作和性能优化思想。 适用人群:具备一定编程基础,对群体智能、机器人编队控制、时滞系统稳定性分析感兴趣的科研人员和工程师。 使用场景及目标:①理解HVC在仿射编队控制中的应用及其对系统性能的提升;②掌握仿射编队控制的具体实现方法,包括控制器设计、稳定性分析和仿真实验;③学习如何通过引入历史信息(如HVC)来优化群体智能系统的性能;④探索中性型时滞系统的稳定性条件及其在实际系统中的应用。 其他说明:此资源不仅提供了理论分析,还包括完整的Python代码实现,帮助读者从理论到实践全面掌握仿射编队控制技术。代码结构清晰,涵盖了从初始化配置、控制律设计到性能评估的各个环节,并提供了丰富的可视化工具,便于理解和分析系统性能。通过阅读和实践,读者可以深入了解HVC增强仿射编队控制的工作原理及其实际应用效果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值