使用kafka消息队列的时候,需要将参数序列化。
消费者:
props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class); props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, ObjectDeSerializer.class);
生产者:
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class); props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, ObjectSerializer.class);
用于在消息队列中传输。
官方默认为我们提供了一些基本类型的序列化,反序列化的工具。
但我们日常开发过程中,会将一些自定义的实体类通过消息队列传输。如:
public class User implements Serializable { private String username; private String sex; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } }
这个时候,我们需要添加消息队列的序列化数据;
/** * 序列化 */ public class ObjectSerializer implements Serializer<Object> { @Override public void configure(Map configs, boolean isKey) { } @Override public byte[] serialize(String topic, Object data) { byte[] b = null; try (ByteArrayOutputStream byteArray = new ByteArrayOutputStream(); ObjectOutputStream outputStream = new ObjectOutputStream(byteArray)) { outputStream.writeObject(data); outputStream.flush(); b = byteArray.toByteArray(); } catch (IOException e) { e.printStackTrace(); } return b; } @Override public void close() { } }
/** * 反序列化 */ public class ObjectDeSerializer implements Deserializer<Object> { @Override public void configure(Map<String, ?> map, boolean b) { } @Override public Object deserialize(String s, byte[] bytes) { Object object = null; try (ByteArrayInputStream in = new ByteArrayInputStream(bytes); ObjectInputStream inputStream = new ObjectInputStream(in)){ object = inputStream.readObject(); } catch (Exception e) { e.printStackTrace(); } return object; } @Override public void close() { } }