Java Code Examples for org.apache.rocketmq.client.producer.TransactionMQProducer#setNamesrvAddr()

The following examples show how to use org.apache.rocketmq.client.producer.TransactionMQProducer#setNamesrvAddr() . 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: OrderStatusUpdateProducer.java    From order-charge-notify with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    // 初始化回查线程池
    executorService = new ThreadPoolExecutor(
            5,
            512,
            10000L,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(512),
            runnable -> {
                Thread thread = new Thread(runnable);
                thread.setName(MessageProtocolConst.ORDER_STATUS_UPDATE_TOPIC.getProducerGroup() + "-check-thread");
                return null;
            });

    transactionMQProducer = new TransactionMQProducer(MessageProtocolConst.ORDER_STATUS_UPDATE_TOPIC.getProducerGroup());
    transactionMQProducer.setNamesrvAddr(nameSrvAddr);
    transactionMQProducer.setExecutorService(executorService);
    transactionMQProducer.setTransactionListener(transactionListener);
    try {
        transactionMQProducer.start();
    } catch (MQClientException e) {
        throw new RuntimeException("启动[订单状态修改生产者]OrderStatusUpdateProducer异常", e);
    }
    LOGGER.info("启动[订单状态修改生产者]OrderStatusUpdateProducer成功, topic={}", MessageProtocolConst.ORDER_STATUS_UPDATE_TOPIC.getTopic());
}
 
Example 2
Source File: ChargeOrderPaymentTranProducer.java    From order-charge-notify with Apache License 2.0 6 votes vote down vote up
@PostConstruct
public void init() {
    // 初始化回查线程池
    executorService = new ThreadPoolExecutor(
            5,
            512,
            10000L,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue<>(512),
            runnable -> {
                Thread thread = new Thread(runnable);
                thread.setName(MessageProtocolConst.WALLET_PAYMENT_TOPIC.getProducerGroup() + "-check-thread");
                return null;
            });

    transactionMQProducer = new TransactionMQProducer(MessageProtocolConst.WALLET_PAYMENT_TOPIC.getProducerGroup());
    transactionMQProducer.setNamesrvAddr(nameSrvAddr);
    transactionMQProducer.setExecutorService(executorService);
    transactionMQProducer.setTransactionListener(transactionListener);
    try {
        transactionMQProducer.start();
    } catch (MQClientException e) {
        throw new RuntimeException("启动[扣款事务消息生产者]ChargeOrderPaymentTranProducer异常", e);
    }
    LOGGER.info("启动[扣款事务消息生产者]ChargeOrderPaymentTranProducer成功, topic={}", MessageProtocolConst.WALLET_PAYMENT_TOPIC.getTopic());
}
 
Example 3
Source File: BootstrapConfiguration.java    From j360-boot-app-all with Apache License 2.0 6 votes vote down vote up
@Bean
public TransactionMQProducer transactionMQProducer() throws MQClientException {
    TransactionMQProducer producer = new TransactionMQProducer();
    RocketMQProperties.Producer producerConfig = rocketMQProperties.getProducer();
    String groupName = producerConfig.getGroup();
    Assert.hasText(groupName, "[spring.rocketmq.producer.group] must not be null");

    producer.setNamesrvAddr(rocketMQProperties.getNameServer());
    producer.setSendMsgTimeout(producerConfig.getSendMsgTimeout());
    producer.setRetryTimesWhenSendFailed(producerConfig.getRetryTimesWhenSendFailed());
    producer.setRetryTimesWhenSendAsyncFailed(producerConfig.getRetryTimesWhenSendAsyncFailed());
    producer.setMaxMessageSize(producerConfig.getMaxMessageSize());
    producer.setCompressMsgBodyOverHowmuch(producerConfig.getCompressMsgBodyOverHowmuch());
    producer.setRetryAnotherBrokerWhenNotStoreOK(producerConfig.isRetryAnotherBrokerWhenNotStoreOk());
    producer.setTransactionListener(new TxListener());
    producer.setProducerGroup(rocketMQProperties.getProducer().getGroup());
    producer.start();
    return producer;
}
 
Example 4
Source File: RocketMQConfig.java    From SpringMVC-Project with MIT License 5 votes vote down vote up
@Override
public void afterPropertiesSet() throws MQClientException {
    clearUserProducer = new TransactionMQProducer(clearUserGroup);
    clearUserProducer.setNamesrvAddr(nameServerAddress);
    ExecutorService executorService = new ThreadPoolExecutor(2, 5, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<>(2000), r -> {
        Thread thread = new Thread(r);
        thread.setName("client-transaction-msg-check-thread");
        return thread;
    });
    clearUserProducer.setExecutorService(executorService);
    clearUserProducer.setTransactionListener(applicationContext.getAutowireCapableBeanFactory().getBean(ClearUserTransactionListener.class));
    clearUserProducer.start();

    clearUserConsumer = new DefaultMQPushConsumer(clearUserGroup);
    clearUserConsumer.setNamesrvAddr(nameServerAddress);
    clearUserConsumer.subscribe(clearUserTopic, "*");
    clearUserConsumer.registerMessageListener(applicationContext.getAutowireCapableBeanFactory().getBean(ClearUserMessageListener.class));
    clearUserConsumer.start();

    chatRecordProducer = new DefaultMQProducer(chatRecordGroup);
    chatRecordProducer.setNamesrvAddr(nameServerAddress);
    chatRecordProducer.start();

    chatRecordConsumer = new DefaultMQPushConsumer(chatRecordGroup);
    chatRecordConsumer.setNamesrvAddr(nameServerAddress);
    chatRecordConsumer.subscribe(chatRecordTopic, chatRecordTags);
    chatRecordConsumer.registerMessageListener(applicationContext.getAutowireCapableBeanFactory().getBean(ChatRecordMessageListener.class));
    chatRecordConsumer.start();
}
 
Example 5
Source File: TransactionProducerTest.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {
	TransactionListener transactionListener = new TransactionListenerImpl();
	TransactionMQProducer producer = new TransactionMQProducer("transactionProducerGroupName");
	producer.setNamesrvAddr("192.168.237.128:9876");
	ExecutorService executorService = new ThreadPoolExecutor(2, 5, 100, TimeUnit.SECONDS,
			new ArrayBlockingQueue<Runnable>(2000), new ThreadFactory() {
				@Override
				public Thread newThread(Runnable r) {
					Thread thread = new Thread(r);
					thread.setName("client-transaction-msg-check-thread");
					return thread;
				}
			});

	producer.setExecutorService(executorService);
	producer.setTransactionListener(transactionListener);
	producer.start();

	String[] tags = new String[] { "TagA", "TagB", "TagC", "TagD", "TagE" };
	for (int i = 0; i < 1; i++) {
		try {
			Message msg = new Message("TopicTest1234", tags[i % tags.length], "KEY" + i,
					("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
			System.out.println("start send message " + msg);
			SendResult sendResult = producer.sendMessageInTransaction(msg, null);
			System.out.printf("%s%n", sendResult);

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

	for (int i = 0; i < 100000; i++) {
		Thread.sleep(1000);
	}
	producer.shutdown();
}
 
Example 6
Source File: RMQTransactionalProducer.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
protected void create(boolean useTLS, TransactionListener transactionListener) {
    producer = new TransactionMQProducer();
    producer.setProducerGroup(getProducerGroupName());
    producer.setInstanceName(getProducerInstanceName());
    producer.setTransactionListener(transactionListener);
    producer.setUseTLS(useTLS);

    if (nsAddr != null) {
        producer.setNamesrvAddr(nsAddr);
    }
}
 
Example 7
Source File: RocketmqFactory.java    From framework with Apache License 2.0 5 votes vote down vote up
/**
 * Description: 初始化向rocketmq发送事务消息的生产者<br>
 * 
 * @author 王伟<br>
 * @taskId <br>
 * @return TransactionMQProducer
 * @throws MQClientException <br>
 */
public static TransactionMQProducer getTransactionProducer() throws MQClientException {

    /*
     * 一个应用创建一个Producer,由应用来维护此对象,可以设置为全局对象或者单例<br> 注意:ProducerGroupName需要由应用来保证唯一<br>
     * ProducerGroup这个概念发送普通的消息时,作用不大,但是发送分布式事务消息时,比较关键, 因为服务器会回查这个Group下的任意一个Producer
     */
    // Producer Group Name
    TransactionMQProducer producer = new TransactionMQProducer(
        PropertyHolder.getProperty("message.rocketmq.producer.transactionProducerGroupName"));

    // Name service address
    producer.setNamesrvAddr(PropertyHolder.getProperty("message.rocketmq.namesrvAddr"));

    // Defalut value ip@pid when not set , this key used for cluster
    // producer.setInstanceName(properties.getProducerTranInstanceName());

    // Retry times
    producer.setRetryTimesWhenSendAsyncFailed(RETRY_TIMES);

    // 事务回查最小并发数
    // producer.setCheckThreadPoolMinSize(2);
    // 事务回查最大并发数
    // producer.setCheckThreadPoolMaxSize(2);
    // 队列数
    // producer.setCheckRequestHoldMax(2000);

    // TODO 由于社区版本的服务器阉割调了消息回查的功能,所以这个地方没有意义
    // TransactionCheckListener transactionCheckListener = new
    // TransactionCheckListenerImpl();
    // producer.setTransactionCheckListener(transactionCheckListener);

    /*
     * Producer对象在使用之前必须要调用start初始化,初始化一次即可<br> 注意:切记不可以在每次发送消息时,都调用start方法
     */
    producer.start();

    LOG.debug("RocketMq TransactionMQProducer Started.");
    return producer;
}
 
Example 8
Source File: TransactionProducer.java    From java-tutorial with MIT License 4 votes vote down vote up
public static void main(String[] args) throws MQClientException, InterruptedException {

        TransactionListener transactionListener = new TransactionListenerImpl();
        TransactionMQProducer producer = new TransactionMQProducer("transaction_Producer");
        producer.setNamesrvAddr(NAMESRVADDR);

        ExecutorService executorService = new ThreadPoolExecutor(2, 5, 100,
                TimeUnit.SECONDS, new ArrayBlockingQueue<>(2000), new ThreadFactory() {
            @Override
            public Thread newThread(Runnable r) {
                Thread thread = new Thread(r);
                thread.setName("client-transaction-msg-check-thread");
                return thread;
            }
        });

        producer.setExecutorService(executorService);
        producer.setTransactionListener(transactionListener);
        producer.start();

        String[] tags = new String[]{"TagA", "TagB", "TagC", "TagD", "TagE"};
        for (int i = 0; i < 10; i++) {
            try {
                Message message = new Message("TopicTransactionTest", tags[i % tags.length],
                        "KEY" + i, ("Hello RocketMQ " + i).getBytes(RemotingHelper.DEFAULT_CHARSET));
                SendResult sendResult = producer.sendMessageInTransaction(message, null);
                System.out.printf("%s%n", sendResult);

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

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

        producer.shutdown();

    }
 
Example 9
Source File: TransactionProducer.java    From rocketmq_trans_message with Apache License 2.0 4 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.setNamesrvAddr("127.0.0.1:9876");
     producer.setNamesrvAddr("testserver004:9876");
    producer.setTransactionCheckListener(transactionCheckListener);
    producer.start();


    String[] tags = new String[]{"TagA", "TagB", "TagC", "TagD", "TagE"};
    TransactionExecuterImpl tranExecuter = new TransactionExecuterImpl();
    ExecutorService executorService = Executors.newFixedThreadPool(20);
    for (int j = 0; j < 5000; j++) {
        final int i = j;
        executorService.submit(new Runnable() {
            @Override
            public void run() {
                try {
                    int xx = i;
                    Message msg =
                            new Message("TransactionTest", tags[i % tags.length], "KEY" + i,
                                    String.valueOf(xx).getBytes(RemotingHelper.DEFAULT_CHARSET));
                    long startTime = System.currentTimeMillis();
                    msg.putUserProperty(PropertyKeyConst.CheckImmunityTimeInSeconds, "30");
                    //producer.send(msg);
                    SendResult sendResult = producer.sendMessageInTransaction(msg, tranExecuter, i);
                    //System.out.println("发送消息:" + sendResult + ",消耗时间:" + (System.currentTimeMillis() - startTime) + "ms");
                    System.out.println("发送消息:" + xx + ",消耗时间:" + (System.currentTimeMillis() - startTime) + "ms");
                    statsMap.put(i, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

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