废话少说,直接上代码。
package com.ctcc.kafka.examples;
import java.util.Properties;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.ctcc.utils.ConfigUtils;
import kafka.javaapi.producer.Producer;
import kafka.producer.KeyedMessage;
import kafka.producer.ProducerConfig;
/**
* producer生产消息的演示
* @author heaven
*/
public class ProducerDemo {
private static final Logger logger = LoggerFactory.getLogger(ContinuousMessageProducer.class);
/**
* 声明message
*/
private String message;
/**
* 声明topic
*/
private String topic;
/**
* 构造方法
* @param topic
* @param message
*/
public ProducerDemo(String topic, String message) {
this.message = message;
this.topic = topic;
}
/**
* 发送消息
*/
public void sendData() {
Producer<String, String> producer = new Producer<String, String>(ProducerConfig());
KeyedMessage<String, String> data = new KeyedMessage<String, String>(this.topic, message);
producer.send(data);
producer.close();
logger.info("producer a message:" + message);
}
public static void main(String[] args) {
if (args == null || args.length != 2) {
logger.info("please input topicname and message!");
//System.exit(0);
args = new String[] { "wanghouda", "heihieheiheiheieh" };
}
new ProducerDemo(args[0], args[1]).sendData();
}
/**
* 设置配置
* @return
*/
public ProducerConfig ProducerConfig() {
Properties props = new Properties();
// 配置broker list
props.put("metadata.broker.list", ConfigUtils.getType("metadata.broker.list"));
props.put("serializer.class", ConfigUtils.getType("serializer.class"));
props.put("request.required.acks", ConfigUtils.getType("request.required.acks"));
return new ProducerConfig(props);
}
}