RedisTrait.php 10.0 KB
<?php

namespace App\Traits;

use App\Enums\Common\Common;
use App\Enums\Common\RedisKey;
use App\Utils\RedisUtils;
use Illuminate\Support\Facades\Redis;

/**
 * @author:wlj
 * @date: 2022/5/30 17:08
 */
trait RedisTrait
{
    public $login_expire_time;
    public $redis;

    public function __construct()
    {
        $this->login_expire_time = config('app.login_expire_time');
        $this->redis = RedisUtils::getClient();
    }

    /**
     * @notes: 获取redis
     * @return Redis
     * @author:wlj
     * @date: 2022/5/30 17:16
     */
    public function isLock($key): bool
    {
        return (bool)$this->redis->get($key);
    }

    /**
     * @notes: 加锁
     * @param $key
     * @param int $time 秒
     * @return bool
     * @author:wlj
     * @date: 2022/5/30 17:22
     */
    public function lock($key, $time = 600): bool
    {
        return $this->redis->setnx($key, 1) && $this->redis->expire($key, $time);
    }

    /**
     * @notes: 解锁
     * @return bool
     * @author:wlj
     * @date: 2022/5/30 17:22
     */
    public function unLock($key): bool
    {
        return $this->redis->del($key);
    }

    public function blpop($key, $bltime = 10)
    {
        return $this->redis->blPop($key, $bltime);
    }

    /**
     * @notes: 获取位图数据
     * @return Redis
     * @author:wlj
     * @date: 2022/5/30 17:16
     */
    public function getBit($key, $offset): bool
    {
        return (bool)$this->redis->getBit($key, $offset);
    }

    public function setBit($key, $offset, $value): bool
    {
        return (bool)$this->redis->setBit($key, $offset, $value);
    }

    /**
     * @notes: 获取为1的数量
     * @param $key
     * @param null $start
     * @param null $end
     * @return int
     * @author:wlj
     * @date: 2022/6/9 18:29
     */

    public function bitCount($key, $start = null, $end = null)
    {
        if ($start == null || $end == null) {
            return $this->redis->bitCount($key);
        }
        return $this->redis->bitCount($key, $start, $end);
    }

    public function setData($key, $value, $timeout = null)
    {
        return $this->redis->set($key, $value, $timeout);
    }

    public function getData($key)
    {
        return $this->redis->get($key);
    }

    public function delData($key)
    {
        return $this->redis->del($key);
    }

    public function hGet($key, $hashKey)
    {
        return $this->redis->hGet($key, $hashKey);
    }

    public function hGetAll($key)
    {
        return $this->redis->hGetAll($key);
    }

    public function sadd($key, ...$value1)
    {
        return $this->redis->sadd($key, ...$value1);
    }

    public function smembers($key)
    {
        return $this->redis->sMembers($key);
    }


    public function sRem($key, ...$member1)
    {
        return $this->redis->sRem($key, ...$member1);
    }


    public function hSet($key, $hashKey, $value)
    {
        return $this->redis->hSet($key, $hashKey, $value);
    }

    public function hDel($key, $hashKey)
    {
        return $this->redis->hDel($key, $hashKey);
    }

    #region 登录相关

    /**
     * @notes: 用户登录设置
     * @param array $userInfo
     * @param $token
     * @author:wlj
     * @date: 2022/6/14 16:34
     */
    public function loginset(array $userInfo, $token)
    {
        $this->setData(RedisKey::USER_LOGIN . $token, json_encode($userInfo, true), $this->login_expire_time);
        $this->redis->sAdd(RedisKey::USER_TOKEN . $userInfo['account_id'], $token);
//        $this->setData(RedisKey::USER_TOKEN . $userInfo['account_id'], $token, $this->login_expire_time);
        $this->hSet(RedisKey::USER_LAST_LOGIN_COMPANY, $userInfo['account_id'], $userInfo['company_id']);
        return true;
    }

    /**
     * @notes: 获取登录信息
     * @param $token
     * @return mixed
     * @author:wlj
     * @date: 2022/7/8 17:15
     */
    public function getloginset($token)
    {
        $singleSign = config('app.single_sign');
        $userInfo = json_decode($this->getData(RedisKey::USER_LOGIN . $token), true);
        $hasToken = false;
        if ($userInfo) {
            $hasToken = $this->redis->sIsMember(RedisKey::USER_TOKEN . $userInfo['account_id'], $token);
        }
        //单点登录
//        if ($singleSign) {
//            $accountId = $userInfo['account_id'] ?? 0;
//            $tokenOri = $this->getData(RedisKey::USER_TOKEN . $accountId);
//            if ($userInfo && ($token == $tokenOri)) {
//                return $userInfo;
//            } else {
//                return [];
//            }
//        }
//    else {
//        return empty($userInfo) ? [] : $userInfo;
//    }
        return (!empty($userInfo) && $hasToken) ? $userInfo : [];
    }

    /**
     * @notes: 用户退出登录设置
     * @param $token
     * @author:wlj
     * @date: 2022/6/14 16:34
     */
    public function logoutset($token)
    {
        $singleSign = config('app.single_sign');

        $userInfo = json_decode($this->getData(RedisKey::USER_LOGIN . $token), true);
        //清除redis tokren对应 user_info数据
        $this->redis->del(RedisKey::USER_LOGIN . $token);
        if ($userInfo) {
            //清除redis token集合中的数据
            $this->redis->sRem(RedisKey::USER_TOKEN . $userInfo['account_id'], $token);
            //退出登录时 删除公司权限
            $this->redis->hDel(RedisKey::USER_PERMISSION, $userInfo['id']);
        }

//        if ($singleSign && $userInfo) {
//            $userInfo = json_decode($userInfo, true);
//            $this->redis->del(RedisKey::USER_TOKEN . $userInfo['account_id']);
//        }

        return true;
    }

    /**
     * @notes: 用户退出登录设置--通过accountId
     * @param $accountId
     * @return bool
     * @author:wlj
     * @date: 2023/3/2 17:08
     */
    public function logoutsetByaccountId($accountId)
    {
        $tokens = $this->redis->sMembers(RedisKey::USER_TOKEN . $accountId);
        $this->delData(RedisKey::USER_TOKEN . $accountId);
        foreach ($tokens as $token) {
            $this->redis->del(RedisKey::USER_LOGIN . $token);
        }

        return true;
    }

    #endregion 登录相关

    /**
     * 设置用户权限
     * @param $userId
     * @param array $permissions
     * @return bool|int
     */
    public function setUserPermission($userId, $permissions = [])
    {
        return $this->hSet(RedisKey::USER_PERMISSION, $userId, json_encode($permissions));
    }

    /**
     * 获取用户权限
     * @param $userId
     * @return array
     */
    public function getUserPermission($userId): array
    {
        $permissions = $this->hGet(RedisKey::USER_PERMISSION, $userId);
        return empty($permissions) ? [] : json_decode($permissions, true);
    }

    /**
     * 删除用户公司权限
     * @param $userId
     */
    public function deleteUserPermission($userId)
    {
        return $this->hDel(RedisKey::USER_PERMISSION, $userId);
    }

    /**
     * 设置项目成员权限
     * @param $userId
     * @param array $permissions
     * @return bool|int
     */
    public function setProjectMemberPermission($memberId, $permissions = [])
    {
        return $this->hSet(RedisKey::MEMBER_PROJECT_PERMISSION, $memberId, json_encode($permissions));
    }

    /**
     * 获取项目成员权限
     * @param $userId
     * @return array
     */
    public function getProjectMemberPermission($memberId): array
    {
        $permissions = $this->hGet(RedisKey::MEMBER_PROJECT_PERMISSION, $memberId);
        return empty($permissions) ? [] : json_decode($permissions, true);
    }

    /**
     * 删除项目员工权限
     * @param $memberId
     */
    public function deleteProjectMemberPermission($memberId)
    {
        return $this->hDel(RedisKey::MEMBER_PROJECT_PERMISSION, $memberId);
    }

    /**
     * @notes: 删除数据
     * @param $key
     * @return int
     * @author:wlj
     * @date: 2022/10/31 15:58
     */
    public function deleteKey($key)
    {
        return $this->redis->del($key);
    }

    /**
     * @notes: 获取用户的fd 空为未上线 无需推送
     * @param $token
     * @return bool|mixed|string
     * @author:wlj
     * @date: 2022/10/31 15:59
     */
    public function getUserFd($token)
    {
        return $this->getData(RedisKey::USER_FD_DATA . $token);
    }

    /**
     * @notes: 给用户们添加新的未读的需求
     * @param array $userIds
     * @param int $storyId
     * @author:wlj
     * @date: 2022/11/2 16:00
     */
    public function addUserAbeyanceStory($userIds = [], $storyId = 0)
    {
        foreach ($userIds as $userId) {
            $this->hSet(RedisKey::USER_ABEYANCE_STORY . $userId, $storyId, Common::YES);
        }
        return true;
    }

    public function readUserAbeyanceStory($userIds = [], $storyId = 0)
    {
        foreach ($userIds as $userId) {
            $this->hDel(RedisKey::USER_ABEYANCE_STORY . $userId, $storyId);
        }
        return true;
    }

    public function getKeys($patten)
    {
        return $this->redis->keys($patten);
    }

    /**
     * @notes: 插入用户最近查看数据 默认10条 多的会trim掉
     * @author:wlj
     * @date: 2023/2/20 16:57
     */
    public function setUserRecentActions($companId, $userId, $actionableType, $actionableId)
    {
        $user_recent_limit = config('app.user_recent_limit');
        $start = 0;
        $stop = -$user_recent_limit - 1;
        $this->redis->zAdd(RedisKey::USER_RECENT_ACTIONS . $companId . '_' . $userId . '_' . $actionableType, [], time(), $actionableId);
        $this->redis->zRemRangeByRank(RedisKey::USER_RECENT_ACTIONS . $companId . '_' . $userId . '_' . $actionableType, $start, $stop);
        return true;
    }

    /**
     * @notes: 获取用户最近查看数据 默认10条
     * @param $companId
     * @param $userId
     * @param $actionableType
     * @return array
     * @author:wlj
     * @date: 2023/2/21 10:05
     */
    public function getUserRecentActions($companId, $userId, $actionableType)
    {
        return $this->redis->zRevRangeByScore(RedisKey::USER_RECENT_ACTIONS . $companId . '_' . $userId . '_' . $actionableType, +INF, -INF, ['withscores' => true]);
    }

}