Skip to content

kafka: set message key dynamically #174

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
aarashtaheri opened this issue Aug 11, 2016 · 2 comments
Open

kafka: set message key dynamically #174

aarashtaheri opened this issue Aug 11, 2016 · 2 comments

Comments

@aarashtaheri
Copy link

aarashtaheri commented Aug 11, 2016

Regarding the kafka sample code, currently you can only have one message key, which you set it in application.properties. After running the application there is no way to change it.

Is there a way to set the message key dynamically, before sending the message?

@aarashtaheri aarashtaheri changed the title set message key dynamically kafka, set message key dynamically Aug 11, 2016
@aarashtaheri aarashtaheri changed the title kafka, set message key dynamically kafka: set message key dynamically Aug 11, 2016
@garyrussell
Copy link
Contributor

garyrussell commented Aug 11, 2016

There are several options.

1 Delete this line:

handler.setMessageKeyExpression(new LiteralExpression(this.messageKey));

And change the send to ...

toKafka.send(new GenericMessage<>("foo" + i));

to

toKafka.send(MessageBuilder.withPayload("foo" + i)
    .setHeader(KafkaHeades.MESSAGE_KEY)
    .build());

If there is no key expression, we look for that header (same thing for the topic, partition).

2 Change this

handler.setMessageKeyExpression(new LiteralExpression(this.messageKey));

to

handler.setMessageKeyExpression(new SpelExpressionParser.parseExpression("<some expression>"));

Where <some expression> calculates the key - such as payload.key or headers['myHeader'].

@garyrussell
Copy link
Contributor

See the README.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants