com.alibaba.rocketmq.common.message.Message Java Examples

The following examples show how to use com.alibaba.rocketmq.common.message.Message. 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: Producer.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {

        DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");

        producer.start();

        for (int i = 0; i < 10000000; i++)
            try {
                {
                    Message msg = new Message("TopicTest",// topic
                            "TagA",// tag
                            "OrderID188",// key
                            ("Hello MetaQ").getBytes(RemotingHelper.DEFAULT_CHARSET));// body
                    SendResult sendResult = producer.send(msg);
                    System.out.println(sendResult);
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        producer.shutdown();
    }
 
Example #2
Source File: RocketMQSender.java    From easyooo-framework with Apache License 2.0 6 votes vote down vote up
@Override
public boolean send(Message data) throws Exception {
	if(data == null){
		return false;
	}
	try{
		SendResult sr = producer.send(data);
		if(sr.getSendStatus() != SendStatus.SEND_OK){
			logger.warn(String.format("Message(%s) has been sent successfully, but send status is %s.", 
					data.getTopic(), sr.getSendStatus()));
		}
	}catch(Exception e){
		if(needFaultTolerant){
			putInErrorQueue(data);
		}
		throw e;
	}
	return true;
}
 
Example #3
Source File: Producer.java    From RocketMQ-Master-analyze with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");
    producer.start();

    try {
        for (int i = 0; i < 6000000; i++) {
            Message msg = new Message("TopicFilter7", // topic
                "TagA", // tag
                "OrderID001", // key
                ("Hello MetaQ").getBytes());// body

            msg.putUserProperty("SequenceId", String.valueOf(i));

            SendResult sendResult = producer.send(msg);
            System.out.println(sendResult);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    producer.shutdown();
}
 
Example #4
Source File: Validators.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
/**
 * Validate message
 *
 * @param msg
 * @param defaultMQProducer
 *
 * @throws com.alibaba.rocketmq.client.exception.MQClientException
 */
public static void checkMessage(Message msg, DefaultMQProducer defaultMQProducer)
        throws MQClientException {
    if (null == msg) {
        throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL, "the message is null");
    }
    // topic
    Validators.checkTopic(msg.getTopic());
    // body
    if (null == msg.getBody()) {
        throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL, "the message body is null");
    }

    if (0 == msg.getBody().length) {
        throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL, "the message body length is zero");
    }

    if (msg.getBody().length > defaultMQProducer.getMaxMessageSize()) {
        throw new MQClientException(ResponseCode.MESSAGE_ILLEGAL,
                "the message body size over max value, MAX: " + defaultMQProducer.getMaxMessageSize());
    }
}
 
Example #5
Source File: Producer.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
        DefaultMQProducer producer = new DefaultMQProducer("yyzGroup2");
        producer.setNamesrvAddr("10.2.223.157:9876;10.2.223.158:9876;10.2.223.159:9876");
       // producer.setNamesrvAddr("10.2.223.228:9876");
        producer.start();
        for(int i = 0; i < 111111; ++i) {
//            Thread.currentThread().sleep(50);
//            for (String item : array) {
            Message msg = new Message("yyztest2",// topic
                    "TAG",// tag
                    "ffff",// 注意, msgkey对帮助业务排查消息投递问题很有帮助,请设置成和消息有关的业务属性,比如订单id ,商品id .
                    "yang ya zhou".getBytes());// body //默认会设置等待消息存储成功。
            SendResult sendResult = null;
            try {//同步发送消息 ,并且等待消息存储成功,超时时间3s .
                System.out.println("send msg with msgKey:" + msg.getKeys());
                sendResult = producer.send(msg); //DefaultMQProducer.send
            } catch (Exception e) {
                e.printStackTrace();
            }
            System.out.println(sendResult);
            Thread.sleep(300);
        }
        System.out.println(System.getProperty("user.home") );
        producer.shutdown();
    }
 
Example #6
Source File: Producer.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");
    producer.start();

    try {
        for (int i = 0; i < 6000000; i++) {
            Message msg = new Message("TopicFilter7",// topic
                "TagA",// tag
                "OrderID001",// key
                ("Hello MetaQ").getBytes());// body

            msg.putUserProperty("SequenceId", String.valueOf(i));

            SendResult sendResult = producer.send(msg);
            System.out.println(sendResult);
        }
    }
    catch (Exception e) {
        e.printStackTrace();
    }

    producer.shutdown();
}
 
Example #7
Source File: RocketMQProducerAdapter.java    From uavstack with Apache License 2.0 6 votes vote down vote up
@Override
public void afterPreCap(InvokeChainContext context, Object[] args) {

    String storeKey = (String) context.get(InvokeChainConstants.CLIENT_SPAN_THREADLOCAL_STOREKEY);
    Span span = this.spanFactory.getSpanFromContext(storeKey);
    String spanMeta = this.spanFactory.getSpanMeta(span);

    Message msg = (Message) args[0];
    msg.putUserProperty(InvokeChainConstants.PARAM_MQHEAD_SPANINFO, spanMeta);

    if (UAVServer.instance().isExistSupportor("com.creditease.uav.apm.supporters.SlowOperSupporter")) {
        SlowOperContext slowOperContext = new SlowOperContext();
        String content;
        try {
            content = new String(msg.getBody(), "UTF-8");
        }
        catch (UnsupportedEncodingException e) {
            content = "unsupported encoding,defalut is utf-8.try to set ContentEncoding to fit.";
        }
        slowOperContext.put(SlowOperConstants.PROTOCOL_MQ_RABBIT_BODY, content);
        Object params[] = { span, slowOperContext };
        UAVServer.instance().runSupporter("com.creditease.uav.apm.supporters.SlowOperSupporter", "runCap",
                span.getEndpointInfo().split(",")[0], InvokeChainConstants.CapturePhase.PRECAP, context, params);
    }
}
 
Example #8
Source File: Producer.java    From rocketmq with Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");
    producer.start();

    try {
        for (int i = 0; i < 6000000; i++) {
            Message msg = new Message("TopicFilter7",// topic
                    "TagA",// tag
                    "OrderID001",// key
                    ("Hello MetaQ").getBytes(RemotingHelper.DEFAULT_CHARSET));// body

            msg.putUserProperty("SequenceId", String.valueOf(i));

            SendResult sendResult = producer.send(msg);
            System.out.println(sendResult);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    producer.shutdown();
}
 
Example #9
Source File: Producer.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    CommandLine commandLine = buildCommandline(args);
    if (commandLine != null) {
        String group = commandLine.getOptionValue('g');
        String topic = commandLine.getOptionValue('t');
        String tags = commandLine.getOptionValue('a');
        String keys = commandLine.getOptionValue('k');
        String msgCount = commandLine.getOptionValue('c');

        DefaultMQProducer producer = new DefaultMQProducer(group);
        producer.setInstanceName(Long.toString(System.currentTimeMillis()));

        producer.start();

        for (int i = 0; i < Integer.parseInt(msgCount); i++) {
            try {
                Message msg = new Message(//
                    topic, // topic
                    tags, // tag
                    keys, // key
                    ("Hello RocketMQ " + i).getBytes());// body
                SendResult sendResult = producer.send(msg);

                System.out.printf("%-8d %s\n", i, sendResult);
            }
            catch (Exception e) {
                e.printStackTrace();
                Thread.sleep(1000);
            }
        }

        producer.shutdown();
    }
}
 
Example #10
Source File: SelectMessageQueueByRandoom.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
@Override
public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
    int value = random.nextInt();
    if (value < 0) {
        value = Math.abs(value);
    }

    value = value % mqs.size();
    return mqs.get(value);
}
 
Example #11
Source File: SelectMessageQueueByHash.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
    int value = arg.hashCode();
    if (value < 0) {
        value = Math.abs(value);
    }

    value = value % mqs.size();
    return mqs.get(value);
}
 
Example #12
Source File: SelectMessageQueueByRandoom.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
@Override
public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
    int value = random.nextInt();
    if (value < 0) {
        value = Math.abs(value);
    }

    value = value % mqs.size();
    return mqs.get(value);
}
 
Example #13
Source File: Producer.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
private static Message buildMessage(final int messageSize) {
    Message msg = new Message();
    msg.setTopic("BenchmarkTest");

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < messageSize; i += 10) {
        sb.append("hello baby");
    }

    msg.setBody(sb.toString().getBytes());

    return msg;
}
 
Example #14
Source File: RocketMQProducerService.java    From onetwo with Apache License 2.0 5 votes vote down vote up
protected void handleException(Throwable e, Message message){
	String errorMsg = "send message error. topic:"+message.getTopic()+", tags:"+message.getTags();
	logger.error(errorMsg);
	if(errorHandler!=null){
		errorHandler.accept(e);
	}else{
		throw new ServiceException(errorMsg, e);
	}
}
 
Example #15
Source File: TransactionExecuterImpl.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Override
public LocalTransactionState executeLocalTransactionBranch(final Message msg, final Object arg) {
    int value = transactionIndex.getAndIncrement();

    if (value == 0) {
        throw new RuntimeException("Could not find db");
    } else if ((value % 5) == 0) {
        return LocalTransactionState.ROLLBACK_MESSAGE;
    } else if ((value % 4) == 0) {
        return LocalTransactionState.COMMIT_MESSAGE;
    }

    return LocalTransactionState.UNKNOW;
}
 
Example #16
Source File: MQClientAPIImpl.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
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
) throws RemotingException, MQBrokerException, InterruptedException {
    RemotingCommand request = null;
    if (sendSmartMsg) {
        SendMessageRequestHeaderV2 requestHeaderV2 = SendMessageRequestHeaderV2.createSendMessageRequestHeaderV2(requestHeader);
        request = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE_V2, requestHeaderV2);
    }
    else { //组装头部信息
        request = RemotingCommand.createRequestCommand(RequestCode.SEND_MESSAGE, requestHeader);
    }

    request.setBody(msg.getBody()); //包体body信息赋值

    switch (communicationMode) {
    case ONEWAY:
        this.remotingClient.invokeOneway(addr, request, timeoutMillis);
        return null;
    case ASYNC:
        this.sendMessageAsync(addr, brokerName, msg, timeoutMillis, request, sendCallback);
        return null;
    case SYNC:
        return this.sendMessageSync(addr, brokerName, msg, timeoutMillis, request);
    default:
        assert false;
        break;
    }

    return null;
}
 
Example #17
Source File: MQClientAPIImpl.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
private void sendMessageAsync(//
        final String addr,//
        final String brokerName,//
        final Message msg,//
        final long timeoutMillis,//
        final RemotingCommand request,//
        final SendCallback sendCallback//
) throws RemotingException, InterruptedException {
    this.remotingClient.invokeAsync(addr, request, timeoutMillis, new InvokeCallback() {
        @Override
        public void operationComplete(ResponseFuture responseFuture) {
            if (null == sendCallback)
                return;

            RemotingCommand response = responseFuture.getResponseCommand();
            if (response != null) {
                try {
                    SendResult sendResult = MQClientAPIImpl.this.processSendResponse(brokerName, msg, response);
                    assert sendResult != null;
                    sendCallback.onSuccess(sendResult);
                }
                catch (Exception e) {
                    sendCallback.onException(e);
                }
            }
            else {
                if (!responseFuture.isSendRequestOK()) {
                    sendCallback.onException(new MQClientException("send request failed", responseFuture.getCause()));
                }
                else if (responseFuture.isTimeout()) {
                    sendCallback.onException(new MQClientException("wait response timeout " + responseFuture.getTimeoutMillis() + "ms",
                        responseFuture.getCause()));
                }
                else {
                    sendCallback.onException(new MQClientException("unknow reseaon", responseFuture.getCause()));
                }
            }
        }
    });
}
 
Example #18
Source File: TransactionProducer.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {

        //事务决断处理类
        TransactionCheckListener transactionCheckListener = new TransactionCheckListenerImpl();
        TransactionMQProducer producer = new TransactionMQProducer("please_rename_unique_group_name");
        producer.setCheckThreadPoolMinSize(2);
        producer.setCheckThreadPoolMaxSize(2);
        producer.setCheckRequestHoldMax(2000);
        producer.setTransactionCheckListener(transactionCheckListener);
        producer.start();

        String[] tags = new String[] { "TagA", "TagB", "TagC", "TagD", "TagE" };
        TransactionExecuterImpl tranExecuter = new TransactionExecuterImpl();
        for (int i = 0; i < 100; i++) {
            try {
                Message msg =
                        new Message("TopicTest", tags[i % tags.length], "KEY" + i,
                            ("Hello RocketMQ " + i).getBytes());
                SendResult sendResult = producer.sendMessageInTransaction(msg, tranExecuter, null);
                System.out.println(sendResult);

                Thread.sleep(10);
            }
            catch (MQClientException e) {
                e.printStackTrace();
            }
        }

        for (int i = 0; i < 100000; i++) {
            Thread.sleep(1000);
        }

        producer.shutdown();

    }
 
Example #19
Source File: RocketMqTracingCollector.java    From dubbo-plus with Apache License 2.0 5 votes vote down vote up
@Override
public void push(List<Span> spanList) {
    byte[] bytes = JSON.toJSONBytes(spanList);
    Message message = new Message(DstConstants.ROCKET_MQ_TOPIC,bytes);
    try {
        SendResult sendResult = defaultMQProducer.send(message);
        if(sendResult.getSendStatus()!= SendStatus.SEND_OK){
            logger.error("send mq message return ["+sendResult.getSendStatus()+"]");
        }
    } catch (Exception e) {
        logger.error("fail to send message.",e);
    }
}
 
Example #20
Source File: SelectMessageQueueByRandoom.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Override
public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
    int value = random.nextInt();
    if (value < 0) {
        value = Math.abs(value);
    }

    value = value % mqs.size();
    return mqs.get(value);
}
 
Example #21
Source File: ProducerTemplate.java    From easyooo-framework with Apache License 2.0 5 votes vote down vote up
/**
 * 发送消息
 * @param topic 对列名
 * @param tag 只支持设置一个Tag(服务端消息过滤使用)
 * @param key 关键字查询使用
 * @param body 消息体
 * @return
 * @throws Throwable
 */
public boolean send(String topic, String tag, String key, String body) throws Throwable{
	// topic is required
	if(StringUtils.isEmpty(topic)){
		return false;
	}
	// body is required
	if(StringUtils.isEmpty(body)){
		return false;
	}
	
	byte[] byteData = body.getBytes();
	Message msg = new Message(topic, tag, key, byteData);
	return sender.send(msg);
}
 
Example #22
Source File: Producer.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
    CommandLine commandLine = buildCommandline(args);
    if (commandLine != null) {
        String group = commandLine.getOptionValue('g');
        String topic = commandLine.getOptionValue('t');
        String tags = commandLine.getOptionValue('a');
        String keys = commandLine.getOptionValue('k');
        String msgCount = commandLine.getOptionValue('c');

        DefaultMQProducer producer = new DefaultMQProducer(group);
        producer.setInstanceName(Long.toString(System.currentTimeMillis()));

        producer.start();

        for (int i = 0; i < Integer.parseInt(msgCount); i++) {
            try {
                Message msg = new Message(//
                    topic,// topic
                    tags,// tag
                    keys,// key
                    ("Hello RocketMQ " + i).getBytes());// body
                SendResult sendResult = producer.send(msg);

                System.out.printf("%-8d %s\n", i, sendResult);
            }
            catch (Exception e) {
                e.printStackTrace();
                Thread.sleep(1000);
            }
        }

        producer.shutdown();
    }
}
 
Example #23
Source File: SendMsgStatusCommand.java    From reading-and-annotate-rocketmq-3.4.6 with GNU General Public License v3.0 5 votes vote down vote up
private static Message buildMessage(final String topic, final int messageSize) {
    Message msg = new Message();
    msg.setTopic(topic);

    StringBuilder sb = new StringBuilder();
    for (int i = 0; i < messageSize; i += 11) {
        sb.append("hello jodie");
    }
    msg.setBody(sb.toString().getBytes());
    return msg;
}
 
Example #24
Source File: RocketmqIT.java    From uavstack with Apache License 2.0 5 votes vote down vote up
private String getTopic(Object mqClient, String methodName, Object args[]) {

        if ("send".equals(methodName)) {
            Message message = (Message) args[0];
            return message.getTopic();
        }
        else if (queueNameIndex.containsKey(methodName)) {
            return (String) args[queueNameIndex.get(methodName)];
        }
        return null;
    }
 
Example #25
Source File: TestProducer.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {

        DefaultMQProducer producer = new DefaultMQProducer("ProducerGroupName");

        producer.start();

        for (int i = 0; i < 1; i++)
            try {
                {
                    Message msg = new Message("TopicTest1",// topic
                            "TagA",// tag
                            "key113",// key
                            ("Hello MetaQ").getBytes(RemotingHelper.DEFAULT_CHARSET));// body
                    SendResult sendResult = producer.send(msg);
                    System.out.println(sendResult);

                    QueryResult queryMessage =
                            producer.queryMessage("TopicTest1", "key113", 10, 0, System.currentTimeMillis());
                    for (MessageExt m : queryMessage.getMessageList()) {
                        System.out.println(m);
                    }
                }

            } catch (Exception e) {
                e.printStackTrace();
            }

        producer.shutdown();
    }
 
Example #26
Source File: TransactionProducer.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Override
public LocalTransactionState executeLocalTransactionBranch(final Message msg, final Object arg) {
    if (ischeck) {
        return LocalTransactionState.UNKNOW;
    }
    return LocalTransactionState.COMMIT_MESSAGE;
}
 
Example #27
Source File: TransactionMQProducer.java    From RocketMQ-Master-analyze with Apache License 2.0 5 votes vote down vote up
@Override
public TransactionSendResult sendMessageInTransaction(final Message msg,
        final LocalTransactionExecuter tranExecuter, final Object arg) throws MQClientException {
    if (null == this.transactionCheckListener) {
        throw new MQClientException("localTransactionBranchCheckListener is null", null);
    }

    return this.defaultMQProducerImpl.sendMessageInTransaction(msg, tranExecuter, arg);
}
 
Example #28
Source File: MQProducer.java    From RocketMQ-Master-analyze with Apache License 2.0 4 votes vote down vote up
void send(final Message msg, final MessageQueueSelector selector, final Object arg,
final SendCallback sendCallback, final long timeout)
        throws MQClientException, RemotingException, InterruptedException;
 
Example #29
Source File: MQProducer.java    From RocketMQ-Master-analyze with Apache License 2.0 4 votes vote down vote up
SendResult send(final Message msg, final MessageQueue mq, final long timeout)
throws MQClientException, RemotingException, MQBrokerException, InterruptedException;
 
Example #30
Source File: MQProducer.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
SendResult send(final Message msg, final long timeout) throws MQClientException,
RemotingException, MQBrokerException, InterruptedException;