pbootcms网站模板|日韩1区2区|织梦模板||网站源码|日韩1区2区|jquery建站特效-html5模板网

使用 RabbitMQ 發送對象

Send an object using RabbitMQ(使用 RabbitMQ 發送對象)
本文介紹了使用 RabbitMQ 發送對象的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!

問題描述

限時送ChatGPT賬號..

我知道這個問題與問題重復使用rabbitmq發送消息不是字符串而是結構

I Understand that this question duplicates question at using rabbitmq to send a message not string but struct

如果使用第一種方法來做到這一點

if to do this using the first way

第一種方式

我有以下痕跡:

java.io.EOFException
at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2304)
at java.io.ObjectInputStream$BlockDataInputStream.readShort(ObjectInputStream.java:2773)
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:798)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:298)
at com.mdnaRabbit.worker.data.Data.fromBytes(Data.java:78)
at com.mdnaRabbit.worker.App.main(App.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)

我已經檢查并確認該消息在發送者類中絕對可以很好地轉換為字節,但消費者無法接收它.

I've checked and shure that message is transformd to bytes absolutely well in sender class, but the consumer can't receive it.

這是我的制作人課程:

package com.mdnaRabbit.newt;

import java.io.IOException;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.MessageProperties;
import org.apache.commons.lang.SerializationUtils;
import com.mdnaRabbit.worker.data.Data;

public class App {

    private static final String TASK_QUEUE_NAME = "task_queue";

    public static void main( String[] argv) throws IOException{

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);

        int i = 0;

        do {
            Data message = getMessage();
            byte [] byteMessage = message.getBytes();
            //System.out.println(byteMessage);
            channel.basicPublish("", TASK_QUEUE_NAME, MessageProperties.PERSISTENT_TEXT_PLAIN, byteMessage);
            System.out.println(" [" + (i+1) + "] message Sent" + Data.fromBytes(byteMessage).getBody());
            i++;
        } while (i<15);

        channel.close();
        connection.close();
    }

    private static Data getMessage(){
        Data data = new Data();
        data.setHeader("header");
        data.setDomainId("abc.com");
        data.setReceiver("me");
        data.setSender("he");
        data.setBody("body");
        return data;
    }

    private static String joinStrings(String[] strings, String delimiter){
        int length = strings.length;
        if (length == 0) return "";
        StringBuilder words = new StringBuilder(strings[0]);
        for (int i = 1; i < length; i++){
            words.append(delimiter).append(strings[i]);
        }
        return words.toString();
    }
}

這是我的消費類:

    package com.mdnaRabbit.worker;

import java.io.IOException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;
import com.mdnaRabbit.worker.data.Data;
import org.apache.commons.lang.SerializationUtils;

public class App {

    private static final String TASK_QUEUE_NAME = "task_queue";
    private static int i = 0;
    public static void main( String[] argv )
            throws IOException,
            InterruptedException{

        ExecutorService threader = Executors.newFixedThreadPool(20);
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection(threader);
        final Channel channel = connection.createChannel();

        channel.queueDeclare(TASK_QUEUE_NAME, true, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        channel.basicQos(20);

        final QueueingConsumer consumer = new QueueingConsumer(channel);
        channel.basicConsume(TASK_QUEUE_NAME, false, consumer);

        try {

            while (true) {

                        try {QueueingConsumer.Delivery delivery = consumer.nextDelivery();
                            Data message = Data.fromBytes(delivery.getBody());
                            //Data message = (Data) SerializationUtils.deserialize(delivery.getBody());

                            System.out.println(" [" + (i++) +"] Received" + message.getBody());

                            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
                        }catch (Exception e){
                        }
                    }
        } catch (Exception e){
            e.printStackTrace();
        }
        channel.close();
        connection.close();
    }

}

這是我的數據類:

package com.mdnaRabbit.worker.data;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Data implements Serializable{

    public String header;
    public String body;
    public String domainId;
    public String sender;
    public String receiver;

    public void setHeader(String head){
        this.header = head;
    }

    public String getHeader(){
        return header;
    }

    public void setBody(String body){
        this.body = body;
    }

    public String getBody(){
        return body;
    }

    public void setDomainId(String domainId){
        this.domainId = domainId;
    }

    public String getDomainId(){
        return domainId;
    }

    public void setSender(String sender){
        this.sender = sender;
    }

    public String getSender(){
        return sender;
    }

    public String getReceiver(){
        return receiver;
    }

    public void setReceiver(String receiver){
        this.receiver = receiver;
    }


    public byte[] getBytes() {
        byte[]bytes;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try{
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(this);
            oos.flush();
            oos.reset();
            bytes = baos.toByteArray();
            oos.close();
            baos.close();
        } catch(IOException e){
            bytes = new byte[] {};
            Logger.getLogger("bsdlog").log(Level.ALL, "unable to write to output stream" + e);
        }
        return bytes;
    }

    public static Data fromBytes(byte[] body) {
        Data obj = null;
        try {
            ByteArrayInputStream bis = new ByteArrayInputStream(body);
            ObjectInputStream ois = new ObjectInputStream(bis);
            obj = (Data) ois.readObject();
            ois.close();
            bis.close();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (ClassNotFoundException ex) {
            ex.printStackTrace();
        }
        return obj;
    }
}

我似乎總是消費者收到消息,因為當我不嘗試將其轉換為對象時,只是寫System.out.println(delivery.getBody)它顯示字節

I always seems that consumer receives messages, because when I'm not trying to transform it into the object and just write System.out.println(delivery.getBody) it shows bytes

推薦答案

你收到的字節數組好像是空的.這是因為:

It looks like the byte array you receive is empty. This happens because of this:

    } catch(IOException e){
        bytes = new byte[] {};
    }

產生異常時,代碼不會警告您某些內容已損壞,而是發送一個空數組.您至少應該記錄錯誤.

When an exception is produced, the code doesn't warn you that something is broken and just sends an empty array instead. You should at least log the error.

產生異常可能是因為您試圖序列化一個不可序列化的類.要使類可序列化,您必須在其聲明中添加implements Serializable":

The exception is being produced probably because you are trying to serialize a class that is not serializable. To make a class serializable you have to add "implements Serializable" to its declaration:

public class Data implements Serializable {

這篇關于使用 RabbitMQ 發送對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!

【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!

相關文檔推薦

Parsing an ISO 8601 string local date-time as if in UTC(解析 ISO 8601 字符串本地日期時間,就像在 UTC 中一樣)
How to convert Gregorian string to Gregorian Calendar?(如何將公歷字符串轉換為公歷?)
Java: What/where are the maximum and minimum values of a GregorianCalendar?(Java:GregorianCalendar 的最大值和最小值是什么/在哪里?)
Calendar to Date conversion for dates before 15 Oct 1582. Gregorian to Julian calendar switch(1582 年 10 月 15 日之前日期的日歷到日期轉換.公歷到儒略歷切換)
java Calendar setFirstDayOfWeek not working(java日歷setFirstDayOfWeek不起作用)
Java: getting current Day of the Week value(Java:獲取當前星期幾的值)
主站蜘蛛池模板: 蔡司三坐标-影像测量机-3D扫描仪-蔡司显微镜-扫描电镜-工业CT-ZEISS授权代理商三本工业测量 | 【灵硕展览集团】展台展会设计_展览会展台搭建_展览展示设计一站式服务公司 | 合肥礼品公司-合肥礼品定制-商务礼品定制公司-安徽柏榽商贸有限公司 | 冲锋衣滑雪服厂家-冲锋衣定制工厂-滑雪服加工厂-广东睿牛户外(S-GERT) | 利浦顿蒸汽发生器厂家-电蒸汽发生器/燃气蒸汽发生器_湖北利浦顿热能科技有限公司官网 | 分轨 | 上传文件,即刻分离人声和伴奏 | 打孔器,打孔钳厂家【温州新星德牌五金工具】 | 无线联网门锁|校园联网门锁|学校智能门锁|公租房智能门锁|保障房管理系统-KEENZY中科易安 | 过滤器_自清洗过滤器_气体过滤器_苏州华凯过滤技术有限公司 | 恒温振荡混匀器-微孔板振荡器厂家-多管涡旋混匀器厂家-合肥艾本森(www.17world.net) | 超声波_清洗机_超声波清洗机专业生产厂家-深圳市好顺超声设备有限公司 | 深圳市索富通实业有限公司-可燃气体报警器 | 可燃气体探测器 | 气体检测仪 | 本安接线盒-本安电路用接线盒-本安分线盒-矿用电话接线盒-JHH生产厂家-宁波龙亿电子科技有限公司 | 电动不锈钢套筒阀-球面偏置气动钟阀-三通换向阀止回阀-永嘉鸿宇阀门有限公司 | 熔体泵|换网器|熔体齿轮泵|熔体计量泵厂家-郑州巴特熔体泵有限公司 | 振动时效_振动时效仪_超声波冲击设备-济南驰奥机电设备有限公司 北京宣传片拍摄_产品宣传片拍摄_宣传片制作公司-现像传媒 | 智慧食堂_食堂管理系统_食堂订餐_食堂消费系统—客易捷 | 河北凯普威医疗器材有限公司,高档轮椅系列,推车系列,座厕椅系列,协步椅系列,拐扙系列,卫浴系列 | 耐火浇注料价格-高强高铝-刚玉碳化硅耐磨浇注料厂家【直销】 | 沈阳庭院景观设计_私家花园_别墅庭院设计_阳台楼顶花园设计施工公司-【沈阳现代时园艺景观工程有限公司】 | 继电器模组-IO端子台-plc连接线-省配线模组厂家-世麦德 | 智慧钢琴-电钢琴-便携钢琴-数码钢琴-深圳市特伦斯乐器有限公司 | 沧州友城管业有限公司-内外涂塑钢管-大口径螺旋钢管-涂塑螺旋管-保温钢管生产厂家 | 高温链条油|高温润滑脂|轴承润滑脂|机器人保养用油|干膜润滑剂-东莞卓越化学 | PSI渗透压仪,TPS酸度计,美国CHAI PCR仪,渗透压仪厂家_价格,微生物快速检测仪-华泰和合(北京)商贸有限公司 | 防爆鼓风机-全风-宏丰鼓风机-上海梁瑾机电设备有限公司 | 818手游网_提供当下热门APP手游_最新手机游戏下载 | 废水处理-废气处理-工业废水处理-工业废气处理工程-深圳丰绿环保废气处理公司 | 纯化水设备-纯水设备-超纯水设备-[大鹏水处理]纯水设备一站式服务商-东莞市大鹏水处理科技有限公司 | 美国HASKEL增压泵-伊莱科elettrotec流量开关-上海方未机械设备有限公司 | 旋振筛_不锈钢旋振筛_气旋筛_旋振筛厂家—新乡市大汉振动机械有限公司 | 大流量卧式砂磨机_强力分散机_双行星双动力混合机_同心双轴搅拌机-莱州市龙跃化工机械有限公司 | 北京三友信电子科技有限公司-ETC高速自动栏杆机|ETC机柜|激光车辆轮廓测量仪|嵌入式车道控制器 | 精密五金冲压件_深圳五金冲压厂_钣金加工厂_五金模具加工-诚瑞丰科技股份有限公司 | 金属回收_废铜废铁回收_边角料回收_废不锈钢回收_废旧电缆线回收-广东益夫金属回收公司 | 集菌仪_智能集菌仪_全封闭集菌仪_无菌检查集菌仪厂家-那艾 | 招商帮-一站式网络营销服务|搜索营销推广|信息流推广|短视视频营销推广|互联网整合营销|网络推广代运营|招商帮企业招商好帮手 | 电动车头盔厂家_赠品头盔_安全帽批发_山东摩托车头盔—临沂承福头盔 | 科昊仪器超纯水机系统-可成气相液氮罐-美菱超低温冰箱-西安昊兴生物科技有限公司 | 气动隔膜泵-电动隔膜泵-循环热水泵-液下排污/螺杆/管道/化工泵「厂家」浙江绿邦 | 扫地车厂家-山西洗地机-太原电动扫地车「大同朔州吕梁晋中忻州长治晋城洗地机」山西锦力环保科技有限公司 |