문제

The difference between a command and an event in bus communication seems a little vague to me. I know that commands should be executed once only, while an event can be handled multiple times, but still I'm not sure when to use a command or an event.

Let's look at an example:

When a new user registers to a web application, we should create him an account and send a confirmation email.

Creating the account - this seems to be the right spot to send a CreateUserCommand to the bus and let a specialized component handle it.

Or maybe this shouldn't even be implemented with an asynchronous bus communication? We want the user to ba able to log in into the application right away. With the bus we have no guarantee when the command will be executed.

Sending email - after the component creates the account I can see 2 possibilities

  1. Send another command to the bus SendConfirmationEmailCommand
  2. Publish an event UserAccountCreatedEvent

And than let the email sender component grab it and to it's job.

On one hand I want the confirmation email to be sent once only (use a command), on the other hand, I believe there can be multiple components interested in newly registered users. A logger or maybe an SMS sender.

How would you implement it?

도움이 되었습니까?

해결책

In principle, a command describes a request that is to be executed, whereas an event describes something that has happened:

  • A command requires some action to be performed by a processor, and this action should be performed only once by this processor.

  • An event is the notification of some action that was already executed or an external happening. Several processors/agents may be interested in knowing about the event. Several of them may further issue commands or action required by this notification in their domain of responsibility.

In your scenario, I understand that:

  • CreateUserCommand is a command
  • UserAccountCreatedEvent is an event that should be issued when CreateUserCommand is successfully completed by the account management service

Now there are two possibilities:

  1. The account management service issues itself a SendConfirmationEmailCommand on the bus, because it expects this command to be executed by a more specialized service.
  2. The account management service does nothing more than sending the event notification on completion, and leaves to another service (e.g. communication service, subscription service, etc...) the decision on whether or not to email/sms/etc... and if necessary to issue a SendConfirmationEmailCommand command to be performed by some gateway.

If you have opted for a service bus approach, it would make sense to use the flexibility that this allows, i.e. to favor option 2.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 softwareengineering.stackexchange
scroll top