Skip to content

Instantly share code, notes, and snippets.

@ndemengel
Last active April 30, 2017 18:14
Show Gist options
  • Save ndemengel/942c21b301ea7a35553fd21197250ca0 to your computer and use it in GitHub Desktop.
Save ndemengel/942c21b301ea7a35553fd21197250ca0 to your computer and use it in GitHub Desktop.
Spring/Rabbit boilerplate
import lombok.Data;
@Data
public final class EmailUpdated {
private String accountId;
private String oldEmail;
private String newEmail;
public EmailUpdated(String accountId, String oldEmail, String newEmail) {
this.accountId = accountId;
this.oldEmail = oldEmail;
this.newEmail = newEmail;
}
// for Jackson
private EmailUpdated() {}
}
@RequestMapping(path = "/some/path", method = POST)
public ModelAndView updateEmail(@Valid NewEmailForm form) {
// ...
// call some account-handling service which ultimately does the following:
eventsService.fire(new EmailUpdated(accountId, oldEmail, newEmail));
// ...
}
import org.springframework.amqp.rabbit.annotation.RabbitListener;
@Service
public class MailChimpSynchronization {
@RabbitListener(queues = RabbitConfig.MAILCHIMP_EMAIL_UPDATED_QUEUE)
public void emailUpdated(EmailUpdated event) {
updateMailChimpMember(event.getOldEmail(), event.getNewEmail());
}
}
@Service
public class EventsService {
@Inject
private RabbitTemplate rabbitTemplate;
public void fire(EmailUpdated event) {
String noRoutingKey = "";
rabbitTemplate.convertAndSend(RabbitConfig.EMAIL_UPDATED_EXCHANGE, noRoutingKey, event);
}
// ... lots of other fire(Xxx) methods
}
import org.springframework.amqp.core.*;
import org.springframework.context.annotation.*;
@Configuration
public class RabbitConfig {
public static final String EMAIL_UPDATED_EXCHANGE = "email.updated.exchange";
// ... lots of other exchange constants...
public static final String MAILCHIMP_EMAIL_UPDATED_QUEUE = "email.updated.mailchimp.queue";
// ... lots of other queue constants...
@Bean
public FanoutExchange emailUpdatedExchange() {
return new FanoutExchange(EMAIL_UPDATED_EXCHANGE, true, false);
}
@Bean
public Binding mailchimpEmailUpdatedBinding() {
return BindingBuilder.bind(mailchimpEmailUpdatedQueue()).to(emailUpdatedExchange());
}
@Bean
public Queue mailchimpEmailUpdatedQueue() {
return queueWithDelayedRetry(MAILCHIMP_EMAIL_UPDATED_QUEUE);
}
@Bean
public Binding bindMailchimpEmailUpdatedQueueToDeadLetter() {
return BindingBuilder.bind(mailchimpEmailUpdatedQueue())
.to(backFromTheDeadExchange())
.with(mailchimpEmailUpdatedQueue().getName());
}
// ... lots of other exchanges, queues, and bindings...
// Plus, the following beans are defined only once:
// deadLetterExchange, retryQueue, deadLetterListener, etc.
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment