rocketMq 事务消息

↘锁芯ラ 提交于 2020-04-08 14:35:09

事务消息 实现TransactionListener

package com.topnet.demo.mq.Transaction;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import org.apache.rocketmq.client.producer.LocalTransactionState;
import org.apache.rocketmq.client.producer.TransactionListener;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.topnet.demo.bean.User;
import com.topnet.demo.service.UserService;

@Component
public class TransactionListenerImpl implements TransactionListener {
	@Autowired
	UserService userService;
    @Override
    public LocalTransactionState executeLocalTransaction(Message msg, Object arg) {
    	String str=null;
    	try {
			  str=new String( msg.getBody(),RemotingHelper.DEFAULT_CHARSET) ;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
    	User u = JSON.parseObject(str, User.class);
    	userService.saveUser(u);
        return LocalTransactionState.UNKNOW;

    }

    @Override
    public LocalTransactionState checkLocalTransaction(MessageExt msg) {
 		
		  String str=null; try { str=new String(
		  msg.getBody(),RemotingHelper.DEFAULT_CHARSET) ; } catch
		  (UnsupportedEncodingException e) { e.printStackTrace(); } User u =
		  JSON.parseObject(str, User.class); 
		    Map<String, Object> m = userService.queryUser(u.getId());
		  System.out.println("---------------------------------");
		  System.out.println(m);
		  if (m!=null) { return
				  LocalTransactionState.COMMIT_MESSAGE; 
		  } 
		  return LocalTransactionState.UNKNOW;
		 
    }
}

 

 

生产端Product

package com.topnet.demo.mq.Transaction;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.client.producer.TransactionMQProducer;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.remoting.common.RemotingHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.topnet.demo.bean.User;

@Component
public class TransactionProducer {
	@Autowired
	TransactionListenerImpl transactionListenerImpl;
	public   void send(User u) {
        TransactionMQProducer producer = new TransactionMQProducer("test_producer");
		  producer.setNamesrvAddr("localhost:9876");
        ExecutorService executorService = new ThreadPoolExecutor(2, 5, 100, TimeUnit.SECONDS, new ArrayBlockingQueue<Runnable>(2000), new ThreadFactory() {
			
			@Override
			public Thread newThread(Runnable r) {
				// TODO Auto-generated method stub
				return new Thread("thread");
			}
		});
        producer.setExecutorService(executorService);
        producer.setTransactionListener(transactionListenerImpl);
        try {
			producer.start();
	            try {
	                Message msg =
	                    new Message("TopicTest","TagA",  JSON.toJSONString( u).getBytes(RemotingHelper.DEFAULT_CHARSET ));
	                SendResult sendResult = producer.sendMessageInTransaction(msg, null);
	                System.out.printf("%s%n", sendResult);
	            } catch ( Exception e) {
	                e.printStackTrace();
	            }
	     
            Thread.sleep(1000*60);
	        producer.shutdown();
		} catch ( Exception e) {
			e.printStackTrace();
		}
	}
	
	public void send2(User u) {
	        TransactionMQProducer producer = new TransactionMQProducer("test_producer");
			  producer.setNamesrvAddr("localhost: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(transactionListenerImpl);
 	            try {
 	            	 producer.start();
 	            	 Message msg =
 		                    new Message("TopicTest","TagA",  JSON.toJSONString( u).getBytes(RemotingHelper.DEFAULT_CHARSET ));
	                SendResult sendResult = producer.sendMessageInTransaction(msg, null);
	                System.out.printf("%s%n", sendResult);
    	            Thread.sleep(1000*100000);
	    	        producer.shutdown();
	            } catch ( Exception e) {
	                e.printStackTrace();
	            }

	      
		
	}
	
	
}

 

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!