SpringBoot 整合 RabbitMQ 使用topic交换机

依赖

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

配置文件

# 连接地址
spring.rabbitmq.host=127.0.0.1
# 端口号
spring.rabbitmq.port=5672
# 账号
spring.rabbitmq.username=guest
# 密码
spring.rabbitmq.password=guest
# 地址
spring.rabbitmq.virtual-host=myvh

# 消息开启手动确认
#spring.rabbitmq.listener.direct.acknowledge-mode=manual
#采取手动应答
#spring.rabbitmq.listener.simple.acknowledge-mode=manual
#支持重试
#spring.rabbitmq.listener.simple.retry.enabled=true
#最大重试次数
#spring.rabbitmq.listener.simple.retry.max-attempts: 5
#重试间隔次数
#spring.rabbitmq.listener.simple.retry.initial-interval: 3000

配置类

@Configuration
public class RabbitmqConfig {

    //配置Exchange
    @Bean
    public TopicExchange directExchange() {
        return new TopicExchange("mytopic");
    }

    // 绑定交换机与队列
    @Bean
    public Binding getMyqueue(TopicExchange topicExchange) {
        Queue queue = new Queue("topicqueue");
        //key -- 消费用的key
        return BindingBuilder.bind(queue).to(topicExchange).with("key.*");
    }

}

发送消息

@Service
public class RabbitmqProducerService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    public void amqpTemplateTest(){
        String message = UUID.randomUUID().toString().substring(0, 6);
        //mytopic --  交换机Name;key -- 发送的key
        amqpTemplate.convertAndSend("mytopic","key.11",message);
        System.out.println("发送完成");
    }
}

接收消息

@Component
public class RabbitmqListener {

    @RabbitListeners({@RabbitListener(queues = "topicqueue")})
    public void reveiceMessage(String msg, Channel channel, Message message) {
        System.out.println(msg);
        System.out.println(channel);
        System.out.println(message);
    }

}
posted @   叕叕666  阅读(51)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
点击右上角即可分享
微信分享提示