rabbitmq 发布/订阅模式

1.pom.xml

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

2.配置文件application.yml

    #rabbitmq配置
    rabbitmq:
      host:  #ip
      port: 5672 #端口
      username:  #账号
      password:  #密码

#rabbitMQ队列名信息
queue:
  name: queue_name
  exchange: queue_exchange
  binding: queue.key.#

3.config配置

import org.springframework.amqp.core.*;
import org.springframework.amqp.core.TopicExchange;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class RabbitMQConfig {

    @Value("${queue.name}")
    private String QUEUE_NAME1 ;
    @Value("${queue.exchange}")
    private String EXCHANGE_NAME;
    @Value("${queue.binding}")
    private String BINDING_KEY ;
    // 创建队列
    @Bean
    public Queue createACN1Queue() {
        return new Queue(QUEUE_NAME1);
    }

    // 创建一个 topic 类型的交换器
    @Bean
    public TopicExchange exchange() {

        return new TopicExchange(EXCHANGE_NAME);
    }
    // 使用路由键(routingKey)把队列(Queue1)绑定到交换器(Exchange)
    @Bean
    public Binding binding1() {
        return BindingBuilder.bind(createACN1Queue()).to(exchange()).with(BINDING_KEY);
    }
}

4.消息生产

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

@Service
public class RabbitMQSendServer {

    @Autowired
    private RabbitTemplate rabbitTemplate;
    @Value("${queue.exchange}")
    private String EXCHANGE_NAME;
    @Value("${queue.binding}")
    private String BINDING_KEY ;
    public void topicSend(String msg) {
        System.out.println("==========发送消息到交换器");
        this.rabbitTemplate.convertAndSend(EXCHANGE_NAME, BINDING_KEY, msg);
    }
}

5.消息消费

import com.allianz.ecallserver.websocket.EcallWebSocket;
import org.apache.log4j.Logger;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;

@Component
public class RabbitMQConsumerServer {

    private static Logger LOG = Logger.getLogger(RabbitMQConsumerServer.class);
    //这里的队列名称要和.yml文件的queue.name一致(应用发布模式时注意)
    private static final String queueName="queue_name";
    
    @RabbitListener(queues = queueName)//这里queueName必须是常量
    public void acnQueueConsumer(String message){
        try {
            LOG.debug("这是获取到的坐席登录ID:"+message);
           
        } catch (Exception e) {
           
            LOG.error("===============消费MQ消息到websocket时发生异常\n"+e);
        }

    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值