Kafka produce to send image

2020-02-07 09:51发布

I have the following Kafka producer code. I want to know if I can send image file instead of JSON file? Is there any code reference sending an image file through Kafka producer?

    try {           
                URL url = getClass().getResource("test.json");
                File file = new File(url.getPath());
                Properties props = new Properties();            
                props.put("bootstrap.servers", "yupsectory.selet.com:9092");
                props.put("client.id", CLIENT_ID);
                props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
                props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
                String jsonData = readFile(file.getAbsolutePath());
                JSONObject jobj = new JSONObject(jsonData);    
                System.out.println("jarr: " + jobj.getJSONObject("data").toString());    

                Producer<String, String> producer = new KafkaProducer <>(props);      
                //Use this util to pull the context that needs to be propagated from the HttpServletRequest
                Map<String, String> headermap = YupsectoryContextUtil.buildContextMap(request);
                //Sending a message
                ProducerRecord<String, String> record = new ProducerRecord<String, String>(topic, jobj.getJSONObject("data").toString());
                producer.send(record, headermap);           
                producer.close();                 
            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

2条回答
爱情/是我丢掉的垃圾
2楼-- · 2020-02-07 10:21

You can send an image by following these simple steps:-

1) convert your image into bytes array ( by search for "how to get bytes of an image file )

2) change this line from :-

props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");

to:-

props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");

3) give your bytesarray of your image file

and, you are good to go.

查看更多
萌系小妹纸
3楼-- · 2020-02-07 10:30

Image can be sent as byte array in message value. so your code will be changed as given.

props.put("value.serializer", "org.apache.kafka.common.serialization.ByteArraySerializer");
查看更多
登录 后发表回答