| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108 |
- <?php
- namespace Heanup\Library;
- use Exception;
- use Heanup\Config\Memcached\Core;
- class Memcached
- {
- private $memcache;
- private $type;
- private static $instance;
- /**
- * Memcache constructor.
- * @throws Exception
- */
- public function __construct()
- {
- $config = Core::getData(null);
- $host = $config[0]['host'];
- $port = $config[0]['port'];
- $this->type = $config[0]['type'] ?: 'memcached';
- try {
- $this->memcache = new \Memcached;
- $this->memcache->setOption(\Memcached::OPT_COMPRESSION, true);
- $this->memcache->setOption(\Memcached::OPT_DISTRIBUTION, true);
- $this->memcache->setOption(\Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
- $this->memcache->setOption(\Memcached::OPT_NO_BLOCK, true);
- $this->memcache->setOption(\Memcached::OPT_CONNECT_TIMEOUT, 50);
- $this->memcache->setOption(\Memcached::OPT_POLL_TIMEOUT, 50);
- $this->memcache->addServer($host, $port);
- } catch (Exception $ex) {
- $message = "Memcached connection failed : [" . $this->type . ';' . $host . ';' . $port . ']' . $ex->getMessage();
- throw new Exception($message, 90301);
- }
- }
- public static function instance()
- {
- if (!isset(self::$instance)) {
- try {
- $instance = new self();
- } catch (Exception $e) {
- }
- self::$instance = $instance;
- } else {
- $instance = self::$instance;
- }
- return $instance;
- }
- public function __destruct()
- {
- if ($this->type != 'memcached') {
- $this->memcache->close();
- }
- }
- public function get($key)
- {
- if (empty($key)) {
- return '';
- } else {
- return $this->memcache->get($key);
- }
- }
- public function delete($key, $time = 0)
- {
- return $this->memcache->delete($key, $time);
- }
- public function set($key, $data, $life_time_limit = 0, $memcache_compressed = 2)
- {
- if ($this->type == 'memcached') {
- return $this->memcache->set($key, $data, $life_time_limit);
- } else {
- return $this->memcache->set($key, $data, $memcache_compressed, $life_time_limit);
- }
- }
- public function replace($key, $data, $memcache_compressed = 2, $life_time_limit = 0)
- {
- if ($this->type == 'memcached') {
- return $this->memcache->replace($key, $data, $life_time_limit);
- } else {
- return $this->memcache->replace($key, $data, $memcache_compressed, $life_time_limit);
- }
- }
- public function increment($key, $value = 1)
- {
- return $this->memcache->increment($key, $value);
- }
- public function decrement($key, $value = 1)
- {
- return $this->memcache->decrement($key, $value);
- }
- public function flush()
- {
- return $this->memcache->flush();
- }
- }
|