KafkaChatMessageHistory
to store and retrieve chat messages from a Kafka cluster.
A running Kafka cluster is required to run the demo. You can follow this instruction to create a Kafka cluster locally.
KafkaChatMessageHistory
:
ttl_ms
: Time to live in milliseconds for the chat messages.partition
: Number of partition of the topic to store the chat messages.replication_factor
: Replication factor of the topic to store the chat messages.
KafkaChatMessageHistory
internally uses Kafka consumer to read chat messages, and it has the ability to mark the consumed position persistently. It has following methods to retrieve chat messages:
messages
: continue consuming chat messages from last one.messages_from_beginning
: reset the consumer to the beginning of the history and consume messages. Optional parameters:max_message_count
: maximum number of messages to read.max_time_sec
: maximum time in seconds to read messages.
messages_from_latest
: reset the consumer to the end of the chat history and try consuming messages. Optional parameters same as above.messages_from_last_consumed
: return messages continuing from the last consumed message, similar tomessages
, but with optional parameters.
max_message_count
and max_time_sec
are used to avoid blocking indefinitely when retrieving messages.
As a result, messages
and other methods to retrieve messages may not return all messages in the chat history. You will need to specify max_message_count
and max_time_sec
to retrieve all chat history in a single batch.
Add messages and retrieve.
messages
again returns an empty list because the consumer is at the end of the chat history.