# Redis [TOC] SD提供了Redis异步连接池,连接池的使用和正常Redis扩展一样。 ## 创建Redis连接池 在SD的initAsynPools方法中已经创建好了redis和mysql默认的连接池。 ``` /** * 初始化各种连接池 * @param $workerId */ public function initAsynPools($workerId) { $this->asynPools = []; if ($this->config->get('redis.enable', true)) { $this->asynPools['redisPool'] = new RedisAsynPool($this->config, $this->config->get('redis.active')); } if ($this->config->get('mysql.enable', true)) { $this->asynPools['mysqlPool'] = new MysqlAsynPool($this->config, $this->config->get('mysql.active')); } $this->redis_pool = $this->asynPools['redisPool'] ?? null; $this->mysql_pool = $this->asynPools['mysqlPool'] ?? null; } ``` 如果你想创建多个Redis连接池可以仿照上面的方法。 ``` $this->addAsynPool('redisPool2', new RedisAsynPool($this->config, ‘redis2’); ``` ## 获取Redis连接池 在Controller,Model,Task共同的基类CoreBase中默认获取了RedisPool。 ``` /** * 当被loader时会调用这个方法进行初始化 * @param $context */ public function initialization(&$context) { $this->setContext($context); $this->redis = $this->loader->redis("redisPool"); $this->db = $this->loader->mysql("mysqlPool",$this); } ``` ## 使用方法 Redis的使用方法和PhpRedis扩展一致,可以参考ServerRedisTest,这是关于Redis的测试用例。 ``` $value = $this->redis->set('test', 'testRedis'); ``` ## Redis-LUA SD支持Redis-LUA,根目录下有个名为lua的文件夹,这里的lua脚本都会自动被SD加载进Redis中。 ``` public function http_testRedisLua() { $value = $this->redis->evalSha(getLuaSha1('sadd_from_count'), ['testlua', 100], 2, [1, 2, 3]); $this->http_output->end($value); } ``` 通过evalSha和getLuaSha1方法配合我们可以非常容易的使用Redis-LUA功能。其中sadd_from_count是lua文件夹某一个lua脚本的文件名。 在SD启动时我们也能看到加载了哪些lua脚本,如果redis服务器不支持lua也会有相应的提示。 ![](https://box.kancloud.cn/6aa55e3de0a42ad861f98374ab792608_512x148.png) ## 同步Redis ``` $redisSync = $this->redis_pool->getSync(); ``` 通过getSync返回一个同步的redis连接。