/** * 保存记录至redis * @access private * @param string $value 保存值 * @return boolean 成功返回true,失败返回false */ private function save_item_in_redis($value = '') { require './include/Predis/Autoloader.php'; Predis\Autoloader::register(); try { $r = new Predis\Client(); $r->connect('127.0.0.1', 6379); $my_log_len = $r->llen($this->config->item('encryption_key')); if ($my_log_len < 21) { $r->rpush($this->config->item('encryption_key'), $value); } else { $r->lpop($this->config->item('encryption_key')); $r->rpush($this->config->item('encryption_key'), $value); } return TRUE; } catch (Exception $e) { echo $e->getMessage(); return FALSE; } }
/** * @fn function init(&$rooter, &$objet) * @brief * @file controller.php * * @param rooter * @param objet * @return */ public function init(&$rooter, &$objet) { include_once dirname(__FILE__) . '/library/redis/Autoloader.php'; Predis\Autoloader::register(); require_once "./" . PATH_LIB . "twig/lib/Twig/Autoloader.php"; Twig_Autoloader::register(); $dont = array("rooter" => 0, "error" => 0); include_once "model.php"; $this->root = $rooter; $this->class['root'] = $rooter; $array = glob("./" . PATH_LIB . "*.php"); foreach ($array as $value) { $temp = str_replace(".php", "", str_replace("./" . PATH_LIB, "", $value)); if (array_key_exists($temp, $dont) === FALSE) { $this->loadLibrary($temp); } } $this->class['redis'] = new Predis\Client("tcp://127.0.0.1:6379"); $this->init_variables(); $this->model = $this->loadModel($this->models, $this->module); foreach ($this->class as $obj) { if (method_exists($obj, "loadLib")) { $obj->loadLib($this->class); } } $this->start($objet); }
function getDataJson() { if (isset($_GET['sfrom'])) { $jordanGUID = $_GET['jordanGUID']; $domain = $_GET['domain']; $protocol = $_GET['protocol']; $path = $_GET['path']; $location = $protocol . $domain . $path; $sfrom = $_GET['sfrom']; initConnection($db_config); //redis 使用 require '../Predis/Autoloader.php'; Predis\Autoloader::register(); $redis = new Predis\Client(array('database' => '0', 'host' => '49.4.129.122', 'port' => 6379)); $datestr = date("Y_m_d_H"); $tableName = "request_" . $datestr; if ($redis->get("tableName") != $tableName) { create_request($tableName); $redis->set("tableName", $tableName); } $request_datetime = date('Y-m-d H:i:s', time()); writeLog('../logs/' . $tableName . '.log', "{$jordanGUID}\t{$domain}\t{$location}\t{$request_datetime}\n", "a"); insert_request_entry($jordanGUID, $domain, $location, $sfrom, $request_datetime, $tableName); insert_request_entry($jordanGUID, $domain, $location, $sfrom, $request_datetime, "request"); //echo "success"; } else { //echo "failure"; } }
public static function predis($dbname, $host) { if (!is_null(self::$redisConection)) { return; } Predis\Autoloader::register(); self::$redisConection = new Predis\Client(array('host' => $host, 'database' => $dbname)); }
public function prepare_items() { if (!class_exists('Predis\\Client')) { require_once dirname(__FILE__) . '/predis.php'; Predis\Autoloader::register(); } $this->items = $this->get_servers(); $this->_column_headers = array($this->get_columns(), $this->get_hidden_columns(), array()); }
function checkdriver() { // Check memcache $this->required_extension("predis-1.0/autoload.php"); try { Predis\Autoloader::register(); } catch (Exception $e) { } return true; }
public function __construct($params = array('ip' => '127.0.0.1', 'port' => 6379)) { require_once './include/Predis/Autoloader.php'; Predis\Autoloader::register(); try { $this->ins = new Predis\Client(); $this->ins->connect($params['ip'], $params['port']); } catch (Exception $e) { exit($e->getMessage()); } }
public function __construct() { $this->db = new database(); // Initializing Redis try { Predis\Autoloader::register(); $this->redis = new Predis\Client(array("scheme" => $this->getRedisScheme(), "host" => $this->getRedisHost(), "port" => $this->getRedisPort())); } catch (Exception $e) { die($e->getMessage()); } }
function checkdriver() { // Check memcache if (!class_exists("\\Predis\\Client")) { $this->required_extension("predis-1.0/autoload.php"); try { Predis\Autoloader::register(); } catch (Exception $e) { } } return true; }
public function __construct() { global $configs, $logger; try { $logger->debug("Creating REDIS cache object"); Predis\Autoloader::register(); $this->redis = new Predis\Client($configs['redis']['client']); } catch (Exception $e) { $logger->warn("Redis cache object could not be created"); $this->redis = null; } }
/** * 获取动态出入金、转账记录 * @return mixed 成功返回对应记录,失败返回false */ private function get_my_log() { require_once './include/Predis/Autoloader.php'; Predis\Autoloader::register(); try { $r = new Predis\Client(); $r->connect('127.0.0.1', 6379); $my_log_len = $r->llen($this->config->item('encryption_key')); return $my_log_len == 0 ? false : $r->lrange($this->config->item('encryption_key'), 0, $my_log_len - 1); } catch (Exception $e) { return false; } }
public function __construct() { parent::__construct(); require APPPATH . 'libraries/vendor/autoload.php'; Predis\Autoloader::register(); try { $this->redis = new Predis\Client(); $this->is_redis_as_runnig = true; } catch (Exception $e) { $this->is_redis_as_runnig = false; log_message('error', ' REDIS: ' . $e->getMessage()); } //echo class_exists('ResqueScheduler'); }
function &redis() { if (!defined('PREDIS_LOADED')) { require dirname(__DIR__) . '/vendor/Predis/Autoloader.php'; Predis\Autoloader::register(); define('PREDIS_LOADED', 1); } try { $redis = new Predis\Client('tcp://127.0.0.1:6379'); return $redis; } catch (Exception $e) { die('AeriaCacheRedis Error: ' . $e->getMessage()); } }
protected function _actionRefresh(KCommandContext $context) { require JPATH_ROOT . '/vendor/autoload.php'; Predis\Autoloader::register(); $this->redis = new Predis\Client(array('scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379)); $this->redis->flushall(); $rows = $this->getModel()->limit(1000)->getList(); $filter = $this->getService('koowa:filter.slug'); foreach ($rows as $row) { $this->redis->set('event:' . $row->id, serialize($row->toArray())); $this->redis->rpush('events', $row->id); $this->redis->sadd('ctas_involvement:' . $filter->sanitize($row->ctas_involvement), $row->id); $row->save(); } }
protected final function __construct() { global $glob; require CC_INCLUDES_DIR . "/lib/predis/autoload.php"; Predis\Autoloader::register(); try { if (isset($glob['redis_parameters']) && isset($glob['redis_options'])) { $this->redis_client = new Predis\Client($glob['redis_parameters'], $glob['redis_options']); } elseif (isset($glob['redis_parameters'])) { $this->redis_client = new Predis\Client($glob['redis_parameters']); } else { $this->redis_client = new Predis\Client(); } } catch (Predis\Connection\ConnectionException $e) { trigger_error($e->getMessage()); return; } $this->_mode = 'Redis'; //Run the parent constructor parent::__construct(); }
public function __construct() { parent::__construct(); require APPPATH . 'libraries/vendor/autoload.php'; Predis\Autoloader::register(); try { $this->redis = new Predis\Client(); $this->is_redis_as_runnig = true; } catch (Exception $e) { $this->is_redis_as_runnig = false; log_message('error', ' REDIS: ' . $e->getMessage()); } //Se comento esto porque esta mandando error // Se debe revisar /*if(Auth::has_permission('listar-actividades__ver_todas', 'actividades/listar-actividades')){ $this->subordinados = array("id_usuario"=>null); } else{*/ $this->subordinados = @CRM_Controller::seleccionar_subordinados(); //}*/ }
/** * Instantiate the Redis class. * * Instantiates the Redis class. * * @param null $persistent_id To create an instance that persists between requests, use persistent_id to specify a unique ID for the instance. */ public function __construct() { global $blog_id, $table_prefix; $redis = array('scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379); if (defined('WP_REDIS_SCHEME')) { $redis['scheme'] = WP_REDIS_SCHEME; } if (defined('WP_REDIS_HOST')) { $redis['host'] = WP_REDIS_HOST; } if (defined('WP_REDIS_PORT')) { $redis['port'] = WP_REDIS_PORT; } if (defined('WP_REDIS_PATH')) { $redis['path'] = WP_REDIS_PATH; } if (defined('WP_REDIS_PASSWORD')) { $redis['password'] = WP_REDIS_PASSWORD; } if (defined('WP_REDIS_DATABASE')) { $redis['database'] = WP_REDIS_DATABASE; } $redis_client = defined('WP_REDIS_CLIENT') ? WP_REDIS_CLIENT : null; if (class_exists('Redis') && strcasecmp('predis', $redis_client) !== 0) { $redis_client = defined('HHVM_VERSION') ? 'hhvm' : 'pecl'; } else { $redis_client = 'predis'; } try { if (strcasecmp('hhvm', $redis_client) === 0) { $this->redis_client = sprintf('HHVM %s Extension', HHVM_VERSION); $this->redis = new Redis(); // Adjust host and port, if the scheme is `unix` if (strcasecmp('unix', $redis['scheme']) === 0) { $redis['host'] = 'unix://' . $redis['path']; $redis['port'] = 0; } $this->redis->connect($redis['host'], $redis['port']); if (isset($redis['password'])) { $this->redis->auth($redis['password']); } if (isset($redis['database'])) { $this->redis->select($redis['database']); } } elseif (strcasecmp('pecl', $redis_client) === 0) { $this->redis_client = 'PCEL Extension'; $this->redis = new Redis(); if (strcasecmp('unix', $redis['scheme']) === 0) { $this->redis->connect($redis['path']); } else { $this->redis->connect($redis['host'], $redis['port']); } if (isset($redis['password'])) { $this->redis->auth($redis['password']); } if (isset($redis['database'])) { $this->redis->select($redis['database']); } } else { $this->redis_client = 'Predis'; // Require PHP 5.4 or greater if (version_compare(PHP_VERSION, '5.4.0', '<')) { throw new Exception(); } // Load bundled Predis library if (!class_exists('Predis\\Client')) { require_once WP_CONTENT_DIR . '/plugins/redis-cache/includes/predis.php'; Predis\Autoloader::register(); } $this->redis = new Predis\Client($redis); $this->redis->connect(); $this->redis_client .= ' v' . Predis\Client::VERSION; } // Throws exception if Redis is unavailable $this->redis->ping(); $this->redis_connected = true; } catch (Exception $exception) { // When Redis is unavailable, fall back to the internal back by forcing all groups to be "no redis" groups $this->no_redis_groups = array_unique(array_merge($this->no_redis_groups, $this->global_groups)); $this->redis_connected = false; } /** * This approach is borrowed from Sivel and Boren. Use the salt for easy cache invalidation and for * multi single WP installs on the same server. */ if (!defined('WP_CACHE_KEY_SALT')) { define('WP_CACHE_KEY_SALT', ''); } // Assign global and blog prefixes for use with keys if (function_exists('is_multisite')) { $this->global_prefix = is_multisite() || defined('CUSTOM_USER_TABLE') && defined('CUSTOM_USER_META_TABLE') ? '' : $table_prefix; $this->blog_prefix = (is_multisite() ? $blog_id : $table_prefix) . ':'; } }
public static function metricsVerb() { # grab the arguments. this function has variable arguments. # the first argument is assumed to be the metrics "verb" being requested. # the remaining argument are assumed to be the arguments to the "verb". require "Predis/Autoloader.php"; Predis\Autoloader::register(); if (func_num_args() == 0) { return -599; # incorrect number of arguements } else { $params = func_get_args(); } $verbName = $params[0]; # ...and hookup with redis try { $redis = new Predis\Client(array("host" => "127.0.0.1", "port" => 6379, "database" => 8)); } catch (Exception $e) { die($e->getMessage()); } # pull in verb information, checking that verb is available and correct in the process $verb = $redis->hgetall($verbName); if (!$verb) { return -500; } # verb not found # pull in the remaining arguments if (func_num_args() != $verb['args']) { return -599; # incorrect number of arguments } # compose the query $query = "{$verbName}_"; for ($i = 1; $i < count($params); $i++) { $query = $query . "{$params[$i]}"; } # Validation test - parameters $verbDate = new Datetime("{$params[1]}-{$params[2]}-01"); # Grab the list of databases needed by this verb and calculate the minimum date range # over which a calculation can be performed. $minDate = new Datetime("1970-1-1"); $maxDate = new Datetime("3000-1-1"); foreach (explode(',', $verb['databases']) as $db) { $dbInfo = $redis->hgetall($db); $dbMin = new Datetime($dbInfo['minDate']); $dbMax = new Datetime($dbInfo['maxDate']); if ($dbMin > $minDate) { $minDate = $dbMin; } if ($dbMax < $maxDate) { $maxDate = $dbMax; } } if ($verbDate < $minDate or $verbDate > $maxDate) { return -501; } # parameter out of range # Validation test - is there an answer for this query in the cache? # if not, kick off a backend job to calculate one. $result = $redis->hgetall($query); if (!$result) { call_user_func_array("celerySubmit", $params); return -401; # result unavailable, calculating result now, come back later } # Validation test - software version # If the result's software version number does not match the verb's version number, re-compute if ($result['software'] != $verb['version']) { call_user_func_array("celerySubmit", $params); return -402; # result out of date, calculating updated result now, come back later } # Validation test - database version # if any of the results' database version number(s) do not match the database(s)'s version number(s), re-compute foreach (explode(',', $verb['databases']) as $db) { $dbInfo = $redis->hgetall($db); if ($dbInfo['version'] != $result[$db]) { call_user_func_array("celerySubmit", $params); return -402; # result out of date, calculating updated result now, come back later } } # It's all good. Increment the popularity counter and return the cached value. $redis->incr('pop_${query}'); return $result['value']; }
<?php header('Content-Type: text/html; charset=utf-8', true); error_reporting(E_ALL); ?> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css"> <link href='https://fonts.googleapis.com/css?family=Open+Sans:600,400,300&subset=latin,cyrillic' rel='stylesheet' type='text/css'> <link href="../css/bootstrap.min.css" rel="stylesheet"> <link href="../css/jquery-ui.min.css" rel="stylesheet"> <link href="../css/custom.css" rel="stylesheet"> <?php require "predis/autoload.php"; Predis\Autoloader::register(); $redis = new Predis\Client(); /* If uses external server $client = new Predis\Client([ 'scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379, ]); */ // Simplest demo how to use Redis /* $redis->set("hello_world", "Hi from php!"); $value = $redis->get("hello_world"); echo $value; */ // 123 - id of property $redis->hmset("123", array("type" => "нерухомість поза містом", "name" => "Приватний будинок поза містом", "location" => "с. Ульянівка", "description" => "Приватний будинок поза містом. Приватизована земельна ділянка. Світло, вода, газ - присутні. Є місце для будівництва.", "sdelka" => "Продаж", "rooms" => 5, "floors" => 2, "area" => 90, "price" => "12000\$"));
function getRedisDB() { global $redis; if ($redis) { return $redis; } Predis\Autoloader::register(); $redis = new Predis\Client(); return $redis; }
/** * Constructor. * * @param string $subdomain The church subdomain. * */ public function __construct($subdomain) { $this->subdomain = $subdomain; Predis\Autoloader::register(); $this->redis = new Predis\Client(); }
public function __construct($name = 'default', $config = null) { if ($config) { $this->config = $config; } if (!class_exists('Predis\\Client')) { require_once BASE_PATH . '/vendor/predis/predis/src/Autoloader.php'; Predis\Autoloader::register(); } $this->cache = new Predis\Client($this->config); $this->name = $name; }
/** * AJAX Gateway * * This is the long description for a DocBlock. This text may contain * multiple lines and even some _markdown_. * * * Markdown style lists function too * * Just try this out once * * The section after the long description contains the tags; which provide * structured meta-data concerning the given element. * * @since 0.0.1 * @package jCore * */ function ajaxGateway() { /* * Sanitizes res id. * * Removes all characters except letters, digits and $-_.+!*'(),{}|\\^~[]`<>#%";/?:@&= */ $resId = filter_input(INPUT_GET | INPUT_POST, "res", FILTER_SANITIZE_URL); $batchPullRequest = array(); if (isset($_POST['pull'])) { $batchPullRequest = json_decode($_POST['pull']); } //error_log(print_r($batchPullRequest, 1)); $batchResponse = array(); try { require_once JCORE_PROJECT . "libs/php/predis/autoload.php"; Predis\Autoloader::register(); require_once 'db-connect.php'; // $redis = new Predis\Client(); $redis = new Predis\Client(array("scheme" => DB_SCHEME, "host" => DB_HOST, "port" => DB_PORT, "password" => DB_PASSWORD)); // $redis->set('/hello-world', 'Hello, jCore!'); // "Successfully connected to Redis"; // Since we connect to default setting localhost and 6379 port there is no need for extra configuration. // If not then you can specify the scheme, host and port to connect as an array to the constructor. // require_once "sha256.inc.php"; foreach ($batchPullRequest as $uri => $pullRequest) { $resource = array(); // Look up uri in redis. $resourcePrefix = '/jc/resources'; $resKey = $resourcePrefix . $uri; if ($redis->exists($resKey)) { $value = $redis->get($resKey); if (isset($pullRequest->value)) { $clientRes = json_encode($pullRequest->value); $serverRes = $value; // Compare resource values. if (strcasecmp($clientRes, $serverRes) != 0) { $resource['value'] = $value; } else { $resource['_'] = JC_NO_ERROR; } } else { if (isset($pullRequest->hash)) { $clientRes = $pullRequest->hash; // Without caching. $hash = hash('sha256', $value); /* // With caching. // Get the server-side hash, generating one if it hasn't been cached. // This only works if the only resource changes are going through the jCore gateway. // Otherwise, we have to assume that resources might have been changed since // last we checked. $hashPrefix = '/jc/hashes'; $hashKey = $hashPrefix.$uri; $hash = ''; if ($redis->exists($hashKey)) { // Server-side hash exists. $hash = $redis->get($hashKey); } else { // Server-side hash doesn't exist and needs to be generated. $hash = hash('sha256', $value); $redis->set($hashKey, $hash); } */ $serverRes = $hash; // Compare resource values. if (strcasecmp($clientRes, $serverRes) != 0) { $resource['value'] = $value; } else { $resource['_'] = JC_NO_ERROR; } } else { // No value or hash means this is an improperly formed request. $resource['_'] = JC_INVALID_REQUEST; } } } else { // Specified uri does not exist. $resource['_'] = HTTP_NOT_FOUND; } $batchResponse[$uri] = $resource; } } catch (Exception $e) { // echo "Couldn't connect to Redis"; $batchResponse['_'] = JC_DB_CONNECT_ERROR . ' Could not connect to database'; $batchResponse['desc'] = $e->getMessage(); } //error_log(print_r($batchResponse, 1)); // This should be the only thing we echo on this page. echo json_encode($batchResponse); exit(0); }
/** * Instantiate the Redis class. * * @param bool $fail_gracefully */ public function __construct($fail_gracefully = true) { global $blog_id, $table_prefix; $parameters = array('scheme' => 'tcp', 'host' => '127.0.0.1', 'port' => 6379); foreach (array('scheme', 'host', 'port', 'path', 'password', 'database') as $setting) { $constant = sprintf('WP_REDIS_%s', strtoupper($setting)); if (defined($constant)) { $parameters[$setting] = constant($constant); } } if (defined('WP_REDIS_GLOBAL_GROUPS') && is_array(WP_REDIS_GLOBAL_GROUPS)) { $this->global_groups = WP_REDIS_GLOBAL_GROUPS; } if (defined('WP_REDIS_IGNORED_GROUPS') && is_array(WP_REDIS_IGNORED_GROUPS)) { $this->ignored_groups = WP_REDIS_IGNORED_GROUPS; } $client = defined('WP_REDIS_CLIENT') ? WP_REDIS_CLIENT : null; if (class_exists('Redis') && strcasecmp('predis', $client) !== 0) { $client = defined('HHVM_VERSION') ? 'hhvm' : 'pecl'; } else { $client = 'predis'; } try { if (strcasecmp('hhvm', $client) === 0) { $this->redis_client = sprintf('HHVM Extension (v%s)', HHVM_VERSION); $this->redis = new Redis(); // Adjust host and port, if the scheme is `unix` if (strcasecmp('unix', $parameters['scheme']) === 0) { $parameters['host'] = 'unix://' . $parameters['path']; $parameters['port'] = 0; } $this->redis->connect($parameters['host'], $parameters['port']); } if (strcasecmp('pecl', $client) === 0) { $this->redis_client = sprintf('PECL Extension (v%s)', phpversion('redis')); $this->redis = new Redis(); if (strcasecmp('unix', $parameters['scheme']) === 0) { $this->redis->connect($parameters['path']); } else { $this->redis->connect($parameters['host'], $parameters['port']); } } if (strcasecmp('pecl', $client) === 0 || strcasecmp('hhvm', $client) === 0) { if (isset($parameters['password'])) { $this->redis->auth($parameters['password']); } if (isset($parameters['database'])) { $this->redis->select($parameters['database']); } } if (strcasecmp('predis', $client) === 0) { $this->redis_client = 'Predis'; // Require PHP 5.4 or greater if (version_compare(PHP_VERSION, '5.4.0', '<')) { throw new Exception(); } // Load bundled Predis library if (!class_exists('Predis\\Client')) { $plugin_dir = defined('WP_PLUGIN_DIR') ? WP_PLUGIN_DIR : WP_CONTENT_DIR . '/plugins'; require_once $plugin_dir . '/redis-cache/includes/predis.php'; Predis\Autoloader::register(); } $options = array(); if (defined('WP_REDIS_CLUSTER')) { $parameters = WP_REDIS_CLUSTER; $options['cluster'] = 'redis'; } if (defined('WP_REDIS_SERVERS')) { $parameters = WP_REDIS_SERVERS; $options['replication'] = true; } if ((defined('WP_REDIS_SERVERS') || defined('WP_REDIS_CLUSTER')) && defined('WP_REDIS_PASSWORD')) { $options['parameters']['password'] = WP_REDIS_PASSWORD; } $this->redis = new Predis\Client($parameters, $options); $this->redis->connect(); $this->redis_client .= sprintf(' (v%s)', Predis\Client::VERSION); } // Throws exception if Redis is unavailable $this->redis->ping(); $this->redis_connected = true; } catch (Exception $exception) { // When Redis is unavailable, fall back to the internal back by forcing all groups to be "no redis" groups $this->ignored_groups = array_unique(array_merge($this->ignored_groups, $this->global_groups)); $this->redis_connected = false; if (!$fail_gracefully) { throw $exception; } } // Assign global and blog prefixes for use with keys if (function_exists('is_multisite')) { $this->global_prefix = is_multisite() || defined('CUSTOM_USER_TABLE') && defined('CUSTOM_USER_META_TABLE') ? '' : $table_prefix; $this->blog_prefix = is_multisite() ? $blog_id : $table_prefix; } }
function __construct() { require 'predis/Autoloader.php'; Predis\Autoloader::register(); }
public function get_ohlc($pair, $start, $end, $bid_offer, $timeslice, $lag = 0) { //to seconds factor lookup $this->to_seconds_factor['s'] = 1; $this->to_seconds_factor['m'] = 60; $this->to_seconds_factor['h'] = 60 * 60; $this->to_seconds_factor['d'] = 60 * 60 * 24; //predis class require 'Predis/lib/Predis/Autoloader.php'; Predis\Autoloader::register(); // set some utility variables $range = $end - $start; $startTime = gmstrftime('%Y-%m-%d %H:%M:%S', $start / 1000); $endTime = gmstrftime('%Y-%m-%d %H:%M:%S', $end / 1000); //set suggested timeslice depending on range //[1s,5s,10s,20s,30s,1m,5m,10m,20m,30m,1h,2h,3h,6h,1d,1w,1M] if (!isset($timeslice)) { $stick_threshold = 300; //on screen count threshold //seconds if ($range < $stick_threshold * 1000) { $timeslice = '1s'; } elseif ($range < $stick_threshold * 5 * 1000) { $timeslice = '5s'; } elseif ($range < $stick_threshold * 10 * 1000) { $timeslice = '10s'; } elseif ($range < $stick_threshold * 20 * 1000) { $timeslice = '20s'; } elseif ($range < $stick_threshold * 30 * 1000) { $timeslice = '30s'; //minutes } elseif ($range < $stick_threshold * 60 * 1000) { $timeslice = '1m'; } elseif ($range < $stick_threshold * 60 * 5 * 1000) { $timeslice = '5m'; } elseif ($range < $stick_threshold * 60 * 10 * 1000) { $timeslice = '10m'; } elseif ($range < $stick_threshold * 60 * 20 * 1000) { $timeslice = '20m'; } elseif ($range < $stick_threshold * 60 * 30 * 1000) { $timeslice = '30m'; //hour } elseif ($range < $stick_threshold * 60 * 60 * 1000) { $timeslice = '1h'; } elseif ($range < $stick_threshold * 60 * 60 * 2 * 1000) { $timeslice = '2h'; } elseif ($range < $stick_threshold * 60 * 60 * 3 * 1000) { $timeslice = '3h'; } elseif ($range < $stick_threshold * 60 * 60 * 6 * 1000) { $timeslice = '6h'; //day } elseif ($range < $stick_threshold * 60 * 60 * 24 * 1000) { $timeslice = '1d'; //week } elseif ($range < $stick_threshold * 60 * 60 * 7 * 1000) { $timeslice = '1w'; //month } else { $timeslice = '1M'; } } //validate and parse timeslice if (!preg_match('/^(?P<dur>\\d+)(?P<len>s|m|h|d|w|M)$/', $timeslice, $matches)) { die("Invalid timeslice parameter: {$timeslice}"); } //timeslice duration (1,2,3,4,..) $ts_duration = $matches['dur']; //timeslice length (s,m,h,d,w,M) $ts_len = $matches['len']; //check durations modulus of parent //60 seconds in a minute and 60 minute in an hour if (in_array($ts_len, array('s', 'm'))) { if (60 % $ts_duration != 0) { //not evenly divisable by 60 die("Invalid 1timeslice parameter: {$ts_duration}{$ts_len}"); } } //24 hours in day if (in_array($ts_len, array('h'))) { if (24 % $ts_duration != 0) { //not evenly divisable by 24 die("Invalid timeslice parameter: {$ts_duration}{$ts_len}"); } } //max 2 day|week|month if (in_array($ts_len, array('d', 'w', 'M'))) { if ($ts_duration > 2) { //not valid duration die("Invalid timeslice parameter: {$ts_duration}{$ts_len}"); } } //check are not cacheing week and month $is_caching = in_array($ts_len, array('w', 'M')) ? false : true; //add lag if ($lag > 0) { if (!in_array($ts_len, array('w', 'M'))) { //to sec $sec = $this->to_seconds_factor[$ts_len] * $ts_duration; //lag start $start = (ceil($start / 1000 / $sec) * $sec - $sec * $lag) * 1000; } else { if ($ts_len == 'w') { $date = date_create_from_format('U', $start); date_sub($date, date_interval_create_from_date_string("{$lag} weeks")); } if ($ts_len == 'M') { $date = date_create_from_format('U', $start); date_sub($date, date_interval_create_from_date_string("{$lag} months")); } //save new start $start = date_format($date, 'U') * 1000; } } //if no week or Month, round start/end time to match candle length if (!in_array($ts_len, array('w', 'M'))) { //to sec $sec = $this->to_seconds_factor[$ts_len] * $ts_duration; //round up start time, round down end time $startTime = date('Y-m-d H:i:s', ceil($start / 1000 / $sec) * $sec); //round down end time $endTime = date('Y-m-d H:i:s', floor($end / 1000 / $sec) * $sec + $sec - 1); } //init vars $time_slices = array(); $result = array(); $ranges = array(); $cache = array(); $time_slices = array(); $empty_time_slices = array(); $is_cache_miss = false; $redis = new Predis\Client(); $redis_zset = "{$pair}:{$bid_offer}:{$timeslice}"; //query redis cache if ($is_caching) { //get list of expected time slices $time_slices = $this->buildTimeSlices($ts_len, $ts_duration, $start / 1000, $end / 1000); //check redis cache $return = $redis->zrangebyscore($redis_zset, $start / 1000, $end / 1000, array('withscores' => true)); //build cache datastructure foreach ($return as $row) { $cache[$row[1]] = $row[0]; } //get empty timeslices $return = $redis->zrangebyscore('empty:' . $redis_zset, $start / 1000, $end / 1000, array('withscores' => true)); //remove empty timeslices from time_slices foreach ($return as $row) { unset($time_slices[$row[1]]); } //find missing slices $cache_miss_slices = array_diff_key($time_slices, $cache); //check for cache misses if (count($cache_miss_slices) > 0) { $is_cache_miss = true; $redis->incr('cache_misses'); //get ranges for missing slices $ranges = $this->buildRangeFromMissingTimeSlices($ts_len, $ts_duration, $cache_miss_slices); } else { $redis->incr('cache_hits'); $results = $cache; } } else { //build full range $ranges[] = array('startTime' => $startTime, 'endTime' => $endTime); } //hit database if we are not caching or if we have a cache miss if (!$is_caching || $is_cache_miss) { //db $return = $this->fetchMySQLAndCache($ts_len, $ts_duration, $is_cache_miss ? $cache_miss_slices : $time_slices, $ranges, $is_caching, $redis, $redis_zset, $pair, $bid_offer); //add missing slices to cache obj if ($is_cache_miss) { foreach ($return as $row) { extract($row); $cache[$datetime] = "[{$datetime},{$open},{$high},{$low},{$close},{$vol}]"; } //sort by key (timestamp) ksort($cache); $results = $cache; } else { //build non cached results results foreach ($return as $row) { extract($row); $results[] = "[{$datetime},{$open},{$high},{$low},{$close},{$vol}]"; } } } return $results; }