【RabbitMQ】SpringBoot整合RabbitMQ

对于RabbitMQ的开发,Spring方法提供了更为方便的操作.

Spring官网介绍: Spring AMQP

RabbitMQ官网介绍: RabbitMQ tutorial - "Hello World!" | RabbitMQ


引入依赖

为了方便测试也引入SpringWeb依赖.

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

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.amqp</groupId>
            <artifactId>spring-rabbit-test</artifactId>
            <scope>test</scope>
        </dependency>
  </dependencies>

添加配置

#配置RabbitMQ的基本信息
spring:
  rabbitmq:
    host:  # IP地址
    port: 5672 #端口号 默认5672
    username:  #用户名
    password:  #密码
    virtual-host: #虚拟主机
    # 以上写法也可以整合成下面这种写法
    # addresses: amqp://用户名:密码@IP地址:端口号/虚拟主机

工作模式代码

相关常量

public class Constants {
    //工作队列模式
    public static final String WORK_QUEUE = "work.queue";
}

相关配置

import com.example.rabbitmqspringboot.constant.Constants;
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 {
    // 工作队列模式
    // 工作队列交给Spring管理
    @Bean("workQueue")
    public Queue workQueue(){
        return QueueBuilder.durable(Constants.WORK_QUEUE).build();
    }
}

生产者

import com.example.rabbitmqspringboot.constant.Constants;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/producer")
@RestController
public class ProducerController {
    // 引入RabbitTemplate 这是Spring Boot提供的RabbitMQ客户端相关操作
    @Autowired
    private RabbitTemplate rabbitTemplate;

    // 工作模式的生产者代码
    @RequestMapping("/work")
    public String work(){
        for (in
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值