1.监听
@EventListenerpublic void logoutEvent(LoginOutEvent event) {// 用户下线时,刷新一下缓存this.flushPlayer(event.getPlayerId());logger.info("用户下线,刷新缓存,playerId:{},threadId:{}", event.getPlayerId(), Thread.currentThread().getId());}
定义 // 唯一不太方便的是: 得传入source参数!!!
public class LoginOutEvent extends ApplicationEvent {private String playerId;public LoginOutEvent(Object source, String playerId) {super(source);this.playerId = playerId;}public String getPlayerId() {return playerId;}
}
2)发射事件
private void bindChannel(ChannelHandlerContext ctx, String playerId) {GamePlayerCacheModel gamePlayerCacheModel = new GamePlayerCacheModel(ctx, playerId);gameChannelService.bindChannel(gamePlayerCacheModel);ctx.channel().closeFuture().addListener(future -> {// 当用于离线时,发送离事事件LoginOutEvent loginOutEvent = new LoginOutEvent(this, playerId);context.publishEvent(loginOutEvent);});}