springboot 之 java事件的使用(guava-19.0.jar)

1、首先创建一个事件  @Data为插件lombok,自动默认为类加上get/set方法。Event

package com.***.app.event;

import com.***.eventbus.Event;
import lombok.Data;

@Data
public class UserLogEvent implements Event {

    private Long userId;

}

2、添加事件监听器,里面做业务逻辑处理    @Subscribe注解是guava的内容,可以更方便的实现Observer模式(观察者模式), 如果要订阅消息, 就不用再继承指定的接口, 只需要在指定的方法上加上@Subscribe注解即可

package com.***.app.event.listener;

import com.alibaba.fastjson.JSON;
import com.***.app.event.UserLogEvent;
import com.***.eventbus.EventListener;
import com.google.common.eventbus.Subscribe;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class UserLogEventListener implements EventListener {

    @Subscribe
    public void saveUserLog(UserLogEvent logEvent){
        log.info("user log .. {}", JSON.toJSONString(logEvent));
    }
}

3、触发事件  

 UserLogEvent event = new UserLogEvent();
 event.setUserId(userId);
 EventBusContext.fireAsyncEvent(event);

触发事件被封装在下面  EventBusContext 类

package com.***.eventbus;

import com.google.common.eventbus.AsyncEventBus;
import com.google.common.eventbus.EventBus;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ThreadPoolExecutor.AbortPolicy;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class EventBusContext {
    private static final Logger log = LoggerFactory.getLogger(EventBusContext.class);
    private static final EventBus EVENT_BUS = new EventBus();
    private static ExecutorService asyncEventBusPool;
    private static final AsyncEventBus ASYNC_EVENT_BUS;

    public EventBusContext() {
    }

    public static void register(EventListener eventListener) {
        EVENT_BUS.register(eventListener);
        ASYNC_EVENT_BUS.register(eventListener);
    }

    public static void fireEvent(Event event) {
        EVENT_BUS.post(event);
    }

    public static void fireAsyncEvent(Event event) {
        ASYNC_EVENT_BUS.post(event);
    }

    static {
        asyncEventBusPool = new ThreadPoolExecutor(1, 3, 0L, TimeUnit.MILLISECONDS, new LinkedBlockingQueue(1024), (new ThreadFactoryBuilder()).setNameFormat("asyncEventBus-pool-%d").build(), new AbortPolicy());
        ASYNC_EVENT_BUS = new AsyncEventBus(asyncEventBusPool);
    }
}

 

你可能感兴趣的:(springboot 之 java事件的使用(guava-19.0.jar))