创建Redis连接
@param {String | Object} config 配置参数
770986
function createRedis(config) {

    if (!config) {
        console.debug('createRedis config is NULL');
        return;
    }
    // 如果为文件路径. 加载文件
    if (typeof config === 'string') {
        config = Utils.UString.readConfig(config);  // JSON.parse(fs.readFileSync(config, "utf8"));
    }
    var opts = {};
    if (config.proxy) {
        opts.no_ready_check = config.proxy;
        if (config.auth_pass) {
            opts.auth_pass = config.auth_pass;
        }
        if (config.debug_mode) {
            opts.debug_mode = config.debug_mode;
        }
        if (config.encoding) {
            opts.encoding = config.encoding;
        }
        if (config.return_buffers) {
            opts.return_buffers = config.return_buffers;
        }

        var client = redis.createClient(config.port, config.host, opts);
        client.on('error', function (err) {
            console.error('连接Redis出现错误: %s', err.stack);
        });
        pools[config.name] = {};
        pools[config.name].client = client;
        pools[config.name].proxy = true;
    } else {
        opts.no_ready_check = true;
        if (config.auth_pass) {
            opts.auth_pass = config.auth_pass;
        }
        if (config.debug_mode) {
            opts.debug_mode = config.debug_mode;
        }
        if (config.encoding) {
            opts.encoding = config.encoding;
        }

        var _pool = gpool.Pool({
            name: config.name,
            dbIndex: 0,
            create: function (cb) {
                var client = redis.createClient(config.port, config.host, opts);
                client.on('error', function (err) {
                    console.error('连接Redis出现错误: %s', err.stack);
                });
                cb(null, client);
            },
            destroy: function (client) {
                if (client) {
                    client.quit();
                }
            },
            max: 1000,
            idleTimeoutMillis: 30000,
            log: false
        });
        pools[config.name] = {};
        pools[config.name].client = _pool;
        pools[config.name].proxy = false;
    }

    if (config.auth_pass) {
        pools[config.name].auth_pass = config.auth_pass;
    }
}
1079789
function readServerConfig( server ) {
  try {
    const severConfig = getConfig( appSeverConfig );
    return Right( Object.assign( server, severConfig ));
  } catch ( e ) {
    print(
      chalk.red( `Failed to read ${SEVER_CONFIG}.` ),
      e.message
    );
    print();
    return Left( null );
  }
}
377631
function (config) {
		if (typeof config === 'undefined') { config = {}; }
		/**
		 * the "memory" where the language parts go
		 */
		this.memory = {};
		/**
		 * If you want to delimit the generated parts
		 */
		this.separator = (config.separator) ? config.separator : '';
		/**
		 * How many... something... to something.... oh it's been too long I don't remember how this works...
		 */
		this.order = (config.order) ? config.order : 2;
		/**
		 * Feed text to memory
		 * @param {String} key key for the chain (so we can store multiple memories)
		 * @param {String} txt word or phrase
		 * @return {null} null
		 */
		this.learn = function (key, txt) {
			const mem = (this.memory[key]) ? this.memory[key] : {};
			// split up text then add the calculated parts to the memory for this ket
			this.breakText(txt, (key, value) => {
				// console.log(key);
				if (!mem[key]) {
					mem[key] = [];
				}
				mem[key].push(value);
				return mem;
			});
			this.memory[key] = mem;
		};
		/**
		 * Return a generated response
		 * @param {String} key key for the chain (so we can store multiples
		 * @param {Array} seed letters to start the response (?)
		 */
		this.generate = function (key, seed) {
			if (!seed) {
				seed = this.genInitial();
			}
			this.cur_key = key;
			return seed.concat(this.step(seed, [])).join(this.separator);
		};
		/**
		 * iterate through, calls self
		 * @param {Array} state array of most recent x(x=order) elements in chain
		 * @param {Array} ret the chain
		 * @return {Array}
		 */
		this.step = function (state, ret) {
			const nextAvailable = this.memory[this.cur_key][state] || [''];
			const next = this.getRandomValue(nextAvailable);
			// we don't have anywhere to go
			if (!next) {
				return ret;
			}
			ret.push(next);
			var nextState = state.slice(1);
			nextState.push(next);
			return this.step(nextState, ret);
		};
		/**
		 * Chunk the word or phrase
		 * @param {String} txt the text to chunk
		 * @param {Function} cb callback function
		 * @return {null} null
		 */
		this.breakText = function (txt, cb) {
			const parts = txt.split(this.separator);
			const prev = this.genInitial();
			
			parts.forEach((v) => {
				v = v.toLowerCase();
				cb(prev, v);
				prev.shift();
				prev.push(v);
			});
			cb(prev, '');
		};
		/**
		 * Generate a starting array for the chain based on the order number
		 * @return {Array} just an empty array of length=order
		 */
		this.genInitial = function () {
			const ret = [];
			for (
				let i = 0;
				i < this.order;
				ret.push(''),
				i++
			);
			return ret;
		};
		/**
		 * Get a random array element
		 * @param {Array} arr an array
		 * @return {String|Object}	random value
		 */
		this.getRandomValue = function (arr) {
			return arr[Math.floor(Math.random() * arr.length)];
		};
	}
481238
private function file($config = array()) {
        $filePath = $config['filePath'];

        if (!file_exists($filePath)) {
            Filesystem::mkdir($filePath);
        }
        //初始化缓存路径
        CacheManager::setup(array(
            "path" => isset($filePath) ? $filePath : sys_get_temp_dir(), // or in windows "C:/tmp/"
        ));
        CacheManager::CachingMethod("phpfastcache");

        //初始化缓存
        $InstanceCache = CacheManager::Files();

        return $InstanceCache;
    }
1086293
function SessionNamespace(config, namespace, RedisClient) {
      this.config = config;
      this.namespace = namespace;
      this.RedisClient = RedisClient;
      this.storeKey = __bind(this.storeKey, this);
      this.destroy = __bind(this.destroy, this);
      this.remove = __bind(this.remove, this);
      this.get = __bind(this.get, this);
      this.put = __bind(this.put, this);
      this.has = __bind(this.has, this);
      this.id = base64id.generateId();
      this.is_started = true;
    }
1324948
function creds(done) {
  var configPath = './config.json';
  try { CONFIG = JSON.parse(fs.readFileSync(configPath)); }
  catch(e) {
    beep();
    console.log('[AWS]'.bold.red + ' Sorry, there was an issue locating your config.json. Please see README.md');
    process.exit();
  }
  done();
}
883282
protected function getRedisHandler(array $config)
    {
        $options = array_get($config, 'redis', []);
        // In case anyone puts the servers under redis configuration - similar to how we handle cache
        $servers = array_get($options, 'servers', []);
        if (empty($servers)) {
            $servers = array_get($config, 'servers', []);
        }

        $redis = $this->getRedisInstance($servers);
        if (!empty($options['database'])) {
            $redis->select((int) $options['database']);
        }

        // In case of anyone setting prefix on the redis server directly
        // Similar to how we do it on cache
        $prefix = array_get($options, 'prefix', 'CCM_SESSION');

        // We pass the prefix to the Redis Handler when we build it
        return $this->app->make(RedisSessionHandler::class, [$redis, ['prefix' => array_get($config, 'name') ?: $prefix]]);
    }
636334
public RedisDS init(String group) {
		if (null == setting) {
			setting = new Setting(REDIS_CONFIG_PATH, true);
		}

		final JedisPoolConfig config = new JedisPoolConfig();
		// 共用配置
		setting.toBean(config);
		if (StrUtil.isNotBlank(group)) {
			// 特有配置
			setting.toBean(group, config);
		}

		this.pool = new JedisPool(config,
				// 地址
				setting.getStr("host", group, Protocol.DEFAULT_HOST),
				// 端口
				setting.getInt("port", group, Protocol.DEFAULT_PORT),
				// 连接超时
				setting.getInt("connectionTimeout", group, setting.getInt("timeout", group, Protocol.DEFAULT_TIMEOUT)),
				// 读取数据超时
				setting.getInt("soTimeout", group, setting.getInt("timeout", group, Protocol.DEFAULT_TIMEOUT)),
				// 密码
				setting.getStr("password", group, null),
				// 数据库序号
				setting.getInt("database", group, Protocol.DEFAULT_DATABASE),
				// 客户端名
				setting.getStr("clientName", group, "Hutool"),
				// 是否使用SSL
				setting.getBool("ssl", group, false),
				// SSL相关，使用默认
				null, null, null);

		return this;
	}
545805
function serializeBucketConfig(config) {
    var cfg, k;

    cfg = {};
    if (typeof (config) == 'object' && config !== null) {
        for (k in config) {
            cfg[k] = config[k];
        }
    }

    cfg.pre = (config.pre || []).map(function (f) {
        return (f.toString());
    });
    cfg.post = (config.post || []).map(function (f) {
        return (f.toString());
    });

    return (cfg);
}
1000944
public static function client(array $config = []): RedisInterface
    {
        $driver = $config['driver'] ?? '';

        if ($driver === 'native' || !PHP_REDIS_EXTENSION) {
            return new Client\Native($config);
        }

        return new Client\PhpRedis($config);
    }
391539
public static RedissonClient create(Config config) {
        Redisson redisson = new Redisson(config);
        if (config.isReferenceEnabled()) {
            redisson.enableRedissonReferenceSupport();
        }
        return redisson;
    }
131729
public static function loadConfig($file = self::DEFAULT_CONFIG_FILE)
    {
        self::readConfigFile($file);

        Redis::setConfig(array(
            'scheme'     => static::getConfig('redis.scheme', Redis::DEFAULT_SCHEME),
            'host'       => static::getConfig('redis.host', Redis::DEFAULT_HOST),
            'port'       => static::getConfig('redis.port', Redis::DEFAULT_PORT),
            'namespace'  => static::getConfig('redis.namespace', Redis::DEFAULT_NS),
            'password'   => static::getConfig('redis.password', Redis::DEFAULT_PASSWORD),
            'rw_timeout' => static::getConfig('redis.rw_timeout', Redis::DEFAULT_RW_TIMEOUT),
            'phpiredis'  => static::getConfig('redis.phpiredis', Redis::DEFAULT_PHPIREDIS),
            'predis'     => static::getConfig('predis'),
        ));

        return true;
    }
557379
protected function createClient(array $config)
    {
        return tap(new Redis, function ($client) use ($config) {
            $this->establishConnection($client, $config);

            if (! empty($config['password'])) {
                $client->auth($config['password']);
            }

            if (! empty($config['database'])) {
                $client->select($config['database']);
            }

            if (! empty($config['prefix'])) {
                $client->setOption(Redis::OPT_PREFIX, $config['prefix']);
            }

            if (! empty($config['read_timeout'])) {
                $client->setOption(Redis::OPT_READ_TIMEOUT, $config['read_timeout']);
            }
        });
    }
1198043
function(url, config) {
        config = config || {}

        // 获取头信息
        let realReq = setRequest(ctx, url, config);

        // 扩展请求头信息
        let headersObj = Object.assign({}, realReq.headers, config.headers)

        // 获取请求数据配置
        let requestData = parseData(ctx, config);

        // 请求request的最终配置
        let requestOpt = Object.assign({}, options, {
          uri: realReq.uri,
          method: realReq.method,
          headers: headersObj,
          timeout: undefined,
          gzip: false,
          encoding: null
        }, requestData, config.conf);

        // 发送请求前的钩子，可以对requestjs的参数自定义任何操作
        config.onBeforeRequest && config.onBeforeRequest.call(ctx, proxyName, requestOpt)

        return request(ctx, {
          needPipeRes: true
        }, requestOpt);
      }
962732
function startAllConnections() {
  try {
    myUtils.validateConfig();
  }
  catch(e) {
    console.error(e.message);
    process.exit(2);
  }

  // redefine keys method before connections are started
  if (config.get('redis.useScan')) {
    console.log('Using scan instead of keys');
    Object.defineProperty(Redis.prototype, 'keys', {
      value: function(pattern, cb) {
        let keys = [];
        let that = this;
        let scanCB = function(err, res) {
          if (err) {
            if (typeof cb === 'function') cb(err);
            else {
              console.log('ERROR in redefined "keys" function to use "scan" instead without callback: ' + JSON.stringify(err));
            }
          }
          else {
            let count = res[0], curKeys = res[1];
            console.log("scanning: " + count + ": " + curKeys.length);
            keys = keys.concat(curKeys);
            if (Number(count) === 0) {
              if (typeof cb === 'function') cb(null, keys);
              else {
                console.log('ERROR in redefined "keys" function to use "scan" instead - no callback given!');
              }
            }
            else {
              that.scan(count, 'MATCH', pattern, 'COUNT', config.get('redis.scanCount'), scanCB);
            }
          }
        };
        return this.scan(0, 'MATCH', pattern, 'COUNT', config.get('redis.scanCount'), scanCB);
      }
    });
  }

  // first default connections from config object
  // second connection from cli params (redis-host, redis-port, ...)
  startDefaultConnections(config.connections, function (err) {
    if (err) {
      console.log(err);
      process.exit();
    }
    let db = parseInt(args['redis-db']);
    if (isNaN(db)) {
        db = 0;
    }

    let client;
    if (args['sentinel-host'] || args['sentinels'] || args['redis-host'] || args['redis-port'] || args['redis-socket'] || args['redis-password']) {
      let newDefault = {
        "label": config.get('redis.defaultLabel'),
        "dbIndex": db,
        "password": args['redis-password'] || '',
        "connectionName": config.get('redis.connectionName')
      };

      if (args['redis-socket']) {
        newDefault.path = args['redis-socket'];
      }
      else {
        newDefault.host = args['redis-host'] || "localhost";
        newDefault.port = args['redis-port'] || "6379";
        newDefault.sentinel_name = args['sentinel-name'];
        if (args['sentinels']) {
          newDefault.sentinels = myUtils.parseRedisSentinel('--sentinels', args['sentinels']);
        }
        else if (args['sentinel-host']) {
          newDefault.sentinels = myUtils.parseRedisSentinel( '--sentinel-host or --sentinel-port',
            args['sentinel-host'] + ':' + args['sentinel-port']);
        }
      }

      if (args['redis-tls']) {
        newDefault.tls = {};
      }

      if (!myUtils.containsConnection(config.connections, newDefault)) {
        client = myUtils.createRedisClient(newDefault);
        redisConnections.push(client);
        config.connections.push(newDefault);
        if (!config.get('noSave')) {
          myUtils.saveConnections(config,function (err) {
            if (err) {
              console.log("Problem saving connection config.");
              console.error(err);
            }
          });
        }
        setUpConnection(client, db);
      }
    } else if (config.connections.length === 0) {
      // fallback to localhost if nothing else configured
      client = myUtils.createRedisClient({label: config.get('redis.defaultLabel')});
      redisConnections.push(client);
      setUpConnection(client, db);
    }

    return startWebApp();
  });

  // wait a bit before starting browser to let http server start
  if (args['open']) {
    setTimeout(function() {
      let address = '127.0.0.1';
      if (config.get('server.address') !== '0.0.0.0' && config.get('server.address') !== '::') {
        address = config.get('server.address');
      }
      require('opener')('http://' + address + ':' + config.get('server.port'));
    }, 1000);
  }
}
317259
function RedisStore(args) {
    args = args || {};
    var id = args.id;
    var self = {},
        host = args.host || getProp("CACHE_REDIS_HOST"),
        port = args.port || getProp("CACHE_REDIS_PORT");
    var ttl = args.ttl;
    self.name = 'redis';
    self.client = require('redis').createClient(port, host, args);
    self.id = id;

    var redisOptions = {
        redis_host: host,
        redis_port: port
    };

    var pool = new RedisPool(redisOptions),
        getKey = function (key) {
            return id + "__" + key;
        };

    function connect(cb) {
        pool.acquire(function (err, conn) {
            if (err) {
                pool.release(conn);
                return cb(err);
            }

            if (args.db || args.db === 0) {
                conn.select(args.db);
            }

            cb(null, conn);
        });
    }

    self.get = function (key, cb) {
        connect(function (err, conn) {
            if (err) {
                return cb(err);
            }

            conn.get(getKey(key), function (err, result) {
                pool.release(conn);
                if (err) {
                    return cb(err);
                }
                cb(null, JSON.parse(result));
            });
        });
    };

    self.set = function (key, value, cb) {
        connect(function (err, conn) {
            if (err) {
                return cb(err);
            }

            if (ttl) {
                conn.setex(getKey(key), ttl, JSON.stringify(value), function (err, result) {
                    pool.release(conn);
                    cb(err, result);
                });
            } else {
                conn.set(getKey(key), JSON.stringify(value), function (err, result) {
                    pool.release(conn);
                    cb(err, result);
                });
            }
        });
    };

    self.del = function (key, cb) {
        connect(function (err, conn) {
            if (err) {
                return cb(err);
            }

            conn.del(getKey(key), function (err, result) {
                pool.release(conn);
                cb(err, result);
            });
        });
    };

    self.reset = function (cb) {
        connect(function (err, conn) {
            if (err) {
                return cb(err);
            }

            conn.keys(self.id + "*", function (err, keys) {
                if (err) {
                    return cb(err);
                }
                //delete all keys
                keys.push(function (err, result) {
                    pool.release(conn);
                    cb(err, result);
                });
                conn.del.apply(conn, keys)
            });
        });
    };

    self.keys = function (cb) {
        connect(function (err, conn) {
            if (err) {
                return cb(err);
            }

            conn.keys(self.id + "*", function (err, keys) {
                if (err) {
                    return cb(err);
                }
                pool.release(conn);
                cb(err, keys);
            });
        });
    };

    return self;
}
1351953
function(key, dest, containerName) {

      // Attempt to connect to redis
      return getRedisClient()

      // Run the redis query and then quit
      .then(function(redis) {
        log.debug(format('Setting DNS. %s => %s', key, dest));
        return Promise.fromNode(function(cb) {
          redis.multi()
          .del(key)
          .rpush(key, containerName)
          .rpush(key, dest)
          .exec(cb);
        })
        .then(function() {
          redis.quit();
        });
      });

    }