栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringBoot和RabbitMQ整合

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringBoot和RabbitMQ整合

导入依赖

    org.springframework.boot
    spring-boot-starter-amqp
项目结构

编写yml文件
spring:
  rabbitmq:
#    地址
    host: 172.20.10.7
#    服务器端口
    port: 5672
#    账号
    username: guest
#    密码
    password: llh123456
#    SSL
    virtual-host: /
编写配置类
package com.guigu.www.springboot_rabbitmq.config;


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;

@Configuration
public class RabbitMQConfig {

    
    @Bean
    public Queue createQueue(){
        
        return new Queue("topics_springBoot");
    }

    
    @Bean
    public TopicExchange createTopicExchange(){
        
        return new TopicExchange("topics_springBoot_exchange");
    }

    
    @Bean
    public Binding binding(){
        
        return BindingBuilder.bind(createQueue()).to(createTopicExchange()).with("operation.#");
    }
}
编写接收者
package com.guigu.www.springboot_rabbitmq.consumer;

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

@Component
public class TopicsConsumer {
    
    @RabbitListener(queues = "topics_springBoot")
    public void ConsumerMassges(Object obj){
        System.out.println(obj);
    }
}

启动SpringBootRabbitmqApplication

测试发布者
package com.guigu.www.springboot_rabbitmq;

import org.junit.jupiter.api.Test;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.boot.test.context.SpringBootTest;

import javax.annotation.Resource;

@SpringBootTest
class SpringBootRabbitmqApplicationTests {

    @Resource
    private RabbitTemplate rabbitTemplate;

    @Test
    void contextLoads() {
        
        rabbitTemplate.convertAndSend("topics_springBoot_exchange","operation.delete","删除成功!!!");
    }

}
运行结果:

接收类:

org.springframework.amqp.core.Message

接受消息:

(Body:'删除成功!!!' MessageProperties [headers={}, contentType=text/plain, contentEncoding=UTF-8, contentLength=0, receivedDeliveryMode=PERSISTENT, priority=0, redelivered=false, receivedExchange=topics_springBoot_exchange, receivedRoutingKey=operation.delete, deliveryTag=1, consumerTag=amq.ctag-krNfa2dtQnyYFgJLZcmR-g, consumerQueue=topics_springBoot])
附上工程链接,仅供学习参考!!!

springBoot_rabbitmq.zip - 蓝奏云文件大小:94.4 K|https://llh317.lanzout.com/i7Lnfy9aibc

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/691164.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号