/** * Store multiple items in the cache for a given number of minutes. * * @param array $values * @param int $minutes * @return void */ public function putMany(array $values, $minutes) { $prefixedValues = []; foreach ($values as $key => $value) { $prefixedValues[$this->prefix . $key] = $value; } $this->memcached->setMulti($prefixedValues, $minutes * 60); }
public function setMulti(array $items, $ttl = null) { $ttl = $ttl ?: 0; if ($ttl > 0) { $ttl = time() + $ttl; } return $this->memcached->setMulti($items, $ttl); }
/** * @inheritdoc */ public function setMulti($values, $expire = 0, array $tags = []) { foreach ($values as $key => $value) { $key = $this->prepareKey($key); $this->setTags($key, $tags, $value); $values[$key] = $this->serialize($value); } $this->storage->setMulti($values, $expire); }
/** * @param array $data * @param int $seconds * @param bool $strict * @throws CacheSetException */ public function setMulti($data, $seconds, $strict = true) { $set = $this->memcached->setMulti($data, $seconds); if (!$set && $strict) { throw new CacheSetException('multi'); } }
/** * Set multiple values to cache at once. * * By sending an array of $items to this function, all values are saved at once to * memcached, reducing the need for multiple requests to memcached. The $items array * keys and values are what are stored to memcached. The keys in the $items array * are merged with the $groups array/string value via buildKeys to determine the * final key for the object. * * @link http://www.php.net/manual/en/memcached.setmulti.php * * @param array $items An array of key/value pairs to store on the server. * @param string|array $groups Group(s) to merge with key(s) in $items. * @param int $expiration The expiration time, defaults to 0. * @param string $server_key The key identifying the server to store the value on. * @param bool $byKey True to store in internal cache by key; false to not store by key * @return bool Returns TRUE on success or FALSE on failure. */ public function setMulti($items, $groups = 'default', $expiration = 0, $server_key = '', $byKey = false) { // Build final keys and replace $items keys with the new keys $derived_keys = $this->buildKeys(array_keys($items), $groups); $expiration = $this->sanitize_expiration($expiration); $derived_items = array_combine($derived_keys, $items); $group_offset = empty($this->cache_key_salt) ? 1 : 2; // Do not add to memcached if in no_mc_groups foreach ($derived_items as $derived_key => $value) { // Get the individual item's group $key_pieces = explode(':', $derived_key); // If group is a non-Memcached group, save to runtime cache, not Memcached if (in_array($key_pieces[$group_offset], $this->no_mc_groups)) { $this->add_to_internal_cache($derived_key, $value); unset($derived_items[$derived_key]); } } // Save to memcached if (false !== $byKey) { $result = $this->mc->setMultiByKey($server_key, $derived_items, $expiration); } else { $result = $this->mc->setMulti($derived_items, $expiration); } // Store in runtime cache if add was successful if (Memcached::RES_SUCCESS === $this->getResultCode()) { $this->cache = array_merge($this->cache, $derived_items); } return $result; }
/** * {@inheritdoc} */ public function deleteMulti(array $keys) { if (!method_exists($this->client, 'deleteMulti')) { /* * HHVM doesn't support deleteMulti, so I'll hack around it by * setting all items expired. * I could also delete() all items, but that would probably take * more network requests (this version always takes 2) * * @see http://docs.hhvm.com/manual/en/memcached.deletemulti.php */ $values = $this->getMulti($keys); $this->client->setMulti(array_fill_keys(array_keys($values), ''), time() - 1); $return = array(); foreach ($keys as $key) { $return[$key] = array_key_exists($key, $values); } return $return; } $result = (array) $this->client->deleteMulti($keys); /* * Contrary to docs (http://php.net/manual/en/memcached.deletemulti.php) * deleteMulti returns an array of [key => true] (for successfully * deleted values) and [key => error code] (for failures) * Pretty good because I want an array of true/false, so I'll just have * to replace the error codes by falses. */ foreach ($result as $key => $status) { $result[$key] = $status === true; } return $result; }
/** * Store multiple items. * * Options: * - namespace <string> optional * - The namespace to use (Default: namespace of object) * - tags <array> optional * - An array of tags * * @param array $keyValuePairs * @param array $options * @return boolean * @throws Exception * * @triggers setItems.pre(PreEvent) * @triggers setItems.post(PostEvent) * @triggers setItems.exception(ExceptionEvent) */ public function setItems(array $keyValuePairs, array $options = array()) { $baseOptions = $this->getOptions(); if (!$baseOptions->getWritable()) { return false; } $this->normalizeOptions($options); $args = new ArrayObject(array('keyValuePairs' => &$keyValuePairs, 'options' => &$options)); try { $eventRs = $this->triggerPre(__FUNCTION__, $args); if ($eventRs->stopped()) { return $eventRs->last(); } $internalKeyValuePairs = array(); $prefix = $options['namespace'] . $baseOptions->getNamespaceSeparator(); foreach ($keyValuePairs as $key => &$value) { $internalKey = $prefix . $key; $internalKeyValuePairs[$internalKey] =& $value; } $errKeys = $this->memcached->setMulti($internalKeyValuePairs, $options['ttl']); if ($errKeys == false) { throw new Exception\RuntimeException("Memcached::setMulti(<array>, {$options['ttl']}) failed"); } $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } }
/** * Internal method to store multiple items. * * @param array $normalizedKeyValuePairs * @return array Array of not stored keys * @throws Exception\ExceptionInterface */ protected function internalSetItems(array &$normalizedKeyValuePairs) { $expiration = $this->expirationTime(); if (!$this->memcached->setMulti($normalizedKeyValuePairs, $expiration)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } return array(); }
/** * Internal method to store multiple items. * * Options: * - ttl <float> * - The time-to-life * - namespace <string> * - The namespace to use * * @param array $normalizedKeyValuePairs * @param array $normalizedOptions * @return boolean * @throws Exception\ExceptionInterface */ protected function internalSetItems(array &$normalizedKeyValuePairs, array &$normalizedOptions) { $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $normalizedOptions['namespace']); $expiration = $this->expirationTime($normalizedOptions['ttl']); if (!$this->memcached->setMulti($normalizedKeyValuePairs, $expiration)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } return true; }
/** * * @param array $items * @param integer $time * @return boolean */ public function setMulti(array $items, $time = 0) { // $_test = ($this->_baseKey !== false and is_array($items)); // if ($_test) { // $this->_translateKeys($items); // } $_ret = $this->_memcached->setMulti($items, $time); return $_ret; }
/** * @param array $vos * @return boolean */ protected function _saveMulti(array $vos = array()) { if (!$this->memcached) { return true; } $toSave = array(); foreach ($vos as $vo) { $toSave[$this->getMemcachedCompleteKey($vo->getId())] = $vo; } return $this->memcached->setMulti($toSave); }
/** * Sets many items in the cache in a single transaction. * * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two * keys, 'key' and 'value'. * @return int The number of items successfully set. It is up to the developer to check this matches the number of items * sent ... if they care that is. */ public function set_many(array $keyvaluearray) { $pairs = array(); foreach ($keyvaluearray as $pair) { $pairs[$pair['key']] = $pair['value']; } if ($this->connection->setMulti($pairs, $this->definition->get_ttl())) { return count($keyvaluearray); } return 0; }
/** * Write many cache entries to the cache at once * * @param array $data An array of data to be stored in the cache * @return array of bools for each key provided, true if the data was * successfully cached, false on failure */ public function writeMany($data) { $cacheData = []; foreach ($data as $key => $value) { $cacheData[$this->_key($key)] = $value; } $success = $this->_Memcached->setMulti($cacheData); $return = []; foreach (array_keys($data) as $key) { $return[$key] = $success; } return $return; }
/** * 批量设置键值 * @param array $sets 键值数组 * @return boolean 是否成功 */ public function mSet($sets) { try { foreach ($sets as &$value) { $value = self::setValue($value); } return $this->handler->setMulti($sets); } catch (Exception $ex) { self::exception($ex); //连接状态置为false $this->isConnected = false; } return false; }
protected function storeValuesImpl(array $values, $expirationTime) { $errorCacheEntryNames = NULL; $adjustedExpirationTime = $expirationTime; if (!isset($adjustedExpirationTime)) { $adjustedExpirationTime = 0; } $storableValues = $deletableCacheEntryNames = NULL; foreach ($values as $cacheEntryName => $value) { if (isset($value)) { $storableValues[$cacheEntryName] = $value; } else { $deletableCacheEntryNames[] = $cacheEntryName; } } if (isset($deletableCacheEntryNames)) { foreach ($deletableCacheEntryNames as $deletableCacheEntryName) { $result = $this->memcached->delete($deletableCacheEntryName); if (($result === FALSE) && ($this->memcached->getResultCode() != Memcached::RES_NOTFOUND)) { $errorCacheEntryNames[] = $deletableCacheEntryName; LogHelper::log_error(t( '[@cacheType] Internal error during value deletion: @message', array('@cacheType' => self::CACHE__TYPE, '@message' => $this->memcached->getResultMessage()))); } } } if (isset($storableValues)) { $result = $this->memcached->setMulti($storableValues, $adjustedExpirationTime); if ($result === FALSE) { LogHelper::log_error(t( '[@cacheType] Internal error during value storing: @message', array('@cacheType' => self::CACHE__TYPE, '@message' => $this->memcached->getResultMessage()))); ArrayHelper::appendValue($errorCacheEntryNames, array_keys($storableValues)); } } return $errorCacheEntryNames; }
/** * Sets many items in the cache in a single transaction. * * @param array $keyvaluearray An array of key value pairs. Each item in the array will be an associative array with two * keys, 'key' and 'value'. * @return int The number of items successfully set. It is up to the developer to check this matches the number of items * sent ... if they care that is. */ public function set_many(array $keyvaluearray) { $pairs = array(); foreach ($keyvaluearray as $pair) { $pairs[$pair['key']] = $pair['value']; } $status = true; if ($this->clustered) { foreach ($this->setconnections as $connection) { $status = $connection->setMulti($pairs, $this->definition->get_ttl()) && $status; } } else { $status = $this->connection->setMulti($pairs, $this->definition->get_ttl()); } if ($status) { return count($keyvaluearray); } return 0; }
/** * Write data to cache * * @param array $keys array of key/value data to store * @param int $expire expiration time * @return boolean true on success */ protected function write(array $keys, $expire = null) { if ($this->memcacheType == GitPHP_CacheResource_Memcache::Memcache) { foreach ($keys as $key => $value) { $this->memcacheObj->set(sha1($key), $value, 0, $expire); } return true; } else { if ($this->memcacheType == GitPHP_CacheResource_Memcache::Memcached) { $mapped = array(); foreach ($keys as $key => $value) { $mapped[sha1($key)] = $value; } $this->memcacheObj->setMulti($mapped, $expire); return true; } } return false; }
/** * Store multiple items. * * Options: * - ttl <float> optional * - The time-to-live (Default: ttl of object) * - namespace <string> optional * - The namespace to use (Default: namespace of object) * * @param array $keyValuePairs * @param array $options * @return boolean * @throws Exception * * @triggers setItems.pre(PreEvent) * @triggers setItems.post(PostEvent) * @triggers setItems.exception(ExceptionEvent) */ public function setItems(array $keyValuePairs, array $options = array()) { $baseOptions = $this->getOptions(); if (!$baseOptions->getWritable()) { return false; } $this->normalizeOptions($options); $args = new ArrayObject(array('keyValuePairs' => &$keyValuePairs, 'options' => &$options)); try { $eventRs = $this->triggerPre(__FUNCTION__, $args); if ($eventRs->stopped()) { return $eventRs->last(); } $this->memcached->setOption(MemcachedResource::OPT_PREFIX_KEY, $options['namespace']); $expiration = $this->expirationTime($options['ttl']); if (!$this->memcached->setMulti($keyValuePairs, $expiration)) { throw $this->getExceptionByResultCode($this->memcached->getResultCode()); } $result = true; return $this->triggerPost(__FUNCTION__, $args, $result); } catch (\Exception $e) { return $this->triggerException(__FUNCTION__, $args, $e); } }
$current .= "\nRealBlockTarget:" . $dataForApp[5]; $current .= "\nSeedHash:" . $dataForApp[7]; $current .= "\nBlock Number:" . $dataForApp[6] . ' / ' . hexdec($dataForApp[6]); $current .= "\n=========================================================================="; $current .= "\nNonceFound:" . $jsonparm[0]; $current .= "\nPowHash:" . $jsonparm[1]; $current .= "\nMixDigest:" . $jsonparm[2]; $current .= "\n=========================================================================="; $current .= "\n=========================================================================="; $shareKey = 'share_ok'; $shareData = $m->get($shareKey); if ($shareData > $shareCounter) { //$m->set($shareKey,0,360); //$m->set('share_fail',0,360); $items = array('share_ok' => 0, 'share_fail' => 0); $m->setMulti($items, time() + 360); } else { $shareData = $shareData + 1; $m->set($shareKey, $shareData, 360); } $existQuery = "SELECT address FROM shares WHERE nonceFound='{$jsonparm['0']}'"; $existResult = mysqli_query($mysqli, $existQuery) or die("Database Error"); $existRow = mysqli_fetch_array($existResult); $addrchecker = $existRow[0]; if (!$addrchecker) { $timeNow = time(); $tas22k = 'INSERT INTO shares (blockid, address, minertarget, minerdiff, blockdiff, blockPowHash, realBlockTarget, nonceFound, FoundPowHash, Digest, seedhash, time) VALUES ("' . $dataForApp[6] . '", "' . $dataForApp[0] . '", "' . $dataForApp[1] . '", "' . $dataForApp[2] . '", "' . $dataForApp[3] . '", "' . $dataForApp[4] . '", "' . $dataForApp[5] . '", "' . $jsonparm[0] . '", "' . $jsonparm[1] . '", "' . $jsonparm[2] . '", "' . $dataForApp[7] . '", "' . $timeNow . '")'; $query = mysqli_query($mysqli, $tas22k) or die("Database Error"); } else { die('Dead'); }
<?php $m = new Memcached(); $m->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT); $m->addServer('10.237.36.113', 11211); $m->addServer('10.237.36.115', 11211); $m->addServer('10.237.36.129', 11211); var_dump($m->set('foo2', 1)); var_dump($m->get('foo2')); var_dump($m->set('boo3', 1)); var_dump($m->get('boo3')); var_dump($m->set('1oo5', 1)); var_dump($m->get('1oo5')); $keys = array('key1' => 'value1', 'key2' => 'value2', 'key3' => 'value3', 'sdasf' => 'value1', 'ksddy2' => 'value2', 'k999ey3' => 'value3'); var_dump($m->setMulti($keys)); var_dump($m->getMulti(array_keys($keys)));
function has_all_keys($keys, $array, $check_true = false) { foreach ($keys as $key) { if (!isset($array[$key])) { return false; } if ($check_true && $array[$key] !== true) { return false; } } return true; } $data = array('foo' => 'foo-data', 'bar' => 'bar-data', 'baz' => 'baz-data', 'lol' => 'lol-data', 'kek' => 'kek-data'); $keys = array_keys($data); $null = null; $m->setMulti($data, 3600); /* Check that all keys were stored */ var_dump(has_all_keys($keys, $m->getMulti($keys))); /* Check that all keys get deleted */ $deleted = $m->deleteMulti($keys); var_dump(has_all_keys($keys, $deleted, true)); /* Try to get the deleted keys, should give empty array */ var_dump($m->getMulti($keys)); /* ---- same tests for byKey variants ---- */ $m->setMultiByKey("hi", $data, 3600); var_dump(has_all_keys($keys, $m->getMultiByKey('hi', $keys))); /* Check that all keys get deleted */ $deleted = $m->deleteMultiByKey('hi', $keys); var_dump(has_all_keys($keys, $deleted, true)); /* Try to get the deleted keys, should give empty array */ var_dump($m->getMultiByKey('hi', $keys));
public function testSetMultiFails() { $request = new MemcacheSetRequest(); $item = $request->addItem(); $item->setKey("widgets_float"); $item->setValue("2"); $item->setFlags(6); // float $item->setSetPolicy(SetPolicy::SET); $item->setExpirationTime(30); $item = $request->addItem(); $item->setKey("widgets_str"); $item->setValue("str_value"); $item->setFlags(0); // string $item->setSetPolicy(SetPolicy::SET); $item->setExpirationTime(30); $response = new MemcacheSetResponse(); $response->addSetStatus(SetStatusCode::STORED); $response->addSetStatus(SetStatusCode::NOT_STORED); $this->apiProxyMock->expectCall('memcache', 'Set', $request, $response); $memcached = new Memcached(); $memcached->setOption(Memcached::OPT_PREFIX_KEY, "widgets_"); $items = ["float" => 2.0, "str" => "str_value"]; $this->assertFalse($memcached->setMulti($items, 30)); $this->assertEquals($memcached->getResultCode(), Memcached::RES_NOTSTORED); $this->apiProxyMock->verify(); }
/** * multi set method * @param array $dataArray * @return bool */ public function batchSet($dataArray) { return $this->m->setMulti($dataArray, 3600 * 24); }
/** * 存储指定数据序列(如存在则覆盖) * * @param array $items * @param int $expiration * @return bool */ public function setMulti($items, $expiration = 0) { return $this->memcached ? $this->memcached->setMulti($items, $expiration) : false; }
$m = new Memcached(); $m->addServer('localhost', '11211'); class Foo { function __toString() { return 'a-foo'; } } $data = array(); for ($i = 0; $i < 1000; $i++) { $data['key' . $i] = 'value' . $i; } $data['a-foo'] = 'a-last'; var_dump($m->setMulti($data)); $keys = array_keys($data); $keys['last'] = new Foo(); $v = $m->getMulti($keys); var_dump(is_array($v)); var_dump($m->getResultCode() == Memcached::RES_SUCCESS); if (is_array($v)) { foreach ($v as $key => $value) { if (!isset($data[$key]) or $value !== $data[$key]) { echo "mismatch \$data['{$key}'] = \n"; var_dump($data[$key]); var_dump($value); } } } else { echo "Result not an array\n";
/** * Set multiple values in the cache. * * @param array $dictionary An array of keys and values to set * @param int|null $expires Optional expiry time in seconds from now */ public function mset(array $dictionary = array(), $expires = 0) { return $this->client->setMulti($dictionary, $expires); }
<?php // ini_set('memcache.chunk_size',1024*20); // set data size 20k $mem = new Memcached(); $mem->addServers([['127.0.0.1', '11211']]); // the server was down , the cache also down // $mem->setOption(Memcached::OPT_DISTRIBUTION, Memcached::DISTRIBUTION_CONSISTENT); // $mem->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, TRUE); $mem->setMulti(array('key1' => 'value1', 'key2' => 'value2')); //delete time must be 0 // $mem->deleteMulti(['key1','key2'],1); sleep(2); print_r($mem->getMulti(['key1', 'key2'])); // sleep(3); // echo $mem->get('key2'); // echo $mem->getResultMessage(); // print_r($mem->getServerList()); // print_r($mem->getStats());
/** * Store multiple items * Memcached::setMulti() is similar to Memcached::set(), but instead of a single key/value item, it works on multiple items specified in items. The expiration time applies to all the items at once. * */ public function setMulti(array $items, $expiration = null) { $lifetime = $this->getLifetime($expiration); return parent::setMulti($items, $lifetime); }
/** * Пропихивает группу данных в мемкеш. * * @param string $datas массив с данным * @param int $data время жизни данных * @param string|array $tags Строка с именем тега или массив, если нужно добавить несколько тегов * * @return bool true - если все ок */ public function sets($datas, $expire = 600, $tags = '') { $output = false; if ($this->bIsConnected) { foreach ($datas as $key => $data) { $key = $key . $this->server; $this->_initSetData($data, $expire, $tags); $datas[$key] = $data; } $output = parent::setMulti($datas, $expire > 0 ? $expire + 900 : 0); } if ($output === false) { $this->_error('set', $key); } return $output; }
/** * @param mixed[] $items */ public function multiSet(array $items) { $this->client->setMulti($items); }