We know that Keywordmessage is the object that is sent and stored by Kafka. So we just need to simulate this to send a custom message.
For example, I need to record the user's id,user,age,address and access IP and access date as a message. I'll customize a message format (id-user-age-address-ip-date).
I immediately thought of myself defining a javabean. Write a userinfo class pseudo-code.
Class UserInfo () {
Id
User
Age
Address
ip
Date
ToString () {
return This.getid () + "-" +this.getuser () + "-" + "..." +this.getdate ();
}
}
Do you think that would be all right? Of course not!
Also in accordance with the Kafka message type encapsulation, here we only need to implement the Encoder class: Continue to look at the code is good;
public class KeywordMessage implements kafka.serializer.Encoder<UserInfo>{ public static final Logger LOG=LoggerFactory.getLogger(UserInfo.class); @Override public Message toMessage(Keyword words) { LOG.info("start in encoding..."); return new Message(words.toString().getBytes()); }}so Keywordmessage is an object that can be sent and stored by Kafka. Let's take a look at the push of the producer,producer data to the broker, so the initiator is the business system, and the code below can send the data directly. /**配置producer必要的参数*/Properties props = new Properties();必要的一些配置省略。。。/**选择用哪个类来进行序列化,就是我们自定义的消息类*/props.put("serializer.class", "org.kafka.message.UserInfo");ProducerConfig config=new ProducerConfig(props);/**构造测试数据*/ UserInfo userInfo = new UserInfo (); .setId( 1 userInfo ); userInfo.setUser("xiaoming"); ...List<UserInfo> msg=new ArrayList<UserInfo>();msg.add(userInfo);/**构造数据发送对象*/Producer<String, UserInfo> producer=new Producer<String, UserInfo>(config); ProducerData<String,UserInfo> data=new ProducerData<String, UserInfo>("test", msg);producer.send(data);The above is the custom encapsulated message content.
Kafka producer-side encapsulation of custom messages