memcache

最後更新: 2019-09-09

介紹

memcache 是一個 distributed memory object caching system

in-memory key-value store for small chunks of arbitrary data (strings, objects)

memcache 與 memcached

pecl/memcache

  • First Release Date: 2004-06-08
  • External Dependency: None

pecl/memcached

  • First Release Date: 2009-01-29 (beta)
  • External Dependency: libmemcached

安全問題:

clients may freely connect to any server ==> deployments of Memcached exist within trusted networks

(memcached is built for speed, not for security)

目錄

  • Wiki 上的 Example
  • Debian 安裝
  • 設定檔
  • Telnet it
  • + / - 數
  • Flush Contents
  • PHP Session 存放在 memcached
  • memcached-tool
  • Durpal6 與 memcache
  • PHP Code Connect  Memcache
  • memcached

 


Wiki 上的 Example

 

get_foo 與 update_foo

 
// 沒有 memcache 的
 function get_foo(int userid) {
    data = db_select("SELECT * FROM users WHERE userid = ?", userid);
    return data;
 }
 
// 有 memcache 的
 function get_foo(int userid) {
    /* first try the cache */
    data = memcached_fetch("userrow:" + userid);
    if (!data) {
       /* not found : request database */
       data = db_select("SELECT * FROM users WHERE userid = ?", userid);
       /* then store in cache until next get */
       memcached_add("userrow:" + userid, data);
    }
    return data;
 }

 function update_foo(int userid, string dbUpdateString) {
   /* first update database */
    result = db_execute(dbUpdateString);
    if (result) {
       /* database update successful : fetch data to be stored in cache */
       data = db_select("SELECT * FROM users WHERE userid = ?", userid);
       /* the previous line could also look like data = createDataFromDBString(dbUpdateString); */
       /* then store in cache until next get */
       memcached_set("userrow:" + userid, data);
    }
 }

 


Debian 安裝

 

apt-get install memcached php5-memcache

Centos Package:

  • memcached
  • php-pecl-memcached

Files:

/etc/init.d/memcached

/usr/bin/memcached

/usr/bin/memcached-tool

/etc/sysconfig/memcached

PORT="11211"
USER="memcached"

# simultaneous connections, Default: 1024
MAXCONN="1024"

# Unit: MB, Default: 64
CACHESIZE="64"

OPTIONS=""

Proccess

memcached -d -p 11211 -u memcached -m 64 -c 1024 -P /var/run/memcached/memcached.pid -l 0.0.0.0 -U 11211 -t 2

  • -l <ip_addr>          # default to INADDR_ANY
  • -U <num>             # Listen on UDP port <num>, the default is port 11211, 0 is off.
  • -t <threads>         # The default is 4

 


設定檔

 

/etc/memcached.conf

# Run memcached as a daemon.
-d

# Be verbose
# -v

# memory
-m 64

# network
-l 127.0.0.1
-p 11211
# UDP port, 0 is off
# -U <num>

# simultaneous incoming connections
-c 1024

# Run the daemon as "nobody"
-u nobody

# -I <size>
# default size of each slab page 1 Mb

# Try to use large memory pages (if available)
-L

 


Test it telnet

 

Usage

telnet localhost 11211

version

VERSION 1.4.5

stats

STAT pid 10234
STAT uptime 1047218
STAT time 1575357582
STAT version 1.5.20
STAT libevent 2.0.21-stable
STAT pointer_size 64
STAT rusage_user 1186.735778
STAT rusage_system 1341.286057
STAT max_connections 1024
STAT curr_connections 73
STAT total_connections 4324
STAT rejected_connections 0
...

add <key> <flags> <exptime> <bytes>

add mykey 0 900 4

1234             # input 4 byte value, 按 'ENTER' 後 Save
STORED

flag

  • flag 是一個16位的無符號整數
  • 屬於自定義標記
  • 在緩存條目被 set 或者 get 的時一起返回

get <key>

get mykey

VALUE mykey 0 4
1234
END

set <key> <flags> <exptime> <bytes>

 * SET is there to update the value, regardless of whether it already exists.

set mykey 0 900 4

test
STORED

delete key

delete mykey

DELETED

dump

stats slabs

# 沒有 data 時

STAT active_slabs 0
STAT total_malloced 0
END

# 當有 data 時

STAT 11:chunk_size 872
STAT 11:chunks_per_page 1202
STAT 11:total_pages 1
STAT 11:total_chunks 1202
STAT 11:used_chunks 1
STAT 11:free_chunks 1
STAT 11:free_chunks_end 1200
STAT 11:mem_requested 769
STAT 11:get_hits 4
STAT 11:cmd_set 3
STAT 11:delete_hits 0
STAT 11:incr_hits 0
STAT 11:decr_hits 0
STAT 11:cas_hits 0
STAT 11:cas_badval 0
STAT active_slabs 4
STAT total_malloced 4193280

一共有 "4" 個 slab, 而 "11" 是其中一個 slab 的 ID

stats cachedump slab_id limit_num_of_key

# first digit is the numeric ID for the slab and the second digit is how many items you want to retrieve.

# limit_num_of_key=0 means all items

stats cachedump 1 10

ITEM mytest1 [4 b; 1383214507 s]
ITEM mytest2 [1 b; 1383214507 s]
END

stats items

#       slab id
#          |
#         \/
STAT items:1:number 2
STAT items:1:age 1772
STAT items:1:evicted 0
STAT items:1:evicted_nonzero 0
STAT items:1:evicted_time 0
STAT items:1:outofmemory 0
STAT items:1:tailrepairs 0
STAT items:1:reclaimed 0
END

flags: 32-bit unsigned integer that the server store with the data

exptime: seconds, 0 = 不過期

 


+ / - 數

 

# 把 mykey + 3

incr mykey 3

當 mykey 不是數字時

CLIENT_ERROR cannot increment or decrement non-numeric value

# 把 mykey - 3

decr mykey 3

 


Flush Contents

 

# It does not free up or flush memory at all, it just causes all items to expire.

flush_all [sec]

OK

 


PHP Session 存放在 memcached

 

Default 的 php 存放方式及地方如下

session.save_handler = files
session.save_path = "/var/lib/php/session"

session.use_cookies = 1
# only use cookies to store the session id on the client side
session.use_only_cookies = 1
session.name = PHPSESSID

session.auto_start = 0
session.cookie_lifetime = 0

改用 memcache (沒有 "d" 的那個 memcache)

memcache.ini

memcache.default_port=11211
session.save_handler=memcache
session.save_path="tcp://localhost:11211?persistent=1&weight=1&timeout=1&retry_interval=15"

P.S.

在 Centos 6 上用 httpd 行 php 會有另外的 Session 的 "Local Value" 及 "Master Value"

/etc/httpd/conf.d/php.conf

php_value session.save_handler "files"
php_value session.save_path    "/var/lib/php/session"

 


memcached-tool

 

Usage: memcached-tool <host[:port]> [mode]

       memcached-tool 127.0.0.1 [display]    # shows slabs (default)

  #  Item_Size  Max_age   Pages   Count   Full?  Evicted Evict_Time OOM
  2     104B     58991s       1       1      no        0        0    0
  4     176B     58991s       1       1      no        0        0    0

       memcached-tool 127.0.0.1 stats       # shows general stats

#127.0.0.1:11211   Field       Value
         accepting_conns           1
               auth_cmds           0
             auth_errors           0
                   bytes         694
              bytes_read       17657
           bytes_written       18230
              cas_badval           0
                cas_hits           0
              cas_misses           0
               cmd_flush           0
                 cmd_get         109
                 cmd_set         193
             conn_yields           0
   connection_structures          20
        curr_connections          18
              curr_items           6
               decr_hits           0
             decr_misses           0
             delete_hits           0
           delete_misses           0
               evictions           0
                get_hits         102
              get_misses           7
               incr_hits          38
             incr_misses          27
          limit_maxbytes    67108864
     listen_disabled_num           0
                     pid       23536
            pointer_size          32
           rusage_system    3.145521
             rusage_user    0.625904
                 threads           4
                    time  1435203879
       total_connections          71
             total_items         155
                  uptime       60670
                 version       1.4.4

       memcached-tool 127.0.0.1 dump       # dumps keys and values

Dumping memcache contents
  Number of buckets: 0
  Number of items  :

 


Durpal6 與 memcache

 

php module:

php5-memcache(memcache.ini)

This extension allows you to work with memcached through handy OO and
procedural interfaces in your php5 applications.
Homepage: http://pecl.php.net/package/memcache

php5-memcached(memcached.ini)   <-- 不是必要的

This extension uses libmemcached library to provide
API for communicating with memcached servers.
Homepage: http://pecl.php.net/package/memcached

php 設定:

# default: standard (PECL extension version >= 2.2.0)
# enable consistent hashing which allows servers to be added or removed
# from the pool without causing keys to be remapped

memcache.hash_strategy="consistent"

修改 php:

settings.php

    $conf = array(
      'cache_inc' => './modules/memcache/memcache.inc',
    );

    web/modules/memcache   

Panel Setting:

設定: Show memcache statistics at the bottom of each page

# Memcache statistics

https://datahunter.org/admin/reports/memcache

# Memcache

https://datahunter.org/admin/settings/memcache

 


PHP Code Connect  Memcache

 

bool Memcache::close ( void )

# This function doesn't close persistent connections,
# which are closed only during web-server shutdown/restart.

bool Memcache::connect ( string $host [, int $port [, int $timeout ]] )

# The connection, which was opened using Memcache::connect() will be automatically closed at the end of script execution.

string Memcache::get ( string $key [, int &$flags ] )

# returns previously stored data if an item with such key exists

<?php
    /* OO API */
    $memcache_obj = new Memcache;
    $memcache_obj->connect('memcache_host', 11211);
    /*
    $var = $memcache_obj->get('some_key');
    print $var;
    */
    $memcache_obj->close();
?>

 

 



Centos 7 - memcached with php7

 

 * memcached is faster than memcache

# 安裝

yum install memcached

# 設定

# /etc/sysconfig/memcached

TCP

PORT="11211"
USER="memcached"

# max simultaneous connections; the default is 1024
MAXCONN="1024"

# the default is 64 megabytes
CACHESIZE="64"

OPTIONS="-l 127.0.0.1"

UNIX Socket

#PORT="11211"
OPTIONS="-a 666 -s /tmp/memcached.sock"

# Other Useful Setting

-L                # Try to use large memory pages (if available).

-b <num>    # Set the backlog queue limit to <num> connections. The default is 1024.

# Enable service

systemctl start memcached

systemctl enable memcached

# Checking

netstat -ntlp | grep memcached

tcp        0      0 127.0.0.1:11211         0.0.0.0:*               LISTEN      31179/memcached

telnet 127.0.0.1 11211

stats items

# php 7 support memcache

yum list | grep php7 | grep devel

php70u-devel.x86_64                     7.0.9-1.ius.el7                ius
php70u-pecl-apcu-devel.x86_64           5.1.5-2.ius.el7                ius

yum install php70u-devel

yum groupinstall "Development Tools"

yum install zlib-devel memcached-devel libmemcached-devel

yum install git

# Get source

git clone https://github.com/php-memcached-dev/php-memcached

cd php-memcached

git checkout php7

phpize

./configure

make

make install

# Enable memcached module

echo "extension=memcached.so" > /etc/php.d/memcached.ini

# Checking

php -m | grep memcached

 


Connect with socket

 

nc 或 socat

  • nc -U /var/run/socket
  • socat - UNIX-CONNECT:/tmp/memcached.sock

 

 

Creative Commons license icon Creative Commons license icon