【Java】Guava的EventBus实现PubSub(进程间)

以删除一个项目,将级联删除该项目下所有任务为例。

一、事件发布/订阅中心

可以看到事件的发布和订阅都采用的是异步的方式。

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.ThreadPoolExecutor;

/**
 * 进程内的事件发布/订阅中心
 */
public class InternalEventCenter {

    private final static EventBus eventBus;

    static {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(5);
        threadPoolTaskExecutor.setMaxPoolSize(5);
        threadPoolTaskExecutor.setQueueCapacity(10);
        threadPoolTaskExecutor.setThreadNamePrefix("event-bus-task");
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        threadPoolTaskExecutor.initialize();

        eventBus = new AsyncEventBus(threadPoolTaskExecutor);
    }

    public static void publishEvent(Object event) {
        eventBus.post(event);
    }

    public static void register(Object object) {
        eventBus.register(object);
    }

    public static void unregister(Object object) {
        eventBus.unregister(object);
    }


}

二、定义任务删除事件

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.experimental.Accessors;

import java.util.List;

/**
 * 任务删除事件
 */
@Data
@Accessors(chain = true)
@AllArgsConstructor
public class TaskDeletedEvent {

    private String staffId;

    private List<String> taskIds;

}

三、任务删除事件监听者/观察者

@Slf4j
@Component
public class TaskDeleteEventListener {

    @Autowired
    private ITaskService iTaskService;

    @PostConstruct
    public void init() {
        InternalEventCenter.register(this);
    }

    @Subscribe
    public void taskDelete(TaskDeletedEvent event){

        log.info("receive task delete event. operator: {}, taskIds: {}", event.getStaffId(), event.getTaskIds());
    }
}

四、发布事件(在删除项目时。。。)

    public void deleteProject(String staffId, List<String> projectIds){
        
        if(isNotEmpty(projectIds)){

            for (String projectId : projectIds){
                if (logger.isInfoEnabled()) {
                    logger.info("[deleteTask]========projectId: {}", projectId);
                }

                List<String> taskIds = taskService.findByProjectId(projectId);

                if (isNotEmpty(taskIds)) {
                    InternalEventCenter.publishEvent(new TaskDeletedEvent(staffId, taskIds));
                }
            }
        }
    }

五、执行效果

发布了121 篇原创文章 · 获赞 116 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/Mr_EvanChen/article/details/103520486