我有一个SCS Sink应用程序。我正在尝试使用Spring Kafka将MessageBuilder消息发送到kafka主题
还
我试图在此处有条件地使用Spring Kafka。按照下面的代码,有没有办法使用SCS(即@SendTo等)来做到这一点?理想情况下,我想使用处理器而不是接收器。只是不清楚条件转发。
谢谢您的时间。
demoSink:
@EnableBinding(Sink.class)
public class SampleSink {
@ServiceActivator(inputChannel = Sink.INPUT)
public void processor(Message<?> message) {
@Autowired
private Sender sender;
Message<String> message1 = (Message<String>) MessageBuilder.fromMessage(message)
.setHeader("header1", "header1")
.copyHeadersIfAbsent(message.getHeaders())
.build();
if(someObj.getSomething()==something){
sender.sendt1(message1);
}
else{
sender.sendt2(message)
}
}
Sender.java
@Service
public class Sender {
private static final Logger LOG = LoggerFactory.getLogger(Sender.class);
@Autowired
private KafkaTemplate<String, String> kafkaTemplate;
@Val
ue("${demo.topic}")
private String topic1;
public void sendt1(Message<?> msg){
Message<String> t1 = (Message<String>) MessageBuilder.fromMessage(msg)
.copyHeadersIfAbsent(msg.getHeaders())
.setHeader(KafkaHeaders.TOPIC, topic1)
.build();
LOG.info("sending message topic1");
kafkaTemplate.send(t1);
}
public void sendt2(Message<?> msg){
Message<String> t2 = (Message<String>) MessageBuilder.fromMessage(msg)
.copyHeadersIfAbsent(msg.getHeaders())
.setHeader(KafkaHeaders.TOPIC, topic2)
.build();
LOG.info("sending message topic2");
kafkaTemplate.send(t2);
}
}
config:
@Configuration
public class SenderConfig {
@Value("${spring.cloud.stream.kafka.binder.brokers}")
private String bootstrapServers;
@Bean
public Map<String, Object> producerConfigs() {
Map<String, Object> props = new HashMap<>();
props.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, bootstrapServers);
props.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
props.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
return props;
}
@Bean
public ProducerFactory<String, String> producerFactory() {
return new DefaultKafkaProducerFactory<>(producerConfigs());
}
@Bean
public KafkaTemplate<String, String> kafkaTemplate() {
return new KafkaTemplate<>(producerFactory());
}
}
我遇到以下错误:-
Caused by:
org.apache.kafka.common.errors.SerializationException: Can't convert value of class [B to class org.apache.kafka.common.serialization.StringSerializer
specified in value.serializer
Caused by: java.lang.ClassCastException:
[B cannot be cast to java.lang.String
答案 0 :(得分:1)
spring尝试将ByteArray转换为String Object,如果您仅尝试转发消息,则可以这样做: 更改为:
Message<?> message1 = MessageBuilder.fromMessage(message)
.setHeader("header1", "header1")
.copyHeadersIfAbsent(message.getHeaders())
.build();
,在您的SenderConfig中,将ByteArraySerializer.class用作键和值。