[英]How do I declare the topic of a KafkaListener in Scala using a property value
I have a simple Kafka/Scala project that creates a producer.我有一个简单的 Kafka/Scala 项目,它创建了一个生产者。 Now I am trying to create the consumer, however, when I use the following code...现在我正在尝试创建使用者,但是,当我使用以下代码时...
@Service
class KafkaService @Autowired()(producer: KafkaTemplate[String, Array[Byte]]){
@Value("${spring.kafka.topic}") val topic : String = null
def sendMessage(msg: String): Unit = {
System.out.println(s"Writing the message $msg to the topic ${this.topic}")
producer.send(topic, msg.getBytes());
}
@KafkaListener(id="test", topics="${this.topic}")
def consume(record: ConsumerRecord[String, String]): Unit = {
System.out.println(s"Consumed Strinsg Message : ${record.value()}")
}
}
I get the following error...我收到以下错误...
[ERROR] ...\service\KafkaService.scala:26: error: type mismatch;
[ERROR] found : String("${this.topic}")
[ERROR] required: Array[String]
[ERROR] @KafkaListener(id="test", topics="${this.topic}")
What am I missing?我错过了什么?
I also tried the following...我也尝试了以下...
@Configuration
public class CommonConfiguration{
...
@Value("${spring.kafka.topic}")
public String topic;
...
}
@Service
class KafkaService @Autowired()(producer: KafkaTemplate[String, Array[Byte]], config: CommonConfiguration){
def sendMessage(msg: String): Unit = {
val topics : Array[String] = config.getTopics();
println(s"Writing the message $msg ${topics.mkString(" ")}")
producer.send(config.topic, msg.getBytes());
}
@KafkaListener(id="test", topics="#{config.topic.split(',')}")
def consume(record: ConsumerRecord[String, String]): Unit = {
System.out.println(s"Consumed Strinsg Message : ${record.value()}")
}
}
Still no luck but the console log on the producer is getting the right value.仍然没有运气,但生产者的控制台日志获得了正确的值。
The error shows that you need a Array[String] type for topics whereas you have supplied a String type.该错误表明您需要一个 Array[String] 类型的主题,而您提供了一个 String 类型。 You would need to convert the topics string into an array.您需要将主题字符串转换为数组。
The annotations looks very similar to Spring where you can do something like注释看起来与 Spring 非常相似,您可以在其中执行类似操作
@Value("#{'${kafka.topic}'.split(',')}")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.