单例模式连接redis类,并在项目中运用redis缓存数据

一、单例模式连接redis类,这个类可以直接放在项目中的extend扩展文件夹中,在项目中使用的时候可以直接实例化用
<?php

namespace MyRedis;
class RedisPackage
{
    private static $handler = null;
    private static $_instance = null;
    //默认配置
    private static $options = [
        'host' => '127.0.0.1',
        'port' => 6379,
        'password' => '',
        'select' => 0,
        'timeout' => 0,
        'expire' => 0,
        'persistent' => false,
        'prefix' => '',
    ];

    public function __construct($options = [])
    {
        if (!extension_loaded('redis')) {
            throw new \BadFunctionCallException('not support: redis');      //判断是否有扩展
        }
        if (!empty($options)) {
            self::$options = array_merge(self::$options, $options);
        }

        $func = self::$options['persistent'] ? 'pconnect' : 'connect';     //长链接或短链接
        $handler = new \Redis;
        $handler->connect(self::$options['host'], self::$options['port'], self::$options['timeout']);

        if ('' != self::$options['password']) {
            $handler->auth(self::$options['password']);
        }
        self::$handler  = $handler;
        if (0 != self::$options['select']) {
            self::$handler->select(self::$options['select']);
        }
    }


    /**
     * @return RedisPackage|null 对象
     */
    public static function getInstance()
    {
        if (!(self::$_instance instanceof self)) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    /**
     * 禁止外部克隆
     */
    public function __clone()
    {
        trigger_error('Clone is not allow!',E_USER_ERROR);
    }

    /**
     * 获得redis实例
     *
     */

    public static function getRedisObj(){

        return self::$handler;
    }



}

二、项目中运用redis缓存数据控制器:

<?php
namespace app\admin\controller;
use \MyRedis\RedisPackage;
/*
 * redis连接控制器
 * author 赫陈
 * date   2019-09-25
 */

class Redisparam extends Base {
    public $redis;
    public function _initialize(){
        //设置redis缓存
        $option = config('redis');
        $RedisPackage = new RedisPackage($option);
        $redis = $RedisPackage -> getRedisObj();
        $this->redis = $redis;
    }

    public function index(){
        $redis = $this -> redis ;
        //普通的set、get操作
        $redis->set('username','hehe5');
        $username = $redis->get('username');

        //del 删除
       /* $res = $redis->del('username');//true
        //检测是否存在某值
        $res = $redis->exists('username');
        */
        //hset/hget 存取hash表的数据
        $redis->hset('hash1','key1','v1'); //将key为’key1′ value为’v1′的元素存入hash1表
        $redis->hset('hash1','key2','v2');
        $res = $redis->hget('hash1','key1');  //取出表’hash1′中的key 'key1′的值,返回’v1′

        dump($username);die;
    }
}


猜你喜欢

转载自blog.csdn.net/hechenhongbo/article/details/102671594