Scala 向kafka topic写信息

IDEA 右侧sbt工具栏,有刷新依赖按钮
查看sbt版本: 1. sbt进入交互 2. sbtVersion
查看scala版本: 1. scala进入交互 2. util.Properties.versionString

sbt-assembly

build.sbt

name := "KafkaTodd"

version := "0.1"

// 如果这个版本跟实际的版本不一致,IDEA可能会 can not resolve symbol
scalaVersion := "2.11.0"

libraryDependencies ++= Seq(
  "org.apache.kafka" % "kafka-clients" % "2.0.0",
  "org.apache.kafka" % "kafka_2.11" % "2.0.0"
)

libraryDependencies += "ch.qos.logback" % "logback-classic" % "1.2.3"

assemblyMergeStrategy in assembly := {
  case PathList("META-INF", xs @ _*) => MergeStrategy.discard
  case x                             => MergeStrategy.first
}

code

package 

import org.apache.kafka.clients.producer.{KafkaProducer, ProducerRecord}
import java.util.{Date, Properties}
// import java.time

object KafkaTodd{
  def main(args: Array[String]):Unit={
    println("start------")
    val topic="test_topic"
    val brokers="127.0.0.1:9092"
    val now=new Date()

    val props=new Properties()
    props.put("bootstrap.servers", brokers)
    props.put("client.id", "0")
    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)
    val rcd=new ProducerRecord[String, String](topic, now.toString())
    producer.send(rcd)
    // 这里必须要调结束,否则kafka那边收不到消息 
    producer.close()

  }
}

你可能感兴趣的:(Scala 向kafka topic写信息)