1. 程式人生 > 實用技巧 >rabbitmq傳送訊息的兩種格式:傳送json資料和直接傳送物件以及對json與物件之間的相互轉換

rabbitmq傳送訊息的兩種格式:傳送json資料和直接傳送物件以及對json與物件之間的相互轉換

前奏:json格式字串與Java物件的相互轉換方法

第一種:com.fasterxml.jackson.databind.ObjectMapper 包

import com.fasterxml.jackson.databind.ObjectMapper;

ObjectMapper objectMapper = new ObjectMapper();
//json字串轉成Java物件
Myclass myclass = objectMapper.readValue(jsonStr , Myclass.class); 

//Java物件轉成json字串
String jsonStr = objectMapper.writeValueAsString(myclass);

第二種: com.alibaba.fastjson.JSONObject 包

import com.alibaba.fastjson.JSONObject;

// json轉換成java物件
Myclass myclass = JSONObject.parseObject(jsonStr , Myclass.class);

//java物件轉換成json
String jsonObject = JSONObject.toJSONString(myclass);

第三種:net.sf.json.JSONObject 包

import net.sf.json.JSONObject;

JSONObject jsonobject = JSONObject.fromObject(jsonStr);
//json字串轉成java物件
Myclass myclass = (MYclass)JSONObject.toBean(jsonobject,Myclass.class);

//java物件轉換成json
JSONObject jsonStu = JSONObject.fromObject(testMQ);
String javaToJson=jsonStu.toString();

第四種:net.sf.json.JSONArray 包

import net.sf.json.JSONArray;

//把JSON字串轉換為JAVA物件陣列
JSONArray json = JSONArray.fromObject(userStr);//userStr是json字串

List<Myclass> myclasses = (List<Myclass>)JSONArray.toCollection(json,Myclass.class);

第一種:生產者傳送json格式資料(將物件轉成json然後傳送,或者直接傳送json資料),消費者接收json格式然後轉換成物件進行消費。

第二種:生產者直接傳送物件資料,消費者接收物件並進行消費。
需要注意的是,當生產者傳送物件的話,需要將物件序列化,消費者將物件進行反序列化即可。

生產者類

public class TestMQ implements Serializable {
    private String name;
    private Integer age;
    //setter/getter以及toString()方法
}

傳送訊息的介面

/**
 * 傳送訊息的介面,如果要傳送訊息就實現這個介面
 * @author Administrator
 */
public interface MQProducer {
    /**
     * 傳送訊息到指定佇列
     * @param queueKey
     * @param 
     */
    public void sendDataToQueue(String exchange, String queueKey, Object object);
}
/**
	 * 這裡使用rabbitmq是通過配置檔案的形式進行使用的
	 * 主要的內容是:在rabbitmq.xml中配置佇列的相關資訊例如connection、exchange等以及佇列訊息的監聽器等相關配置
	 * 定義一個傳送訊息的介面,使用時實現這個介面,在實現類裡重寫AmqpTemplate amqpTemplate 的sendDataToQueue方法。
	 *
	 * @throws Exception
	 */
@Test
public void MQProducer() throws Exception{
    String exchangeName="clsExchange";
    String bindingKey="merchant.queue.jasonqueue";
    //需要傳送的物件
    TestMQ testMQ=new TestMQ();
    testMQ.setAge(8101);
    testMQ.setName("javatojson");
   	//將物件通過位元組流和物件輸出流寫出去
    ByteArrayOutputStream bo = new ByteArrayOutputStream();
    ObjectOutputStream oo = new ObjectOutputStream(bo);
    oo.writeObject(testMQ);
    byte[] javaByte=bo.toByteArray();

    //生產者直接傳送物件
    rabbitMQProducer.sendDataToQueue(exchangeName,bindingKey,javaByte);
}

通過監聽消費這個訊息

import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageListener;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;

public class TestClsConsumer implements MessageListener  {
    @Override
    public void onMessage(Message message) {
        //位元組碼轉化為物件
        byte[] bytes=message.getBody();
        ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
        ObjectInputStream oi = null;
        try {
            oi = new ObjectInputStream(bi);
            TestMQ testMQ=(TestMQ) oi.readObject();
            System.out.println("消費者直接接收物件進行消費(進行處理一些業務):"+testMQ.getName());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

參考博文:
(1) https://www.cnblogs.com/fpqi/p/9722235.html (json格式轉換成物件相關方法)
(2) https://blog.csdn.net/east123321/article/details/78900791?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.compare&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-3.compare (rabbitmq傳送物件)