A simple example of using Guava's eventbus to complete asynchronous events

Guava's Event Bus library is an implementation of the event publishing subscription model, enabling us to decouple our modules and domain boundaries well in the domain-driven design (DDD) by the nature of weak references to events.The following are examples of common asynchronous events:

1. Declare asynchronous processing classes inside configure

    public AsyncEventBus asyncEventBus(){
        return new AsyncEventBus(Executors.newFixedThreadPool(100));

Thread pool of 100 threads

2. Define an entity class to load event content

public class SmsEvent {
    private Long smsId;
    private String telphone;
    private String content;

    public SmsEvent(Long smsId, String telphone, String content) {
        this.smsId = smsId;
        this.telphone = telphone;
        this.content = content;

    public String getTelphone() {
        return telphone;

    public void setTelphone(String telphone) {
        this.telphone = telphone;

    public String getContent() {
        return content;

    public void setContent(String content) {
        this.content = content;

    public Long getSmsId() {
        return smsId;

    public void setSmsId(Long smsId) {
        this.smsId = smsId;
public class NoticeSmsEvent extends SmsEvent {

    public NoticeSmsEvent(Long smsId, String telphone, String content) {
        super(smsId, telphone, content);

3. Create event monitoring
Since it's publish-subscribe mode, we'll first publish a listener.

public class NoticeSmsListener {
    private AsyncEventBus asyncEventBus;

    //Register this listener
    public void register() {

    public void sendSms(NoticeSmsEvent smsEvent) {
        //Write here the logic that needs to be executed asynchronously
        boolean result=SmsUtil.send(smsEvent.getTelphone(),smsEvent.getContent(),"SendNoticeSms",propertyMapper);

4. Call Asynchronous Events

Subscribe to the publication where you need to perform the third-step logic and push the information.

NoticeSmsEvent noticeSmsEvent = new NoticeSmsEvent(id, mobilePhone, smsContent);

Posted on Tue, 05 May 2020 20:04:08 -0700 by nemxu