springboot | Rabbitmq 实现RPC方式 远程同步调用

上篇相关文章 Springboot项目整合Rabbitmq详细教程

服务端代码示例

    @Resource
    private RabbitTemplate rabbitTemplate;


    /**
     *  同步	对外发送消息的方法
     * @param msg	具体的消息内容
     * @throws Exception
     */
    public String syncSend(String msg) {
        MessageProperties messageProperties=new MessageProperties();
        Message message=new Message(msg.getBytes(StandardCharsets.UTF_8),messageProperties);
        String uuid = UUID.randomUUID().toString();
        CorrelationData data = new CorrelationData(uuid);
        log.info("【发送的消息-社会信用代码】:" + msg);
         Object result=rabbitTemplate.convertSendAndReceive("data_exchange","data_queue", message,data);
        log.info("【同步消息返回结果-msgResult】:{}",result);
        return result.toString();

    }

消费端代码示例


    @RabbitListener(queues ="data_queue")
    public String gis2dMessage(Message message,Channel channel){
        ackOrReject(message,channel,true);
        return "测试啊啊";
    }

    private void ackOrReject(Message message, Channel channel, boolean result)  {
        try {
            if (result) {
                channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
            } else {
                channel.basicReject(message.getMessageProperties().getDeliveryTag(), false);
            }
        }catch (IOException e){
            new IOException();
        }
    }

yml配置 reply-to 默认等待时间为5s,若是消费者处理时间太长,添加下面配置

spring:
  rabbitmq:
    host: 127.0.0.1
    port: 5672
    username: leaniot
    password: leaniot
    virtual-host: /3d_gis
    template:
      reply-timeout: 10000

测试结果

 觉得不错,记得点赞支持!!!

猜你喜欢

转载自blog.csdn.net/weixin_40986713/article/details/122347853