模拟一些数据,发送到kafka

import java.io.PrintWriter
import java.text.SimpleDateFormat
import java.util.{Date, Properties}

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}

/**
  * Created by xiang on 2020/5/11.
  */
object SparkTrafficMockData {

  def main(args: Array[String]): Unit = {

    /*val write = new PrintWriter("L:\\input\\testyuekao1\\data.txt")*/
    var i = 0
    val props: Properties = new Properties
    props.put("bootstrap.servers", "192.168.137.134:9092,192.168.137.135:9092,192.168.137.136:9092")
    props.put("acks", "all")
    props.put("key.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    props.put("value.serializer", "org.apache.kafka.common.serialization.StringSerializer")
    val producer = new KafkaProducer[String, String](props)


    while(i<100){
      //date 日期
      var time = new  SimpleDateFormat("yyyy-MM-dd").format( new java.util.Date())
      //卡口号
      var kakou  =   new java.util.Random().nextInt(20)
      var kakouS = kakou.formatted("%04d")
      //摄像头号
      var shexiangtou = new java.util.Random().nextInt(10000)
      var shexiangtouS = shexiangtou.formatted("%05d")
      //车牌号
      var paizhaoArea = Array("京","沪","粤","深","湘")
      var paizhao =  paizhaoArea( new java.util.Random().nextInt( paizhaoArea.length))
      var zimu  = ( new java.util.Random().nextInt(26) + 65).asInstanceOf[Char]
      var numberS = new java.util.Random().nextInt(99999)
      var numberZmu = numberS.formatted("%05d")
      var paizhaoHeji = paizhao+zimu+ numberZmu
      //拍照时间
      var timeS = new  SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format( new Date())
      //车速
      var speed = new java.util.Random().nextInt(200)
      //道路编号
      var road = new java.util.Random().nextInt(50)
      var roadS = road.formatted("%02d")
      //区域编号
      var area = new java.util.Random().nextInt(10)
      var areaS = area.formatted("%02d")

      //将以上数据通过\t拼接成长字符串,
      var suijishu =  time + "\t" + kakouS + "\t" + shexiangtouS + "\t" + paizhaoHeji + "\t" + timeS +"\t"+ speed + "\t"+ roadS + "\t" + areaS
      println( suijishu)
      //将拼接好的长字符串通过kafka的生产者API将数发送到kafka
      producer.send(new ProducerRecord[String, String]("topic_car", suijishu))

      Thread.sleep(500)

      //同时将以上数据保存到本地文件 data.txt
      /*write.write(suijishu)
      write.write("\n")*/
      i=i+1
    }
/*
    write.close()
*/
  }

}

你可能感兴趣的:(kafka)