RabbitMq(八) SpringBoot整合RabbitMQ 生产者代码实现

在本章中我们将创建RabbitMQ的生产者工程,并实现生产者端代码实现。

springboot整合RabbitMQ生产者工程步骤如下:

  1. 创建maven工程
  2. 引入springboot及RabbitMQ依赖
  3. 创建SpringBoot启动类
  4. 添加配置文件
  5. 编写RabbitMQ配置类
  6. 编写发送消息类或者单元测试类

一、创建maven工程以及添加主要依赖。

创建maven工程略过,springboot工程我们首先需要加入parent标签指明为SpringBoot工程,然后我们引入amqp的starter。我们使用web工程接收url参数请求进行调用发送消息,所以同时也引入了starter-web。pom整体代码如下:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.xiaohui.mqconsumer</groupId>
    <artifactId>MqConsumer</artifactId>
    <version>1.0-SNAPSHOT</version>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.1.4.RELEASE</version>
    </parent>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
    </dependencies>

</project>

二、创建SpringBoot启动类

创建SpringBoot启动类,并创建main函数,函数内部使用SpringApplication.run 函数进行运行启动,类需要添加SpringBootApplication注解,代码如下:

package com.xiaohui.rabbitmq;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * 生产者启动类
 */
@SpringBootApplication
public class ProducerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProducerApplication.class,args);
    }
}

三、添加SpringBoot配置文件application.properties

添加配置文件指明项目启动的web端口,以及RabbitMQ的服务端以及用户信息。配置代码如下:

#端口
server.port=8888
#rabbitMq配置
spring.rabbitmq.host=172.18.255.54
spring.rabbitmq.port=5672
spring.rabbitmq.virtual-host=/myhost
spring.rabbitmq.username=xiaohui
spring.rabbitmq.password=root

四、编写RabbitMQ的配置类

在rabbitMq配置类中我们进行声明消息队列、交换机,以及将消息队列绑定交换机以及路由信息。其中需要注意不要王杰配置类注解@Configuration,以及内部绑定函数注解@Bean。配置类代码如下:

package com.xiaohui.rabbitmq.config;


import org.springframework.amqp.core.*;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMqConfig {

    //交换机名称
    public static final String ITEM_TOPIC_EXCHANGE = "item_topic_exchange";
    //队列名称
    public static final String ITEM_QUEUE = "item_queue";

    //声明交换机
    @Bean("itemTopicExchange")
    public Exchange topicExchange(){
        return ExchangeBuilder.topicExchange(ITEM_TOPIC_EXCHANGE).durable(true).build();
    }

    //声明队列
    @Bean("itemQueue")
    public Queue itemQueue(){
        return QueueBuilder.durable(ITEM_QUEUE).build();
    }

    //绑定队列和交换机
    @Bean
    public Binding itemQueueExchage(@Qualifier("itemQueue")Queue itemQueue,
                                    @Qualifier("itemTopicExchange")Exchange itemTopicExchange){
        return BindingBuilder.bind(itemQueue).to(itemTopicExchange).with("item.#").noargs();
    }

}

五、编写web模块代码实现通过url请求发送消息

创建Controller代码以及一个请求方法,并指明消息的发送路径以及参数(消息内容以及路由key)。使用到的注解有@RestController、@Getmapping、@RequestParam 。在webController中我们注入RabbitMQ的RabbitTemplate对象进行返送消息。使用其主要方法:

org.springframework.amqp.rabbit.core.RabbitTemplate#convertAndSend(java.lang.String, java.lang.String, java.lang.Object)。

其代码如下:

package com.xiaohui.rabbitmq.controller;

import com.xiaohui.rabbitmq.config.RabbitMqConfig;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MsgController {


    @Autowired
    RabbitTemplate rabbitTemplate;

    @GetMapping("/sendMsg")
    public String sendMsg(@RequestParam String msg,@RequestParam String key){

        rabbitTemplate.convertAndSend(RabbitMqConfig.ITEM_TOPIC_EXCHANGE,key,msg);

        return "消息发送成功!";
    }
}

至此,SpringBoot整合RabbitMQ生产者代码全部实现完毕,消费者整合请看下一篇文章,整体项目工程目录如下:

### PyCharm 打开文件显示全的解决方案 当遇到PyCharm打开文件显示全的情况时,可以尝试以下几种方法来解决问题。 #### 方法一:清理缓存并重启IDE 有时IDE内部缓存可能导致文件加载异常。通过清除缓存再启动程序能够有效改善此状况。具体操作路径为`File -> Invalidate Caches / Restart...`,之后按照提示完成相应动作即可[^1]。 #### 方法二:调整编辑器字体设置 如果是因为字体原因造成的内容显示问题,则可以通过修改编辑区内的文字样式来进行修复。进入`Settings/Preferences | Editor | Font`选项卡内更改合适的字号大小以及启用抗锯齿功能等参数配置[^2]。 #### 方法三:检查项目结构配置 对于某些特定场景下的源码视图缺失现象,可能是由于当前工作空间未能正确识别全部模块所引起。此时应该核查Project Structure的Content Roots设定项是否涵盖了整个工程根目录;必要时可手动添加遗漏部分,并保存变更生效[^3]。 ```python # 示例代码用于展示如何获取当前项目的根路径,在实际应用中可根据需求调用该函数辅助排查问题 import os def get_project_root(): current_file = os.path.abspath(__file__) project_dir = os.path.dirname(current_file) while not os.path.exists(os.path.join(project_dir, '.idea')): parent_dir = os.path.dirname(project_dir) if parent_dir == project_dir: break project_dir = parent_dir return project_dir print(f"Current Project Root Directory is {get_project_root()}") ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值