php单例模式简易封装redis

5 篇文章 0 订阅
<?php
/**
 * Created by PhpStorm.
 * User: 
 * Date: 2021/6/23
 * Time: 15:42
 */
class Rediscurd
{
	//
    private static $redis;
    //redis连接
    private $conn;
    //私有构造函数
    private function __construct()
    {
    	//连接本地redis
        $host = "127.0.0.1";
        $port = "6379";
        $this->conn = new Redis();
        $this->conn -> connect($host,$port);
    }
	//私有克隆方式
    private function __clone()
    {
        // TODO: Implement __clone() method.
    }
	//单一获取对象入口
    public static function get_instance(){
    	//若部位该类对象则实例化对象,若不是则返回已实例化对象
        if (!self::$redis instanceof self){
            self::$redis = new self;
        }
        return self::$redis;
    }

    /*
     * 设置redis
     * value redis设置的值
     * expire redis过期时间
     *
    */
    public  function set_redis($key,$value,$expire=0){
        if (is_array($value)){
            $value = json_encode($value);
        }
        return $expire ? $this->conn->set($key,$value,$expire): $this->conn->set($key,$value);
    }

    /*
     * 获取redis
     * key redis的键
     * return array|int|string
     */
    public function get_redis($key){
       $data = $this->conn->get($key);
       return json_decode($data) ? json_decode($data) : $data;
    }

    /*
     * 移除redis
     * key redis的键
     */
    public function del_redis($key){
        return $this->conn->del($key);
    }
    
     /*
     * php list操作
     * lpush操作
     */
    public function lpush($list,$value){
        $value = is_array($value) ? json_encode($value) : $value;
        return $this->conn->lPush($list,$value);
    }

    /*
     * rpush操作
     */
    public function rpush($list,$value){
        $value = is_array($value) ? json_encode($value) : $value;
        return $this->conn->rPush($list,$value);
    }

    /*
     * lrange操作
     */
    public function lrange($key,$start,$end){
        $res = $this->conn->lRange($key,$start,$end);
        foreach ($res as & $k){
            if (json_decode($k)){
                $k = json_decode($k);
            }
        }
        return $res;
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值