Mecached.class.php 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace Common\Cache;
  3. use Memcached;
  4. /**
  5. * 加载redis
  6. * @539 2016-4-6
  7. */
  8. class Mecached {
  9. protected $mcache;
  10. public static $_MCaches = array();
  11. public function __construct() {
  12. if (!extension_loaded('memcached')) {
  13. throw_exception(L('_NOT_SUPPERT_') . ':memcached');
  14. }
  15. $this->initCache(MC_HOST);
  16. }
  17. public function initCache($cache_server_name){
  18. if(isset(self::$_MCaches[$cache_server_name])){
  19. $this->mcache = self::$_MCaches[$cache_server_name];
  20. }else{
  21. self::$_MCaches[$cache_server_name] = new Memcached; //声明一个新的memcached链接
  22. self::$_MCaches[$cache_server_name]->setOption(Memcached::OPT_COMPRESSION, false); //关闭压缩功能
  23. self::$_MCaches[$cache_server_name]->setOption(Memcached::OPT_BINARY_PROTOCOL, true); //使用binary二进制协议
  24. self::$_MCaches[$cache_server_name]->addServer($cache_server_name, MC_PORT);
  25. $this->mcache = self::$_MCaches[$cache_server_name];
  26. }
  27. }
  28. public function get($key) { //获取MC值
  29. if (empty($key)) {
  30. return false;
  31. }
  32. $res = $this->mcache->get($key);
  33. return $res;
  34. }
  35. /**
  36. * @param type $key key值
  37. * @param type $val 存入的值
  38. * @param type $expire 过期时间,默认null秒 //设置为0表明此数据永不过期(但是它可能由于服务端为了给其他新的元素分配空间而被删除)
  39. * @return boolean
  40. */
  41. public function set($key, $val, $expire = null) {
  42. if (empty($key)) {
  43. return false;
  44. }
  45. $res = $this->mcache->set($key, $val, $expire);
  46. return $res;
  47. }
  48. public function saveOne($key, $update_val, $expire = null) {
  49. $val = $this->mcache->get($key);
  50. if (is_array($val)) {
  51. $update_val = array_merge($val, $update_val);
  52. }
  53. $res = $this->mcache->set($key, $update_val, $expire);
  54. return $res;
  55. }
  56. public function delete($key) { //根据key清除缓存
  57. if (empty($key)) {
  58. return false;
  59. }
  60. $res = $this->mcache->delete($key);
  61. return $res;
  62. }
  63. public function getMulti() {
  64. }
  65. public function setMulti() {
  66. }
  67. public function delMulti() {
  68. }
  69. //自增
  70. public function increment($key,$val){
  71. $res = $this->mcache->increment($key, $val);
  72. return $res;
  73. }
  74. public function clearAll() { //清除所有缓存
  75. $res = $this->mcache->flush();
  76. return $res;
  77. }
  78. }