现在我正在尝试从mqtt消息连接到kafka(实际上是kafka中的spark流)
我使用了这个连接符https://github.com/evokly/kafka-connect-mqtt
和Spark-2.1.0,Kafka - 0.10.1.1
像这样的Saprk流输出
({"schema":{"type":"string","optional":false},"payload":"mqtt"},{"schema":{"type":"bytes","optional":false},"payload":"MTIzMTIz"})
和生产者代码
object mqttProducer {
def main(args: Array[String]) {
val brokerUrl = "tcp://ip"
val topic = "mqtt"
val msg = "123123"
var client: MqttClient = null
// Creating new persistence for mqtt client
val persistence = new MqttDefaultFilePersistence("/tmp")
try {
// mqtt client with specific url and client id
client = new MqttClient(brokerUrl, MqttClient.generateClientId, persistence)
client.connect()
val msgTopic = client.getTopic(topic)
val message = new MqttMessage(msg.getBytes("utf-8"))
while (true) {
msgTopic.publish(message)
println("Publishing Data, Topic : %s, Message : %s".format(msgTopic.getName, message))
Thread.sleep(1000)
}
}
catch {
case e: MqttException => println("Exception Caught: " + e)
}
finally {
client.disconnect()
}
和spark-streaming kafka消费者代码
package hb.test1
import org.apache.kafka.common.serialization.StringDeserializer
import org.apache.spark.SparkConf
import org.apache.spark.streaming.Seconds
import org.apache.spark.streaming.StreamingContext
import org.apache.spark.streaming.kafka010.ConsumerStrategies.Subscribe
import org.apache.spark.streaming.kafka010.KafkaUtils
import org.apache.spark.streaming.kafka010.LocationStrategies.PreferConsistent
object test2 {
def main(args: Array[String]): Unit = {
val sparkConf = new SparkConf().setAppName("app")
val ssc = new StreamingContext(sparkConf, Seconds(1))
val kafkaParams = Map[String, Object](
"bootstrap.servers" ->
"servers ip",
"key.deserializer" -> classOf[StringDeserializer],
"value.deserializer" -> classOf[StringDeserializer],
"group.id" -> "use_a_separate_group_id_for_each_stream",
"auto.offset.reset" -> "latest",
"enable.auto.commit" -> (false: java.lang.Boolean)
)
val topics = Array("mqtt-kafka")
val stream = KafkaUtils.createDirectStream[String, String](
ssc,
PreferConsistent,
Subscribe[String, String](topics, kafkaParams)
)
val testStream = stream.map(x => (x.key, x.value))
testStream.print()
ssc.start()
ssc.awaitTermination()
}
}
我怎么能得到字符串不是字节? 请帮助人
答案 0 :(得分:2)
有效载荷“MTIzMTIz”是字符串“123123”,只是base64编码。如果您只想获取MQTT有效负载并将其发送到没有base64编码的Kafka,则应使用ByteArrayConverter。在我对相同mqtt连接器的配置中,我设置了值转换器,如下所示:
“value.converter”:“io.confluent.connect.replicator.util.ByteArrayConverter”
上面的ByteArrayConverter附带了Confluent Enterprise发行版,但还有其他开源Kafka Connect ByteArrayConverters,例如qubole / streamx kafka-connect-s3连接器附带的那个。
KIP-128将标准ByteArrayConverter添加到Kafka Connect框架
更新:Kafka 0.11现已发布,附带ByteArrayConverter。配置"value.converter": "org.apache.kafka.connect.converters.ByteArrayConverter"
,您应该获得没有Base64编码的原始mqtt有效负载。