import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.Random;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import com.alibaba.fastjson.JSONObject;
public class OrderGenerator {
private static final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
public static void main(String[] args) throws InterruptedException {
Random random = new Random();
int orderId = 1;
// Kafka配置参数
Properties props = new Properties();
props.put("bootstrap.servers", "<kafka_host>:<kafka_port>");
props.put("acks", "all");
props.put("retries", 0);
props.put("batch.size", 16384);
props.put("linger.ms", 1);
props.put("buffer.memory", 33554432);
props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer");
props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer");
// 创建Kafka生产者实例
KafkaProducer<String, String> producer = new KafkaProducer<>(props);
while (true) {
int amount = random.nextInt(1000) + 1;
String orderTime = dateFormat.format(new Date());
JSONObject orderJson = new JSONObject();
orderJson.put("orderId", orderId);
orderJson.put("amount", amount);
orderJson.put("orderTime", orderTime);
JSONObject userJson = new JSONObject();
userJson.put("userId", random.nextInt(100) + 1);
userJson.put("userName", "User " + (random.nextInt(10) + 1));
orderJson.put("user", userJson);
JSONObject productJson = new JSONObject();
productJson.put("productId", random.nextInt(1000) + 1);
productJson.put("productName", "Product " + (random.nextInt(10) + 1));
orderJson.put("product", productJson);
String orderInfo = orderJson.toJSONString();
// 发送订单信息到Kafka
ProducerRecord<String, String> record = new ProducerRecord<>("orders", orderInfo);
producer.send(record);
System.out.println("Sent order: " + orderInfo);
orderId++;
Thread.sleep(5000);
}
}
}