By default it assumes there is a redis server running on localhost at port 6379 and uses the database number 0. It is possible to connect to a redis server using [[hostname]] and [[port]] or using a [[unixSocket]]. It also supports the AUTH command of redis. When the server needs authentication, you can set the [[password]] property to authenticate with the server after connect. The execution of redis commands is possible with via Connection::executeCommand.
부터: 2.0
저자: Carsten Brandt (mail@cebe.cc)
상속: extends yii\base\Component
예제 #1
0
 /**
  * @param  boolean    $reset whether to clean up the test database
  * @return Connection
  */
 public function getConnection($reset = true)
 {
     $databases = $this->getParam('databases');
     $params = isset($databases['redis']) ? $databases['redis'] : [];
     $db = new Connection($params);
     if ($reset) {
         $db->open();
         $db->flushdb();
     }
     return $db;
 }
 public function actionDeleteCache(Connection $redis, Response $response)
 {
     $data = $errorMsg = '';
     try {
         $redis->del(self::HASH_KEY);
         $data = 'Кэш сброшен';
     } catch (Exception $e) {
         $errorMsg = $e->getMessage();
     }
     $response->format = Response::FORMAT_JSON;
     return ['data' => $data, 'error' => $errorMsg];
 }
예제 #3
0
 public function __call($name, $params)
 {
     $redisCommand = strtoupper(Inflector::camel2words($name, false));
     if (in_array($redisCommand, $this->redisCommands)) {
         return $this->executeCommand($name, $params);
     } else {
         return parent::__call($name, $params);
     }
 }
예제 #4
0
 /**
  * @return mixed
  * @throws InvalidConfigException
  */
 public function configGetDatabases()
 {
     try {
         if ($this->_connect instanceof PhpredisConnection) {
             return $this->_connect->executeCommand('CONFIG', ['GET', 'databases'])['databases'];
         } else {
             return $this->_connect->executeCommand('CONFIG', ['GET', 'databases'])[1];
         }
     } catch (\Exception $e) {
         throw new InvalidConfigException('Can`t connect to redis database, please check module and redis-connection settings!!!!');
     }
 }
예제 #5
0
 /**
  * Initializes the redis Counter component.
  * This method will initialize the [[redis]] property to make sure it refers to a valid redis connection.
  * @throws InvalidConfigException if [[redis]] is invalid.
  */
 public function init()
 {
     parent::init();
     if (is_string($this->redis)) {
         $this->redis = Yii::$app->get($this->redis);
     } elseif (is_array($this->redis)) {
         if (!isset($this->redis['class'])) {
             $this->redis['class'] = Connection::className();
         }
         $this->redis = Yii::createObject($this->redis);
     }
     if (!$this->redis instanceof Connection) {
         throw new InvalidConfigException("Counter::redis must be either a Redis connection instance or the application component ID of a Redis connection.");
     }
 }
예제 #6
0
 /**
  * @inherit
  *
  * 针对键值相关命令, 需要根据键对应的业务标识选择指定的数据库
  */
 public function __call($name, $params)
 {
     $key = false;
     $busiName = null;
     $redisCommand = strtoupper(Inflector::camel2words($name, false));
     if (in_array($redisCommand, $this->keyValueCommands)) {
         if (is_array($params)) {
             $key = $params[0];
         }
         if ($key && ($busiName = $this->parseBusiName($key))) {
             $this->setDB($busiName);
         } else {
             throw new \OutOfRangeException('Business key parse failed');
         }
     }
     return parent::__call($name, $params);
 }
예제 #7
0
 /**
  * Initializes the redis Session component.
  * This method will initialize the [[redis]] property to make sure it refers to a valid redis connection.
  * @throws InvalidConfigException if [[redis]] is invalid.
  */
 public function init()
 {
     if (is_string($this->redis)) {
         $this->redis = Yii::$app->get($this->redis);
     } elseif (is_array($this->redis)) {
         if (!isset($this->redis['class'])) {
             $this->redis['class'] = Connection::className();
         }
         $this->redis = Yii::createObject($this->redis);
     }
     if (!$this->redis instanceof Connection) {
         throw new InvalidConfigException("Session::redis must be either a Redis connection instance or the application component ID of a Redis connection.");
     }
     if ($this->keyPrefix === null) {
         $this->keyPrefix = substr(md5(Yii::$app->id), 0, 5);
     }
     parent::init();
 }
예제 #8
0
 protected function tearDown()
 {
     $this->redis->executeCommand('FLUSHDB');
     parent::tearDown();
 }
예제 #9
0
 /**
  * Fetch by pk if possible as this is much faster
  * @param Connection $db the database connection used to execute the query.
  * If this parameter is not given, the `db` application component will be used.
  * @param string $type the type of the script to generate
  * @param string $columnName
  * @return array|bool|null|string
  * @throws \yii\base\InvalidParamException
  * @throws \yii\base\NotSupportedException
  */
 private function findByPk($db, $type, $columnName = null)
 {
     if (count($this->where) == 1) {
         $pks = (array) reset($this->where);
     } else {
         foreach ($this->where as $values) {
             if (is_array($values)) {
                 // TODO support composite IN for composite PK
                 throw new NotSupportedException('Find by composite PK is not supported by redis ActiveRecord.');
             }
         }
         $pks = [$this->where];
     }
     /* @var $modelClass ActiveRecord */
     $modelClass = $this->modelClass;
     if ($type == 'Count') {
         $start = 0;
         $limit = null;
     } else {
         $start = $this->offset === null ? 0 : $this->offset;
         $limit = $this->limit;
     }
     $i = 0;
     $data = [];
     foreach ($pks as $pk) {
         if (++$i > $start && ($limit === null || $i <= $start + $limit)) {
             $key = $modelClass::keyPrefix() . ':a:' . $modelClass::buildKey($pk);
             $result = $db->executeCommand('HGETALL', [$key]);
             if (!empty($result)) {
                 $data[] = $result;
                 if ($type === 'One' && $this->orderBy === null) {
                     break;
                 }
             }
         }
     }
     // TODO support orderBy
     switch ($type) {
         case 'All':
             return $data;
         case 'One':
             return reset($data);
         case 'Count':
             return count($data);
         case 'Column':
             $column = [];
             foreach ($data as $dataRow) {
                 $row = [];
                 $c = count($dataRow);
                 for ($i = 0; $i < $c;) {
                     $row[$dataRow[$i++]] = $dataRow[$i++];
                 }
                 $column[] = $row[$columnName];
             }
             return $column;
         case 'Sum':
             $sum = 0;
             foreach ($data as $dataRow) {
                 $c = count($dataRow);
                 for ($i = 0; $i < $c;) {
                     if ($dataRow[$i++] == $columnName) {
                         $sum += $dataRow[$i];
                         break;
                     }
                 }
             }
             return $sum;
         case 'Average':
             $sum = 0;
             $count = 0;
             foreach ($data as $dataRow) {
                 $count++;
                 $c = count($dataRow);
                 for ($i = 0; $i < $c;) {
                     if ($dataRow[$i++] == $columnName) {
                         $sum += $dataRow[$i];
                         break;
                     }
                 }
             }
             return $sum / $count;
         case 'Min':
             $min = null;
             foreach ($data as $dataRow) {
                 $c = count($dataRow);
                 for ($i = 0; $i < $c;) {
                     if ($dataRow[$i++] == $columnName && ($min == null || $dataRow[$i] < $min)) {
                         $min = $dataRow[$i];
                         break;
                     }
                 }
             }
             return $min;
         case 'Max':
             $max = null;
             foreach ($data as $dataRow) {
                 $c = count($dataRow);
                 for ($i = 0; $i < $c;) {
                     if ($dataRow[$i++] == $columnName && ($max == null || $dataRow[$i] > $max)) {
                         $max = $dataRow[$i];
                         break;
                     }
                 }
             }
             return $max;
     }
     throw new InvalidParamException('Unknown fetch type: ' . $type);
 }
예제 #10
0
 /**
  * Initializes the redis Cache component.
  * This method will initialize the [[redis]] property to make sure it refers to a valid redis connection.
  * @throws InvalidConfigException if [[redis]] is invalid.
  */
 public function init()
 {
     parent::init();
     $this->redis = Instance::ensure($this->redis, Connection::className());
 }
예제 #11
0
 /**
  * Purge the whole queue.
  * @return boolean
  */
 public function purge()
 {
     return $this->db->del($this->key);
 }
예제 #12
0
파일: main.php 프로젝트: baranov-nt/setyes
<?php

return ['name' => 'setYes', 'language' => 'ru', 'charset' => 'UTF-8', 'vendorPath' => dirname(dirname(__DIR__)) . '/vendor', 'components' => ['userAgentParser' => ['class' => \yii\useragentparser\UserAgentParser::className(), 'nameHttpPropertyUserAgent' => 'HTTP_USER_AGENT'], 'googleApi' => ['class' => \common\widgets\GoogleMapsMarkers\GoogleMaps::className(), 'geocode_api_key' => 'AIzaSyBn0XnEmdPDw9ku7H66JT4_9KN7IXDZfcA', 'webroot' => '@webroot', 'map_language' => 'en'], 'reCaptcha' => ['name' => 'reCaptcha', 'class' => 'himiklab\\yii2\\recaptcha\\ReCaptcha', 'siteKey' => '6LcWAxMTAAAAAD2teUNSJdJ8OwfQuqIUyJJDW79j', 'secret' => '6LcWAxMTAAAAAEZCbXGi-azhHhA8kYRq5WmY9pLg'], 'redis' => ['class' => \yii\redis\Connection::className(), 'hostname' => 'localhost', 'port' => 6379, 'database' => 0, 'dataTimeout' => 30], 'cache' => ['class' => 'yii\\redis\\Cache', 'redis' => ['hostname' => 'localhost', 'port' => 6379, 'database' => 1]], 'session' => ['class' => 'yii\\redis\\Session', 'redis' => ['hostname' => 'localhost', 'port' => 6379, 'database' => 2]], 'authManager' => ['class' => 'yii\\rbac\\DbManager'], 'authClientCollection' => require __DIR__ . '/auth.php', 'assetManager' => ['class' => 'yii\\web\\AssetManager'], 'formatter' => ['defaultTimeZone' => 'UTC', 'datetimeFormat' => 'php:d.mm.Y H:s', 'decimalSeparator' => ',', 'thousandSeparator' => ' ', 'currencyCode' => 'RUB'], 'i18n' => ['class' => common\widgets\yii2TranslatePanel\components\I18N::className(), 'languages' => ['ru', 'de', 'fr'], 'format' => 'db', 'sourcePath' => [__DIR__ . '/../../frontend', __DIR__ . '/../../backend', __DIR__ . '/../../common', __DIR__ . '/../../console'], 'messagePath' => __DIR__ . '/../../messages', 'translations' => ['*' => ['class' => yii\i18n\DbMessageSource::className(), 'enableCaching' => true, 'cachingDuration' => 60 * 60 * 2], 'yii' => ['class' => yii\i18n\DbMessageSource::className(), 'enableCaching' => true, 'cachingDuration' => 60 * 60 * 2], 'app' => ['class' => yii\i18n\DbMessageSource::className(), 'enableCaching' => true, 'cachingDuration' => 60 * 60 * 2]]]]];