KTable as input from topic with null keys - spring-boot

I'm very new to Kafka Streams and encountered a problem.
I have two tables - one is for long-term data (descriptions) and the other is for live data (live). They have a common id.
And the idea is to store data from descriptions (presumably in KTable, keep latest description for each id) and when new messages appear in live - join with data from descriptions on corresponding id and send it further.
For simplicity let's just make all types String.
So the basic idea was like in every tutorial I've seen:
interface Processor {
#Input("live")
KStream<String, String> input();
#Input("descriptions")
KTable<String, String> input();
#Output("output")
KStream<String, String> output();
}
And then:
#StreamListener
#SendTo("output")
public KStream<String, String> process(
#Input("live") KStream<String, String> live,
#Input("descriptions") KTable<String, String> descriptions) {
// ...
}
The problem is that descriptions topic is not KTable-suitable (null keys, just messages).
So I can't use it as an input and I can't create any new intermediate topics for storing a valid stream out of this table (basically read-only).
I was searching for some sort of in-memory Binding destination, but to no avail.
The way I thought it could be possible is something like creating an intermediate output that just stores KTable in-memory or something and then using this intermediate as an input in live processing. Like:
#StreamListener("descriptions")
#SendTo("intermediate")
public KTable<String, String> process(#Input("descriptions") KStream<String, String> descriptions) {
// ...
}
Hope it's possible with this Binding semantics.

I think you can try to introduce an intermediate topic for storing the key/value by introducing an initial processor. Then use that stream as a table for the input in your regular processor. Here are some templates. I am using the new functional model in Spring Cloud Stream to write these processors.
#Bean
public Function<KStream<String, String>, KStream<String, String>> processDescriptions() {
return descriptions ->
descriptions.map((key, value) -> {
Pojo p = parseIntoPojo(value);
return new KeyValue<>(p.getId(), value);
})
.groupByKey()
.reduce((v1, v2) -> v2)
.toStream();
}
#Bean
public BiFunction<KStream<String, String>, KTable<String, String>, KStream<String, String>> realStream() {
return (live, description) -> {
}
}
The first processor receives the description as KStream and then enrich that with the key and then output as KStream. Now that this topic has both key and value, we can use this as a KTable in our next processor. The next processor is a java.util.function.BiFunction which receives two inputs and generate an output. The inputs are KStream and KTable respectively and the output is a KStream.
You can set destinations on them as below:
spring.cloud.stream.function.definition=prorcessDescriptions;realStream
spring.cloud.stream.bindings.processDescriptions-in-0.destinaion=description-topic
spring.cloud.stream.bindings.processDescriptions-out-0.destinaion=description-table-topic
spring.cloud.stream.bindings.realStream-in-0.destinaion=live-topic
spring.cloud.stream.bindings.realStream-in-1.destinaion=description-table-topic
spring.cloud.stream.bindings.realStream-out-0.destinaion=output
You can achieve the same results by using the StreamListener approach as well.
The downside of this approach is that you need to maintain an extra intermediate topic in Kafka, but if you really want it as a KTable and the underlying information is non-keyed, I don't think there are too many options here.
If you don't need the descriptions as a top-level KTable, you might be able to store this somehow in a state store and later query that store all within a single processor. I haven't tried that out, so you need to play around with that idea. Basically, you get two streams, live and descriptions
(live, descriptions) -> Reduce key/value for descriptions and keep that in a state store.
Then, do the processing on live by joining with what is in the state store.
Kafka Streams allows various ways to accomplish things like that. Check their reference docs for more info.
Hope this helps.

Related

How to consume messages from Kafka by type

I'm new to kafka and have some questions about it. I have configured a kafka consumer to consume messages from topic and I'm having different types of events coming to the topic.
f.e.
class Event {
String type;
Object event;
}
I want to configure different kafka listeners to consume different types of events.
I see two ways of doing it like consuming event in String(json) format and the converting to event object and switching between types and doing business logic, or configuring different kafka listener factory
public ConcurrentKafkaListenerContainerFactory<String, String> businessEventStreamListenerContainerFactory() {
ConcurrentKafkaListenerContainerFactory<String, String> factory =
new ConcurrentKafkaListenerContainerFactory<>();
factory.setConsumerFactory(consumerFactory());
factory.setRecordFilterStrategy(consumerRecord -> !consumerRecord.value().contains("typeOfObjectIWantToConsume"));
return factory;
}
So the first approach is not SOLID and for the second one I need to create a lot of factory classes. Is there any way to do this more elegantly?
Well, this kind of business requirements was really a reason why we have introduced a #KafkaHandler.
See more info in docs: https://docs.spring.io/spring-kafka/docs/current/reference/html/#class-level-kafkalistener.

#InboundChannelAdapter in Spring-integration is not running continously?

i am working in spring cloud data flow,there i am having a scenario like reading from the database and send the data to the kafka topic using the #InboundChannelAdapter
Below is the strategy i followed.
->Created common list to store the objects if the list was empty
->if the list have the data i won't poll
->i am sending the values to kafka one by one by using index and after that i will remove the index
if i keep the #Bean it is inserting only the first object in the list to kafka topic.
{"id":101443442,"name":"Mobile1","price":8000}
if i remove the #Bean then it will insert all empty data into kafka.
{}
public static List<Product> products;
#Bean
public void initList() {
products = new ArrayList<>();
}
#Bean
#InboundChannelAdapter(channel = TbeSource.PR1)
public MessageSource<Product> addProducts() {
if (products.size() == 0) {
products.add(new Product(101443442, "Mobile1", 8000));
products.add(new Product(102235434, "book111", 6000));
}
MessageBuilder<Product> message = MessageBuilder.withPayload(products.get(0));
products.remove(0);
return message::build;
}
what am i doing wrong?
i need to send the data frequently by reading from db ?
Really not clear what you are asking.
If you talk about JDBC then you may consider to use a JDBC Source from tout-of-the-box applications for Data Flow.
If you are doing logic yourself to take data from data base, you may consider to use a JdbcPollingChannelAdapter from Spring Integration for the same #InboundChannelAdapter reason.
The rest of your logic with that list is not clear. It is strange to see a #Bean on a void method. If you need to initialize that products and get access from the MessageSource implementation, you just need to do private List<Product> products = new ArrayList<>();. Having property as public is really a bad practice.

Pass data from one writer to another writer after reading from DB

I have to create a batch job where I need to fetch data from 1 DB and after processing dump that data to another DB where auto generated ID would be assigned to persisted data. I need to send that data along with generated ID to solace queue.
Reader(DB1) --data1--> Processor --data2--> Writer (DB2) --data3--> Writer (Solace Publisher)
I am using spring boot-2.2.5.RELEASE and spring-boot-starter-batch.
I have created a job having 1 step that read data from DB1 and write data to DB2 via RepositoryItemReader and RepositoryItemWriter respectively. This is working fine.
Now next task is to send persisted data having generated ID to solace stream (using spring-cloud-starter-stream-solace).
I have below questions. Please assist as I am totally new to spring batch
How can I get the complete record after it's saved to DB2 based on some parameter? Do I have to write my own RepositoryItemWriter having StepExecution Context or can I somehow use the existing RepositoryItemWriter.
Once I got the record I need to use solace stream and there I have publish method which expects argument(record) to be published. I think again I need to write my own Item Writer and either I could use the record passed from above repositoryItemWriter by StepExecutionContext or should I query into DB2 directly from here based on some parameter ?
Either of the above case I need to use stepexecution context but can I use available RepositoryItemWriter or do I have to write my own?
Is there any other concept which is handy in this handy instead of using above approaches?
Passing data to future steps is a common pattern in Spring Batch. According to the documentation https://docs.spring.io/spring-batch/docs/current/reference/html/common-patterns.html#passingDataToFutureSteps you can use stepExecution to store and retrieve your generated IDs. In your case the writers are also listeners which has before step methods annotated with #BeforeStep. For example:
public class DB2ItemWriter implements ItemWriter<Object> {
private StepExecution stepExecution;
public void write(List<? extends Object> items) throws Exception {
// ...
ExecutionContext stepContext = this.stepExecution.getExecutionContext();
stepContext.put("generatedIds", ids);
}
#BeforeStep
public void saveStepExecution(StepExecution stepExecution) {
this.stepExecution = stepExecution;
}
}
and then you retrieve the ids in the next writer
public class SolacePublisherItemWriter implements ItemWriter<Object> {
public void write(List<? extends Object> items) throws Exception {
// ...
}
#BeforeStep
public void retrieveGeneratedIds(StepExecution stepExecution) {
ExecutionContext stepExecutionContext = stepExecution.getExecutionContext();
this.generatedIds = stepExecutionContext.get("generatedIds");
}
}
I have created a job having 1 step that read data from DB1 and write data to DB2 via RepositoryItemReader and RepositoryItemWriter respectively. This is working fine.
I would add a second step that reads data from the table (in which records have been persisted by step 1 and have their IDs generated) and push it to solace using a custom writer.

What is the benefit of converting a Ktable into a Streaming before materializing it into a Topic?

I often see this pattern in book and blogs that I read all around, but can't quite understand how useful it is:
Stream.GrouBy.Agg.toStream.to(Topic)
What is the benefit of converting the KTable into a stream before materializing its result into a topic ?
Can't we just write Stream.GrouBy.Agg.to(Topic)
What would be the difference in term of implications between the 2 ?
EDIT1
The javadoc says that to on a Ktable has been deprecated and that converting to a stream first and then using to was the recommended approach.
I wonder why ?
According to Javadoc , KTable .to() method implementation is as given below where it calls .toStream() internally:
#SuppressWarnings("deprecation")
#Override
public void to(final String topic) {
to(null, null, null, topic);
}
#SuppressWarnings("deprecation")
#Override
public void to(final Serde<K> keySerde,
final Serde<V> valSerde,
final StreamPartitioner<? super K, ? super V> partitioner,
final String topic) {
this.toStream().to(keySerde, valSerde, partitioner, topic);
}
There is no difference technically in both method, above one is just converting KTable into KStream internally by hiding the .toStream() method call, while in Stream.GrouBy.Agg.toStream.to(Topic) , it calls .toStream() explicitly.

Field Grouping for a Kafka Spout

Can field grouping be done on tuples emitted by a kafka spout? If yes, then how does Storm gets to know the fields in a Kafka record?
Field grouping (and grouping in general) in Storm is for bolts, not for spouts. This is done via InputDeclarer class.
When you call setBolt() on TopologyBuilder, InputDeclarer is returned.
Kafka Spout declared its output fields like any other component. My explanation is based on current implementation of KafkaSpout.
In KafkaSpout.java class we see declareOutputFields method that call getOutputFields() method of KafkaConfig Scheme.
#Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(_spoutConfig.scheme.getOutputFields());
}
By default, KafkaConfig uses RawMultiScheme that implements this method in this way.
#Override
public Fields getOutputFields() {
return new Fields("bytes");
}
So what does it mean?, if you declared bolt which reads tuples from KafkaSpout with fieldGrouping you know that every tuple that contains equals field "bytes" is going to be executed by the same task. If you want to emit any field, you should implement new scheme for your needs.
TL:DR
The default implementation of KafkaSpout declares following output fields in declareOutputFields:
new Fields("topic", "partition", "offset", "key", "value");
So in building topology code directly do:
topologyBuilder.setSpout(spoutName, mySpout, parallelismHintSpout);
topologyBuilder.setBolt(boltName, myBolt, parallelismHintBolt).fieldsGrouping(spoutName, new Fields("key"));
Details: A little looking into code tells that:
In Kafka Spout, declareOutputFields is implemented in following way:
#Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
RecordTranslator<K, V> translator = kafkaSpoutConfig.getTranslator();
for (String stream : translator.streams()) {
declarer.declareStream(stream, translator.getFieldsFor(stream));
}
}
It gets fields from RecordTranslator interface and its instance is fetched from kafkaSpoutConfig i.e. KafkaSpoutConfig<K, V>. KafkaSpoutConfig<K, V> extends from CommonKafkaSpoutConfig (this is slightly different in 1.1.1 version though). The builder of this returns DefaultRecordTranslator. If you check the Fields in this class implementation, you will find:
public static final Fields FIELDS = new Fields("topic", "partition", "offset", "key", "value");
So we can use Fields("key") directly in fields grouping in topology code:
topologyBuilder.setBolt(boltName, myBolt, parallelismHintBolt).fieldsGrouping(spoutName, new Fields("key"));

Resources