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 @ 2022-03-07 18:03  叕叕666  阅读(61)  评论(0)    收藏  举报