🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
2.x配置文件时Config.php ``` 'REDIS'=>[ 'host'=>'127.0.0.1', 'port'=>'6379', 'time_out'=>20 ] ``` 控制器使用 ``` //easySwoole2.x\vendor\easyswoole\easyswoole\src\Config.php use EasySwoole\Config; class xxx{ public xx(){ $redisConfig=Config::getInstance()->getConf("REDIS"); } } ``` ## **配置单独的配置文件** 项目文件下新建Conf/redis.php ``` return [ 'host'=>'127.0.0.1', 'port'=>'6379', 'time_out'=>20 ]; ``` 在项目的全局事件文件`EasySwooleEvent`中的frameInitialize方法添加`$this->loadConf(EASYSWOOLE_ROOT . '/Conf'); `,然后新建LoadConf方法,注意引入File类 ``` <?php namespace EasySwoole; use \EasySwoole\Core\AbstractInterface\EventInterface; //use \EasySwoole\Core\Component\Di; use App\Lib\Redis\Redis; use EasySwoole\Core\Utility\File; Class EasySwooleEvent implements EventInterface { public static function frameInitialize(): void { date_default_timezone_set('Asia/Shanghai'); // 载入项目 Conf 文件夹中所有的配置文件 self::loadConf(EASYSWOOLE_ROOT . '/Conf'); } public function static loadConf($ConfPath) { //easySwoole2.x\vendor\easyswoole\easyswoole\src\Config.php的命名空间都是EasySwoole这里可以省略 $Conf = Config::getInstance(); $files = File::scanDir($ConfPath); foreach ($files as $file) { $data = require_once $file; $Conf->setConf(strtolower(basename($file, '.php')), (array)$data); } } } ``` Redis.php ``` <?php namespace App\Lib\Redis; use EasySwoole\Core\AbstractInterface\Singleton; use EasySwoole\Config; class Redis{ use Singleton; public $redis=""; private function __construct(){ if (!extension_loaded('redis')) { throw new \Exception("redis扩展未开启", 1); } try{ $this->redis=new \Redis(); //$result=$this->redis->connect("127.0.0.1", 6379,20); // $redisConfig=Config::getInstance()->getConf("REDIS"); $redisConfig=Config::getInstance()->getConf("redis"); $result=$this->redis->connect($redisConfig['host'], $redisConfig['port'],$redisConfig['time_out']); }catch(\Exception $e){ throw new \Exception("redis链接异常", 1); } if ($result===false) { throw new \Exception("redis 链接失败", 1); } } public function get($key){ if (empty($key)) { return ""; } return $this->redis->get($key); } public function set($key,$value){ if (empty($key)||empty($value)) { return ""; } return $this->redis->set($key,$value); } } ```