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

The following examples show how to use org.apache.rocketmq.client.producer.SendCallback. 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 File: DeFiBusProducerImpl.java    From DeFiBus with 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 #2
Source File: RMQAsyncSendProducer.java    From rocketmq-read with 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 File: AsyncProducer.java    From blog with 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 #4
Source File: RocketMQTemplate.java    From rocketmq-spring with 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 #5
Source File: RMQAsyncSendProducer.java    From rocketmq with 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 #6
Source File: RMQAsyncSendProducer.java    From rocketmq-4.3.0 with 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 #7
Source File: RMQAsyncSendProducer.java    From DDMQ with 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 File: RMQAsyncSendProducer.java    From DDMQ with 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 #9
Source File: DefaultMQProducerImpl.java    From DDMQ with 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 #10
Source File: AsyncSendExceptionIT.java    From rocketmq-read with 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 #11
Source File: DefaultMQProducerImpl.java    From DDMQ with 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 File: Producer.java    From java-tutorial with MIT License 5 votes vote down vote up
@Override
public void run(String... args) throws Exception {

    SendResult result = rocketMQTemplate.syncSend(springTopic, "RocketMQ 同步发送字符串");
    System.out.printf(String.format("syncSend topic %s,sendResult", springTopic, result));

    result = rocketMQTemplate.syncSend(springTopic, MessageBuilder.withPayload("Hello, RocketMQ! MessageBuilder发送消息").build());
    System.out.printf("syncSend2 to topic %s sendResult=%s %n", springTopic, result);

    //发送异步消息
    rocketMQTemplate.asyncSend(orderPaidTopic, new OrderPaidEvent("SO_1001", new BigDecimal("66.66")), new SendCallback() {
        @Override
        public void onSuccess(SendResult sendResult) {
            System.out.printf("异步消息发送成功 SendResult=%s %n", sendResult);
        }

        @Override
        public void onException(Throwable throwable) {
            System.out.printf("异步消息发生异常 SendResult=%s %n", throwable);
        }
    });

    rocketMQTemplate.convertAndSend(msgExtTopic + ":tag0", "I'm from tag0");
    System.out.printf("syncSend topic %s tag %s %n", msgExtTopic, "tag0");

    rocketMQTemplate.convertAndSend(msgExtTopic + ":tag1", "I'm from tag1");
    System.out.printf("syncSend topic %s tag %s %n", msgExtTopic, "tag1");

    sendBatchMessage();

    sendTransaction();
}
 
Example #13
Source File: AsyncProducer.java    From java-tutorial with MIT License 5 votes vote down vote up
public static void main(String[] args) throws Exception {
    //Instantiate with a producer group name.
    DefaultMQProducer producer = new DefaultMQProducer("ASYNC_MQ_GROUP");
    // Specify name server addresses.
    producer.setNamesrvAddr(SyncProducer.NAMESRVADDR);
    producer.setInstanceName("ASYNC_PRODUCER");
    producer.setVipChannelEnabled(false);
    // 设置重试次数,默认2
    producer.setRetryTimesWhenSendFailed(3);
    //设置发送超时时间,默认是3000
    producer.setSendMsgTimeout(10000);

    //Launch the instance.
    producer.start();
    producer.setRetryTimesWhenSendAsyncFailed(0);

    for (int i = 0; i < 10; i++) {
        final int index = i;
        Message msg = new Message("Async_Topic_Test",
                "Async_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();
            }
        }, 10000);
    }
    //Shut down once the producer instance is not longer in use.
    producer.shutdown();
}
 
Example #14
Source File: AsyncSendExceptionIT.java    From rocketmq with 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.waitForMonment(100);
    }
    producer.shutdown();
    assertThat(sendFail).isEqualTo(true);
}
 
Example #15
Source File: AsyncSendExceptionIT.java    From rocketmq with 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 #16
Source File: SendCallBackFactory.java    From DDMQ with 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 #17
Source File: AsyncProducer.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void main(String[] args) throws Exception {
	// Instantiate with a producer group name.
	DefaultMQProducer producer = new DefaultMQProducer("ExampleProducerGroup");
	producer.setNamesrvAddr(RocketConfig.HOST);
	// Launch the instance.
	producer.start();
	producer.setRetryTimesWhenSendAsyncFailed(0);
	for (int i = 0; i < 100; i++) {
		final int index = i;
		// Create a message instance, specifying topic, tag and message body.
		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();
			}
		});
	}
	// Shut down once the producer instance is not longer in use.
	producer.shutdown();
}
 
Example #18
Source File: ClientFuseTest.java    From DeFiBus with 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());
}
 
Example #19
Source File: DefaultMQProducerImpl.java    From DDMQ with 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 #20
Source File: SendCallBackFactory.java    From rocketmq with 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 #21
Source File: AsyncSendExceptionIT.java    From rocketmq-read with 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 #22
Source File: AsyncSendExceptionIT.java    From rocketmq-read with 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 #23
Source File: AsyncSendExceptionIT.java    From DDMQ with 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 #24
Source File: DefaultMQProducerImpl.java    From rocketmq-read with Apache License 2.0 5 votes vote down vote up
/**
 * 带队列选择器的发送
 * @param msg msg
 * @param selector selector
 * @param arg arg
 * @param communicationMode 发送模型
 * @param sendCallback callback
 * @param timeout timeout
 * @return ;
 * @throws MQClientException ;
 * @throws RemotingException ;
 * @throws MQBrokerException ;
 * @throws InterruptedException ;
 */
private SendResult sendSelectImpl(
    Message msg,
    MessageQueueSelector selector,
    Object arg,
    final CommunicationMode communicationMode,
    final SendCallback sendCallback, final long timeout
) throws MQClientException, RemotingException, MQBrokerException, InterruptedException {

    long beginStartTime = System.currentTimeMillis();
    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);
        }

        long costTime = System.currentTimeMillis() - beginStartTime;
        if (timeout < costTime) {
            throw new RemotingTooMuchRequestException("sendSelectImpl call timeout");
        }
        if (mq != null) {
            return this.sendKernelImpl(msg, mq, communicationMode, sendCallback, null, timeout - costTime);
        } else {
            throw new MQClientException("select message queue return null.", null);
        }
    }

    throw new MQClientException("No route info for this topic, " + msg.getTopic(), null);
}
 
Example #25
Source File: DeFiBusClientAPIImplTest.java    From DeFiBus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendMessagetypeOfnull_Success() throws RemotingException, InterruptedException, MQBrokerException {
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock mock) throws Throwable {
            InvokeCallback callback = mock.getArgument(3);
            RemotingCommand request = mock.getArgument(1);
            ResponseFuture responseFuture = new ResponseFuture(null, request.getOpaque(), 3 * 1000, null, null);
            responseFuture.setResponseCommand(createSuccessResponse(request));
            callback.operationComplete(responseFuture);
            return null;
        }
    }).when(remotingClient).invokeAsync(anyString(), any(RemotingCommand.class), anyLong(), any(InvokeCallback.class));
    SendMessageContext sendMessageContext = new SendMessageContext();
    sendMessageContext.setProducer(new DefaultMQProducerImpl(new DefaultMQProducer()));
    deFiBusClientAPI.sendMessage(brokerAddr, brokerName, msg, new SendMessageRequestHeader(), 3 * 1000, CommunicationMode.ASYNC,
        new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
                assertThat(sendResult.getOffsetMsgId()).isEqualTo("123");
                assertThat(sendResult.getQueueOffset()).isEqualTo(123L);
                assertThat(sendResult.getMessageQueue().getQueueId()).isEqualTo(1);
            }

            @Override
            public void onException(Throwable e) {
            }
        },
        null, null, 0, sendMessageContext, defaultMQProducerImpl);
}
 
Example #26
Source File: DeFiBusClientAPIImplTest.java    From DeFiBus with Apache License 2.0 5 votes vote down vote up
@Test
public void testSendMessageTypeOfReply_Success() throws Exception {
    doAnswer(new Answer() {
        @Override
        public Object answer(InvocationOnMock mock) throws Throwable {
            InvokeCallback callback = mock.getArgument(3);
            RemotingCommand request = mock.getArgument(1);
            ResponseFuture responseFuture = new ResponseFuture(null, request.getOpaque(), 3 * 1000, null, null);
            responseFuture.setResponseCommand(createSuccessResponse(request));
            callback.operationComplete(responseFuture);
            return null;
        }
    }).when(remotingClient).invokeAsync(anyString(), any(RemotingCommand.class), anyLong(), any(InvokeCallback.class));
    SendMessageContext sendMessageContext = new SendMessageContext();
    sendMessageContext.setProducer(new DefaultMQProducerImpl(new DefaultMQProducer()));
    msg.getProperties().put("msgType", "reply");
    deFiBusClientAPI.sendMessage(brokerAddr, brokerName, msg, new SendMessageRequestHeader(), 3 * 1000, CommunicationMode.ASYNC,
        new SendCallback() {
            @Override
            public void onSuccess(SendResult sendResult) {
                assertThat(sendResult.getSendStatus()).isEqualTo(SendStatus.SEND_OK);
                assertThat(sendResult.getOffsetMsgId()).isEqualTo("123");
                assertThat(sendResult.getQueueOffset()).isEqualTo(123L);
                assertThat(sendResult.getMessageQueue().getQueueId()).isEqualTo(1);
            }

            @Override
            public void onException(Throwable e) {
            }
        }, null, null, 0, sendMessageContext, defaultMQProducerImpl);
}
 
Example #27
Source File: AsyncProducer.java    From netty-chat with 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 #28
Source File: ClientFuseTest.java    From DeFiBus with 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 #29
Source File: DeFiBusClientAPIImpl.java    From DeFiBus with 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 #30
Source File: DeFiBusProducerImpl.java    From DeFiBus with 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);
}