RabbitMQ实现消息传递,数据共享

简单实现Rabbitmq消息传递和数据共享,首先是配置类

@Configuration
public class RabbitmqConfig {

    @Bean
    public Queue testQueue() {
        return new Queue(Mqconstant.TEST_QUEUE);
    }
   
    @Bean
    public TopicExchange exchangeTopic() {
        return new TopicExchange(Mqconstant.TOPIC_EXCHANGE);
    }
    @Bean
    public Binding bindingTest() {
        return BindingBuilder.bind(testQueue()).to(exchangeTopic()).with("test.*");
    }
  
    @Bean
    public RabbitListenerContainerFactory<?> rabbitListenerContainerFactory(ConnectionFactory connectionFactory){
        DirectRabbitListenerContainerFactory factory = new DirectRabbitListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setMessageConverter(new Jackson2JsonMessageConverter());
        factory.setAcknowledgeMode(AcknowledgeMode.MANUAL);
        return factory;
    }

}

静态常量

public class Mqconstant {
    public static final String TOPIC_EXCHANGE = "exchange_topic";
    public static final String TEST_QUEUE = "test_queue";

    public static final String TEST_CREATE = "test.create";
    public static final String TEST_DELETE = "test.delete";
    public static final String TEST_UPDATE = "test.update";
}

发送消息

@Component
public class RabbitUtils {
    @Autowired
    RabbitTemplate rabbitTemplate;
    public void publish(String routeKey,String msg) throws UnsupportedEncodingException {
        MessageProperties properties = new MessageProperties();
        //等于是给消息设置了id,用来判断消息是否已被处理
        properties.setMessageId(routeKey+String.valueOf(System.currentTimeMillis()));
        properties.setDeliveryTag(System.currentTimeMillis());
        Message message = new Message(msg.getBytes("UTF-8"),properties);
        rabbitTemplate.convertAndSend(Mqconstant.TOPIC_EXCHANGE, routeKey, message);
    }

}

工具类,用来执行不同的消息传递

@Component
public class TestrRabbitUtils {

    @Autowired
    private RabbitUtils rabbitUtils;
	// Object 对象
     public void sendRabbitCreate(Object po) throws UnsupportedEncodingException {
         rabbitUtils.publish(Mqconstant.TEST_CREATE, JSON.toJSONString(po));
         
     }

    public void sendRabbitUpdate(Object po) throws UnsupportedEncodingException {
        rabbitUtils.publish(Mqconstant.TEST_UPDATE, JSON.toJSONString(po));
       
    }

    public void sendRabbitDelete(Object po) throws UnsupportedEncodingException {
        rabbitUtils.publish(Mqconstant.TEST_DELETE, JSON.toJSONString(po));
       
    }

}

具体使用方法

@Autowired
private TestrRabbitUtils userRabbitUtils;

userRabbitUtils.sendRabbitCreate(obj);
userRabbitUtils.sendRabbitUpdate(obj);
userRabbitUtils.sendRabbitDelete(obj);

接收消息

@Component
public class RabbitMqListener {

    private final static Logger log = LoggerFactory.getLogger(RabbitMqListener.class);

    @RabbitListener(queues = Mqconstant.TEST_QUEUE )
    public void receiveMsg1(Message msg, @Headers Map<String ,Object> headers, Channel channel) throws Exception {
        // 获取路由地址,根据这个判断做什么操作create delete status update;
        String key = (String) headers.get("amqp_receivedRoutingKey");
        long tag = msg.getMessageProperties().getDeliveryTag();
        String messageId = msg.getMessageProperties().getMessageId();
        Object obj = JSON.toJavaObject(JSON.parseObject(new String(msg.getBody(),"UTF-8")), Object.class);
        
        try {
            Object value = redisUtils.getValue(messageId);
            if(Objects.nonNull(value)){
                channel.basicAck(tag,false);
                return;
            }
            switch(key){
                case Mqconstant.TEST_CREATE :
                    //执行具体的业务逻辑
                    break;
                case Mqconstant.TEST_DELETE :
                    //执行具体的业务逻辑
                    break;
                case Mqconstant.TEST_UPDATE :
                    //执行具体的业务逻辑
                    break;
                default :
                    //System.out.println("Key:"+ key +",消息:" + msg);
                    break;
            }
          
            redisUtils.setValue(messageId,key,expire);
            channel.basicAck(tag,false);
        } catch (Exception e) {
            e.printStackTrace();
            channel.basicNack(tag,false,true);
        }

    }

}
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值