Java Code Examples for org.apache.rocketmq.client.producer.SendCallback

The following examples show how to use org.apache.rocketmq.client.producer.SendCallback. These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source Project: DDMQ   Source File: RMQAsyncSendProducer.java    License: Apache License 2.0 6 votes vote down vote up
public RMQAsyncSendProducer(String nsAddr, String topic) {
    super(topic);
    this.nsAddr = nsAddr;
    sendCallback = new SendCallback() {
        public void onSuccess(org.apache.rocketmq.client.producer.SendResult sendResult) {
            successSendResult.add(sendResult);
        }

        public void onException(Throwable throwable) {
            exceptionMsgCount.getAndIncrement();
        }
    };

    create();
    start();
}
 
Example 2
Source Project: rocketmq-4.3.0   Source File: RMQAsyncSendProducer.java    License: Apache License 2.0 6 votes vote down vote up
public RMQAsyncSendProducer(String nsAddr, String topic) {
    super(topic);
    this.nsAddr = nsAddr;
    sendCallback = new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
            successSendResult.add(sendResult);
        }
        @Override
        public void onException(Throwable throwable) {
            exceptionMsgCount.getAndIncrement();
        }
    };

    create();
    start();
}
 
Example 3
Source Project: DeFiBus   Source File: DeFiBusProducerImpl.java    License: Apache License 2.0 6 votes vote down vote up
public void publish(final Message msg, final SendCallback sendCallback,
    final long timeout) throws MQClientException, RemotingException, InterruptedException {
    if (msg.getUserProperty(DeFiBusConstant.PROPERTY_MESSAGE_TTL) == null) {
        msg.putUserProperty(DeFiBusConstant.PROPERTY_MESSAGE_TTL, DeFiBusConstant.DEFAULT_TTL);
    }

    final AtomicReference<MessageQueue> selectorArgs = new AtomicReference<MessageQueue>();
    AsynCircuitBreakSendCallBack asynCircuitBreakSendCallBack = new AsynCircuitBreakSendCallBack();
    asynCircuitBreakSendCallBack.setMsg(msg);
    asynCircuitBreakSendCallBack.setProducer(this.deFiBusProducer);
    asynCircuitBreakSendCallBack.setSelectorArg(selectorArgs);
    asynCircuitBreakSendCallBack.setSendCallback(sendCallback);

    String topic = msg.getTopic();
    boolean hasRouteData = deFiBusProducer.getDefaultMQProducer().getDefaultMQProducerImpl().getmQClientFactory().getTopicRouteTable().containsKey(topic);
    if (!hasRouteData) {
        LOGGER.info("no topic route info for " + topic + ", send heartbeat to nameserver");
        deFiBusProducer.getDefaultMQProducer().getDefaultMQProducerImpl().getmQClientFactory().updateTopicRouteInfoFromNameServer(topic);
    }

    DeFiBusProducerImpl.this.deFiBusProducer.getDefaultMQProducer().send(msg, messageQueueSelector, selectorArgs, asynCircuitBreakSendCallBack, timeout);
}
 
Example 4
Source Project: rocketmq-read   Source File: RMQAsyncSendProducer.java    License: Apache License 2.0 6 votes vote down vote up
public RMQAsyncSendProducer(String nsAddr, String topic) {
    super(topic);
    this.nsAddr = nsAddr;
    sendCallback = new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
            successSendResult.add(sendResult);
        }
        @Override
        public void onException(Throwable throwable) {
            exceptionMsgCount.getAndIncrement();
        }
    };

    create();
    start();
}
 
Example 5
Source Project: rocketmq-spring   Source File: RocketMQTemplate.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Same to {@link #asyncSend(String, Message, SendCallback)} with send timeout and delay level specified in
 * addition.
 *
 * @param destination formats: `topicName:tags`
 * @param message {@link org.springframework.messaging.Message}
 * @param sendCallback {@link SendCallback}
 * @param timeout send timeout with millis
 * @param delayLevel level for the delay message
 */
public void asyncSend(String destination, Message<?> message, SendCallback sendCallback, long timeout,
    int delayLevel) {
    if (Objects.isNull(message) || Objects.isNull(message.getPayload())) {
        log.error("asyncSend failed. destination:{}, message is null ", destination);
        throw new IllegalArgumentException("`message` and `message.payload` cannot be null");
    }
    try {
        org.apache.rocketmq.common.message.Message rocketMsg = this.createRocketMqMessage(destination, message);
        if (delayLevel > 0) {
            rocketMsg.setDelayTimeLevel(delayLevel);
        }
        producer.send(rocketMsg, sendCallback, timeout);
    } catch (Exception e) {
        log.info("asyncSend failed. destination:{}, message:{} ", destination, message);
        throw new MessagingException(e.getMessage(), e);
    }
}
 
Example 6
Source Project: DDMQ   Source File: RMQAsyncSendProducer.java    License: Apache License 2.0 6 votes vote down vote up
public RMQAsyncSendProducer(String nsAddr, String topic) {
    super(topic);
    this.nsAddr = nsAddr;
    sendCallback = new SendCallback() {
        public void onSuccess(org.apache.rocketmq.client.producer.SendResult sendResult) {
            successSendResult.add(sendResult);
        }

        public void onException(Throwable throwable) {
            exceptionMsgCount.getAndIncrement();
        }
    };

    create();
    start();
}
 
Example 7
Source Project: rocketmq   Source File: RMQAsyncSendProducer.java    License: Apache License 2.0 6 votes vote down vote up
public RMQAsyncSendProducer(String nsAddr, String topic) {
    super(topic);
    this.nsAddr = nsAddr;
    sendCallback = new SendCallback() {
        public void onSuccess(org.apache.rocketmq.client.producer.SendResult sendResult) {
            successSendResult.add(sendResult);
        }

        public void onException(Throwable throwable) {
            exceptionMsgCount.getAndIncrement();
        }
    };

    create();
    start();
}
 
Example 8
Source Project: blog   Source File: AsyncProducer.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static void main(String[] args)
		throws MQClientException, RemotingException, InterruptedException, UnsupportedEncodingException {
	DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName2");
	producer.setRetryTimesWhenSendAsyncFailed(3);
	producer.setNamesrvAddr("192.168.237.128:9876");
	producer.start();
	for (int i = 0; i < 1; i++) {
		Message msg = new Message("TopicTest6", "TagA",
				("Hello RocketMQ" + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
		producer.send(msg, new SendCallback() {
			@Override
			public void onSuccess(SendResult sendResult) {
				System.out.println(sendResult);
			}

			@Override
			public void onException(Throwable e) {
				e.printStackTrace();
			}
		});
	}
}
 
Example 9
Source Project: netty-chat   Source File: AsyncProducer.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    DefaultMQProducer producer = new DefaultMQProducer("aaa");
    producer.setNamesrvAddr("127.0.0.1:9876");
    producer.start();
    producer.setRetryTimesWhenSendAsyncFailed(0);
    for (int i = 0; i < 10; i++) {
        int index = i;
        Message msg = new Message("TopicTest",
                "TagA",
                "OrderID188",
                "Hello world".getBytes(RemotingHelper.DEFAULT_CHARSET));
        producer.send(msg, new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                System.out.printf("%-10d OK %s %n", index, sendResult.getMsgId());
            }

            @Override
            public void onException(Throwable e) {
                System.out.printf("%-10d Exception %s %n", index, e);
                e.printStackTrace();
            }
        });
    }
    Thread.sleep(1000);
    producer.shutdown();
}
 
Example 10
Source Project: code   Source File: Producer.java    License: Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {

        DefaultMQProducer producer = new DefaultMQProducer("test_async_producer_name");

        producer.setNamesrvAddr(Const.NAMESRV_ADDR_SINGLE);

        producer.start();

        for (int i = 0; i < 5; i++) {
            //	1、创建消息
            Message message = new Message("test_quick_topic",    //	主题
                    "TagA", //	标签
                    "key" + i,    // 	用户自定义的key ,唯一的标识
                    ("Hello RocketMQ" + i).getBytes());    //	消息内容实体(byte[])
            // 2、发送消息
            //SendResult sr = producer.send(message);
            //System.err.println("消息发出:" + sr);
            producer.send(message, new SendCallback() {
                @Override
                public void onSuccess(SendResult sendResult) {
                    System.err.println("msgId: " + sendResult.getMsgId() + ", status: " + sendResult.getSendStatus());
                }

                @Override
                public void onException(Throwable e) {
                    e.printStackTrace();
                    System.err.println("------发送失败");
                }
            });

        }

        //producer.shutdown();

    }
 
Example 11
Source Project: DDMQ   Source File: DefaultMQProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void send(Message msg, SendCallback sendCallback, long timeout)
    throws MQClientException, RemotingException, InterruptedException {
    try {
        this.sendDefaultImpl(msg, CommunicationMode.ASYNC, sendCallback, timeout);
    } catch (MQBrokerException e) {
        throw new MQClientException("unknownn exception", e);
    }
}
 
Example 12
Source Project: DDMQ   Source File: DefaultMQProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void send(Message msg, MessageQueue mq, SendCallback sendCallback, long timeout)
    throws MQClientException, RemotingException, InterruptedException {
    this.makeSureStateOK();
    Validators.checkMessage(msg, this.defaultMQProducer);

    if (!msg.getTopic().equals(mq.getTopic())) {
        throw new MQClientException("message's topic not equal mq's topic", null);
    }

    try {
        this.sendKernelImpl(msg, mq, CommunicationMode.ASYNC, sendCallback, null, timeout);
    } catch (MQBrokerException e) {
        throw new MQClientException("unknown exception", e);
    }
}
 
Example 13
Source Project: DDMQ   Source File: DefaultMQProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
private SendResult sendSelectImpl(
    Message msg,
    MessageQueueSelector selector,
    Object arg,
    final CommunicationMode communicationMode,
    final SendCallback sendCallback, final long timeout
) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {
    this.makeSureStateOK();
    Validators.checkMessage(msg, this.defaultMQProducer);

    TopicPublishInfo topicPublishInfo = this.tryToFindTopicPublishInfo(msg.getTopic());
    if (topicPublishInfo != null && topicPublishInfo.ok()) {
        MessageQueue mq = null;
        try {
            mq = selector.select(topicPublishInfo.getMessageQueueList(), msg, arg);
        } catch (Throwable e) {
            throw new MQClientException("select message queue throwed exception.", e);
        }

        if (mq != null) {
            return this.sendKernelImpl(msg, mq, communicationMode, sendCallback, null, timeout);
        } else {
            throw new MQClientException("select message queue return null.", null);
        }
    }

    throw new MQClientException("No route info for this topic, " + msg.getTopic(), null);
}
 
Example 14
Source Project: DDMQ   Source File: DefaultMQProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void send(Message msg, MessageQueueSelector selector, Object arg, SendCallback sendCallback, long timeout)
    throws MQClientException, RemotingException, InterruptedException {
    try {
        this.sendSelectImpl(msg, selector, arg, CommunicationMode.ASYNC, sendCallback, timeout);
    } catch (MQBrokerException e) {
        throw new MQClientException("unknownn exception", e);
    }
}
 
Example 15
Source Project: DDMQ   Source File: SendCallBackFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static SendCallback getSendCallBack() {
    return new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
        }

        @Override
        public void onException(Throwable throwable) {
        }
    };
}
 
Example 16
Source Project: DDMQ   Source File: AsyncSendExceptionIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSendCallBackNull() throws Exception {
    Message msg = new Message(topic, RandomUtils.getStringByUUID().getBytes());
    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);
    SendCallback sendCallback = null;
    producer.send(msg, sendCallback);
}
 
Example 17
Source Project: DDMQ   Source File: AsyncSendExceptionIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testQueueIdBigThanQueueNum() throws Exception {
    int queueId = 100;
    sendFail = false;
    MessageQueue mq = new MessageQueue(topic, broker1Name, queueId);
    Message msg = new Message(topic, RandomUtils.getStringByUUID().getBytes());
    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);

    producer.send(msg, mq, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
        }

        @Override
        public void onException(Throwable throwable) {
            sendFail = true;
        }
    });

    int checkNum = 50;
    while (!sendFail && checkNum > 0) {
        checkNum--;
        TestUtils.waitForMoment(100);
    }
    producer.shutdown();
    assertThat(sendFail).isEqualTo(true);
}
 
Example 18
Source Project: DDMQ   Source File: AsyncSendExceptionIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testQueueIdSmallZero() throws Exception {
    int queueId = -100;
    sendFail = true;
    MessageQueue mq = new MessageQueue(topic, broker1Name, queueId);
    Message msg = new Message(topic, RandomUtils.getStringByUUID().getBytes());
    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);

    producer.send(msg, mq, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
            sendFail = false;
        }

        @Override
        public void onException(Throwable throwable) {
            sendFail = true;
        }
    });

    int checkNum = 50;
    while (sendFail && checkNum > 0) {
        checkNum--;
        TestUtils.waitForMoment(100);
    }
    producer.shutdown();
    assertThat(sendFail).isEqualTo(false);
}
 
Example 19
Source Project: DDMQ   Source File: RmqSender.java    License: Apache License 2.0 5 votes vote down vote up
public static void send(DefaultMQProducer producer,
                        Message msg,
                        MessageQueue mq,
                        SendCallback sendCallback,
                        long timeout)
        throws MQBrokerException, MQClientException, RemotingException, InterruptedException {
    Validators.checkMessage(msg, producer);
    producer.getDefaultMQProducerImpl().sendKernelImpl(msg, mq, CommunicationMode.ASYNC, sendCallback, null, timeout);
}
 
Example 20
Source Project: DDMQ   Source File: RmqSender.java    License: Apache License 2.0 5 votes vote down vote up
public static void send(DefaultMQProducer producer,
                        CarreraRequest request,
                        SendCallback sendCallback,
                        long timeout)
        throws MQBrokerException, MQClientException, RemotingException, InterruptedException {
    MessageQueue mq = select(producer, request);
    send(producer, request.toRmqMessage(), mq, sendCallback, timeout);
}
 
Example 21
Source Project: rocketmq-4.3.0   Source File: DefaultMQProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
/**
     * DEFAULT ASYNC -------------------------------------------------------
     */
//
    public void send(Message msg,
                     SendCallback sendCallback) throws MQClientException, RemotingException, InterruptedException {
//        3s超时=》
        send(msg, sendCallback, this.defaultMQProducer.getSendMsgTimeout());
    }
 
Example 22
Source Project: rocketmq-4.3.0   Source File: SendCallBackFactory.java    License: Apache License 2.0 5 votes vote down vote up
public static SendCallback getSendCallBack() {
    return new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
        }

        @Override
        public void onException(Throwable throwable) {
        }
    };
}
 
Example 23
Source Project: rocketmq-4.3.0   Source File: AsyncSendExceptionIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testSendCallBackNull() throws Exception {
    Message msg = new Message(topic, RandomUtils.getStringByUUID().getBytes());
    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);
    SendCallback sendCallback = null;
    producer.send(msg, sendCallback);
}
 
Example 24
Source Project: rocketmq-4.3.0   Source File: AsyncSendExceptionIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testQueueIdBigThanQueueNum() throws Exception {
    int queueId = 100;
    sendFail = false;
    MessageQueue mq = new MessageQueue(topic, broker1Name, queueId);
    Message msg = new Message(topic, RandomUtils.getStringByUUID().getBytes());
    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);

    producer.send(msg, mq, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
        }

        @Override
        public void onException(Throwable throwable) {
            sendFail = true;
        }
    });

    int checkNum = 50;
    while (!sendFail && checkNum > 0) {
        checkNum--;
        TestUtils.waitForMoment(100);
    }
    producer.shutdown();
    assertThat(sendFail).isEqualTo(true);
}
 
Example 25
Source Project: rocketmq-4.3.0   Source File: AsyncSendExceptionIT.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testQueueIdSmallZero() throws Exception {
    int queueId = -100;
    sendFail = true;
    MessageQueue mq = new MessageQueue(topic, broker1Name, queueId);
    Message msg = new Message(topic, RandomUtils.getStringByUUID().getBytes());
    DefaultMQProducer producer = ProducerFactory.getRMQProducer(nsAddr);

    producer.send(msg, mq, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
            sendFail = false;
        }

        @Override
        public void onException(Throwable throwable) {
            sendFail = true;
        }
    });

    int checkNum = 50;
    while (sendFail && checkNum > 0) {
        checkNum--;
        TestUtils.waitForMoment(100);
    }
    producer.shutdown();
    assertThat(sendFail).isEqualTo(false);
}
 
Example 26
Source Project: DeFiBus   Source File: DeFiBusProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void reply(
    Message replyMsg,
    final SendCallback sendCallback) throws InterruptedException, RemotingException, MQClientException, MQBrokerException {
    replyMsg.putUserProperty(DeFiBusConstant.KEY, DeFiBusConstant.REPLY);
    replyMsg.putUserProperty(DeFiBusConstant.PROPERTY_MESSAGE_TTL, String.valueOf(deFiBusProducer.getDefaultMQProducer().getSendMsgTimeout()));

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug("Reply message: {} ", replyMsg.toString());
    }
    final String requestId = replyMsg.getUserProperty(DeFiBusConstant.PROPERTY_RR_REQUEST_ID);
    if (requestId == null) {
        LOGGER.warn("rr request id is null, can not reply");
    }
    publish(replyMsg, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
            if (sendCallback != null) {
                sendCallback.onSuccess(sendResult);
            }
        }

        @Override
        public void onException(Throwable e) {
            LOGGER.warn("Reply message fail, requestId={}", requestId);
            if (sendCallback != null) {
                sendCallback.onException(e);
            }
        }
    });
}
 
Example 27
Source Project: DeFiBus   Source File: DeFiBusProducerImpl.java    License: Apache License 2.0 5 votes vote down vote up
public void publish(Message msg, long timeout) throws MQClientException, RemotingException, InterruptedException {
    publish(msg, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
            LOGGER.debug(sendResult.toString());
        }

        @Override
        public void onException(Throwable e) {
            LOGGER.warn("", e);
        }
    }, timeout);
}
 
Example 28
Source Project: DeFiBus   Source File: DeFiBusClientAPIImpl.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public SendResult sendMessage(//
    final String addr, // 1
    final String brokerName, // 2
    final Message msg, // 3
    final SendMessageRequestHeader requestHeader, // 4
    final long timeoutMillis, // 5
    final CommunicationMode communicationMode, // 6
    final SendCallback sendCallback, // 7
    final TopicPublishInfo topicPublishInfo, // 8
    final MQClientInstance instance, // 9
    final int retryTimesWhenSendFailed, // 10
    final SendMessageContext context, // 11
    final DefaultMQProducerImpl producer // 12
) throws RemotingException, MQBrokerException, InterruptedException {
    RemotingCommand request = null;
    if (DeFiBusConstant.REPLY.equals(msg.getProperties().get(DeFiBusConstant.KEY)) ||
        DeFiBusConstant.DIRECT.equals(msg.getProperties().get(DeFiBusConstant.KEY))) {
        if (sendSmartMsg) {
            SendMessageRequestHeaderV2 requestHeaderV2 = SendMessageRequestHeaderV2.createSendMessageRequestHeaderV2(requestHeader);
            request = RemotingCommand.createRequestCommand(DeFiBusRequestCode.SEND_DIRECT_MESSAGE_V2, requestHeaderV2);
        } else {
            request = RemotingCommand.createRequestCommand(DeFiBusRequestCode.SEND_DIRECT_MESSAGE, requestHeader);
        }
        request.setBody(msg.getBody());
        final AtomicInteger times = new AtomicInteger();
        this.sendMessageAsync(addr, brokerName, msg, timeoutMillis, request, sendCallback, topicPublishInfo, instance,
            retryTimesWhenSendFailed, times, context, producer);
        return null;

    } else {
        return super.sendMessage(addr, brokerName, msg, requestHeader, timeoutMillis, communicationMode, sendCallback, topicPublishInfo, instance, retryTimesWhenSendFailed, context, producer);
    }
}
 
Example 29
Source Project: DeFiBus   Source File: ClientFuseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws Exception {
    DeFiBusClientConfig clientConfig = new DeFiBusClientConfig();
    clientConfig.setClusterPrefix("GL");
    clientConfig.setProducerGroup(producerGroup);
    clientConfig.setNamesrvAddr("127.0.0.1:9876");
    deFiBusProducer = new DeFiBusProducer(clientConfig);
    deFiBusProducer.start();

    msg = new Message(topic, new byte[] {'a'});
    Field field = DefaultMQProducerImpl.class.getDeclaredField("mQClientFactory");
    field.setAccessible(true);
    field.set(deFiBusProducer.getDefaultMQProducer().getDefaultMQProducerImpl(), mQClientFactory);

    field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
    field.setAccessible(true);
    field.set(mQClientFactory, mqClientAPIImpl);

    deFiBusProducer.getDefaultMQProducer().getDefaultMQProducerImpl().getmQClientFactory().
        registerProducer(producerGroup, deFiBusProducer.getDefaultMQProducer().getDefaultMQProducerImpl());

    Exception e = new MQBrokerException(DeFiBusResponseCode.CONSUME_DIFF_SPAN_TOO_LONG, "CODE: " + DeFiBusResponseCode.CONSUME_DIFF_SPAN_TOO_LONG + " DESC: consume span too long, maybe has slow consumer, so send rejected\nFor more information, please visit the url, http://rocketmq.apache.org/docs/faq/");
    when(mqClientAPIImpl.sendMessage(anyString(), anyString(), any(Message.class), any(SendMessageRequestHeader.class), anyLong(), any(CommunicationMode.class),
        any(SendCallback.class), nullable(TopicPublishInfo.class), any(MQClientInstance.class), anyInt(), nullable(SendMessageContext.class), any(DefaultMQProducerImpl.class)))
        .thenAnswer(new Answer() {
            @Override
            public Object answer(InvocationOnMock invocation) throws Throwable {
                Object[] args = invocation.getArguments();
                SendCallback callback = (SendCallback) args[6];
                callback.onException(e);
                return new SendResult();
            }
        });
}
 
Example 30
Source Project: DeFiBus   Source File: ClientFuseTest.java    License: Apache License 2.0 5 votes vote down vote up
@Test
public void testProcessResponseFuse() throws Exception {
    when(mqClientAPIImpl.getTopicRouteInfoFromNameServer(anyString(), anyLong())).thenReturn(createTopicRoute());
    CountDownLatch countDownLatch = new CountDownLatch(1);
    Field fieldSelector = DeFiBusProducerImpl.class.getDeclaredField("messageQueueSelector");
    fieldSelector.setAccessible(true);
    Field fieldProducer = DeFiBusProducer.class.getDeclaredField("deFiBusProducerImpl");
    fieldProducer.setAccessible(true);
    MessageQueueHealthManager messageQueueHealthManager = ((HealthyMessageQueueSelector) fieldSelector.get(fieldProducer.get(deFiBusProducer))).getMessageQueueHealthManager();

    Assert.assertEquals(0, messageQueueHealthManager.faultMap.size());

    deFiBusProducer.publish(msg, new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
        }

        @Override
        public void onException(Throwable e) {
            Assert.fail(e.getMessage());
            countDownLatch.countDown();
        }
    });
    countDownLatch.await(3000L, TimeUnit.MILLISECONDS);

    Assert.assertEquals(3, messageQueueHealthManager.faultMap.size());
}