Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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();
            }
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
1.0k views
Welcome To Ask or Share your Answers For Others

1 Answer

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");

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...