RabbitMq浅试和记录

本次需求需要同步两库中的company表。
业务代码略过。。。
rabbitmq创建交换机
在这里插入图片描述
绑定队列
在这里插入图片描述
创建队列
在这里插入图片描述
2.发布者代码

	@Autowired
    RabbitTemplate rabbitTemplate;

	@Override
	public void sendMessageCompany(JSONObject messageVo, String routingkey) {
		// 交换机名称 绑定的routingkey 消息
		rabbitTemplate.convertAndSend("company", "hello", messageVo);
	}

3.消费者代码
初始化通道

package com.gold.mtmc.rabbitmq.config;

import com.gold.mtmc.common.contants.enums.RabbitMqEnum;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @function direct直连模式的交换机配置,包括一个direct交换机,三个队列,三根网线binding
 */
@Configuration
public class HelloExchangeConfig {
	/**
	 * 交换机名称
	 */
	private String EXCHANGE = "hello";

	private String QUEUE = "helloqueue";

	private String RoutingKey = "message_hello";

	/**
	 * 直连模式交换机
	 * @return
	 */
	@Bean
	public DirectExchange helloExchange() {
		DirectExchange directExchange = new DirectExchange(EXCHANGE, true, false);
		return directExchange;
	}

	/**
	 * 处理消息管理中消息推送
	 * @return
	 */
	@Bean
	public Queue helloQueueMsg() {
		Queue queue = new Queue(QUEUE, true, false, false);
		return queue;
	}

	/**
	 * 指定 routing key 绑定 消息队列
	 * @return
	 */
	@Bean
	public Binding helloBindingQueueMsg() {
		Binding binding = BindingBuilder.bind(helloQueueMsg()).to(helloExchange()).with(RoutingKey);
		return binding;
	}

}

@Slf4j
@Component
public class DirectMsgListener {

    @Autowired
    private MsgListener msgListener;

	//指定队列名称
    @RabbitListener(queues = "fanout")
    public void displayMailFanout(JSONObject messageVo, Channel channel, Message message) throws IOException {
        //回调处理消息
        try {
            log.info("directMsg队列监听器收到消息开始:" + messageVo.toString());

            //调用发送消息接口
            msgListener.send(messageVo);

            log.info("directMsg队列监听器收到消息结束:" + messageVo.toString());
        } catch (Exception e) {
            log.info("***********************************************发送消息失败:"+e.getMessage());
            e.printStackTrace();
            log.info("***********************************************发送消息失败:"+e);
        } finally {
            log.info("directMsg队列监听器收到消息结束:" + messageVo.toString() + message.getMessageProperties().getDeliveryTag());
            //这段代码表示,这次消息,我已经接受并消费掉了,不会再重复发送消费
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值