All Downloads are FREE. Search and download functionalities are using the official Maven repository.

xin.alum.aim.groups.SessionGroups Maven / Gradle / Ivy

There is a newer version: 1.9.6
Show newest version
package xin.alum.aim.groups;

import io.netty.channel.Channel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import xin.alum.aim.AIM;
import xin.alum.aim.model.Transportable;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 群组Sesions 管理通道
 *
 * @auther alum(alum @ live.cn)
 * @date 2021/8/3 14:29
 */
@Component
public class SessionGroups extends ConcurrentHashMap {

    /**
     * 将用户连接绑定到群组
     *
     * @param ch       通道
     * @param groupKey 组键值
     */
    public Sessions bindGroup(Channel ch, String groupKey) {
        Sessions userSession;
        if (super.containsKey(groupKey)) {
            userSession = get(groupKey);
        } else {
            userSession = new Sessions(groupKey);
        }
        if (!userSession.contains(ch)) {
            userSession.add(ch);
            super.put(groupKey, userSession);
        }
        return userSession;
    }

    /**
     * 解绑群组连接
     *
     * @param ch
     * @param groupKey
     * @return
     */
    public Sessions unBindGroup(Channel ch, String groupKey) {
        Sessions userSession;
        if (super.containsKey(groupKey)) {
            userSession = get(groupKey);
        } else {
            userSession = new Sessions(groupKey);
        }
        if (userSession.contains(ch)) {
            userSession.remove(ch);
            super.remove(ch);
        }
        return userSession;
    }

    /**
     * 用户退出群组
     *
     * @param userId
     * @return
     */
    public Sessions exitGroup(String userId, String groupKey) {
        Sessions groupSession;
        String userGroupKey = Sessions.PREFIX_BIND_USER_GROUP.concat(userId);
        Sessions userSession = get(userGroupKey);
        if (super.containsKey(groupKey)) {
            groupSession = get(groupKey);
        } else {
            groupSession = new Sessions(groupKey);
        }
        userSession.forEach(w -> {
            groupSession.remove(w);
            super.remove(w);
        });
        return groupSession;
    }

    /**
     * 获取群组Sessions
     *
     * @param groupKey
     * @return
     */
    public Sessions getGroup(String groupKey) {
        return super.getOrDefault(groupKey, new Sessions());
    }

    /**
     * 向集群指定群组推送通知
     *
     * @param groupKey
     * @param msg
     */
    public void sends(String groupKey, Transportable msg) {
        if (AIM.clusterFactory != null) {
            AIM.clusterFactory.push(groupKey, msg);
        } else {
            getGroup(groupKey).sends(msg);
        }
    }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy