springboot引入rabbit mq

spring boot 集成 rabbit mq

第一步引入springboot 依赖
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-amqp</artifactId>
        </dependency>
第二步添加rabbitmq配置
spring:
  rabbitmq:
    host: 127.0.0.1
    port: 17004
    username: admin
    password: ******
    virtual-host: /nonauto
    exchange: EX_ZY_PROPOSALSTATUS
    routingKey: ZY_PROPOSALSTATUS
    queue: Q_ZY_PROPOSALSTATUS
第三步添加rabbitmq配置类
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.amqp.core.Queue;
/**
 * @ClassName RabbitConfig
 * @Description rabbit mq 配置类
 * @Author God丶Man
 * @Date 2022/3/19 11:13
 * @Version 1.0
 **/
@Configuration
public class RabbitConfig {

    @Value("${spring.rabbitmq.exchange}")
    private String exchange;
    @Value("${spring.rabbitmq.routingKey}")
    private String routingKey;
    @Value("${spring.rabbitmq.queue}")
    private String queue;


    @Bean
    public Queue proposalQueue() {
        return new Queue(queue, true);
    }


    @Bean
    public DirectExchange proposalExchange() {
        return new DirectExchange(exchange, true, false);
    }

    @Bean
    public Binding bindingDirect() {
        return BindingBuilder.bind(proposalQueue()).to(proposalExchange()).with(routingKey);
    }
}

第四步消息生产者消费者测试类
import cn.hutool.json.JSONUtil;
import com.dh.marketplatform.vehicle.BaseTest;
import org.junit.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName RabbitMqTest
 * @Description 消息生产者测试类
 * @Author God丶Man
 * @Date 2022/3/19 11:31
 * @Version 1.0
 **/
public class RabbitMqTest extends BaseTest {

    @Autowired
    private RabbitTemplate rabbitTemplate;


    @Test
    public void testMq() {
        // 发送消息 商业险
        Map<String, Object> paramMap = getStringObjectMap();

        String reqStr = JSONUtil.toJsonStr(paramMap);
        System.out.println(reqStr);
        /**
         * Convert a Java object to an Amqp {@link Message} and send it to a specific exchange
         * with a specific routing key.
         *
         * @param exchange the name of the exchange
         * @param routingKey the routing key
         * @param message a message to send
         * @throws AmqpException if there is a problem
         */
        rabbitTemplate.convertAndSend("EX_ZY_PROPOSALSTATUS", "ZY_PROPOSALSTATUS", reqStr);
    }

    private Map<String, Object> getStringObjectMap() {
        Map<String,Object> paramMap = new HashMap<>();
        paramMap.put("proposalNo","110250020221230000003");
        paramMap.put("proposalStatus","0");
        paramMap.put("riskCode","1230");
        return paramMap;
    }

}
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @ClassName RabbitMq
 * @Description 消息消费者测试类
 * @Author God丶Man
 * @Date 2022/3/19 11:33
 * @Version 1.0
 **/
@Component
@Slf4j
public class RabbitMqConsumer {


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "${spring.rabbitmq.queue}", autoDelete = "false"),
            exchange = @Exchange(value = "${spring.rabbitmq.exchange}")
    ))
    public void messagerevice(String message) {
        log.info("========接受消息打印: " + message);
    }

}

### Spring Boot与RabbitMQ集成教程及配置实例 #### 配置依赖项 为了使Spring Boot应用程序能够与RabbitMQ交互,需在项目的`pom.xml`文件中加入必要的依赖。这通常涉及引入Spring Boot Starter for AMQP以及可能的其他相关组件。 ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-amqp</artifactId> </dependency> ``` 此操作确保了项目具备处理AMQP协议的能力,从而可以顺利连接到像RabbitMQ这样的消息代理服务[^1]。 #### 应用程序属性设置 接着,在`application.properties`或`application.yml`文件内指定RabbitMQ服务器的具体参数,如主机地址、端口、用户名和密码等基本信息。 对于`.properties`格式: ```properties spring.rabbitmq.host=localhost spring.rabbitmq.port=5672 spring.rabbitmq.username=guest spring.rabbitmq.password=guest ``` 而对于`.yml`格式,则如下所示: ```yaml spring: rabbitmq: host: localhost port: 5672 username: guest password: guest ``` 这些设定允许应用轻松接入本地运行的默认配置下的RabbitMQ实例。 #### 创建监听器类 定义一个简单的消息监听器来接收来自队列的消息。这里展示了一个基本的例子,其中包含了如何声明队列并绑定至交换机的方法。 ```java import org.springframework.amqp.core.Queue; import org.springframework.context.annotation.Bean; import org.springframework.stereotype.Component; @Component public class RabbitConfig { @Bean public Queue helloQueue() { return new Queue("hello"); } } ``` 上述代码片段展示了创建名为“hello”的队列的过程;而下面的部分则实现了实际的消息处理器逻辑。 ```java import org.springframework.amqp.rabbit.annotation.RabbitListener; import org.springframework.stereotype.Service; @Service public class Receiver { @RabbitListener(queues = "hello") public void receive(String in) throws Exception { System.out.println(" [x] Received '" + in + "'"); } } ``` 这段Java代码利用了`@RabbitListener`注解来标记方法作为特定队列上的消费者角色,每当有新消息到达时便会触发相应的业务处理流程。 #### 发送消息给队列 最后一步就是编写发送方代码,负责向目标队列推送数据包。此处提供了一种简易的方式实现这一点——通过注入`AmqpTemplate`接口完成消息投递动作。 ```java import org.springframework.amqp.AmqpException; import org.springframework.amqp.rabbit.connection.CachingConnectionFactory; import org.springframework.amqp.rabbit.core.RabbitTemplate; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; @Component public class Sender { private final RabbitTemplate rabbitTemplate; @Autowired public Sender(CachingConnectionFactory connectionFactory) { this.rabbitTemplate = new RabbitTemplate(connectionFactory); } @Scheduled(fixedRate = 5000) public void send() { String message = "Hello, World!"; try { rabbitTemplate.convertAndSend("hello", message); System.out.println("[x] Sent '" + message + "'"); } catch (AmqpException e) { e.printStackTrace(); } } } ``` 以上示例中的定时任务每隔五秒就会尝试往名称为“hello”的队列里放入一条字符串形式的信息,并打印确认日志。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值