Cách cài đặt Memcached trên CentOS

Memcached là hệ thống phân phối và lưu trữ bộ nhớ đệm (cache) giúp tăng tốc website rất hiệu quả do cơ chế lưu trữ đơn giản (key – value) và được lưu trữ hoàn toàn trên RAM của server nên có độ trễ thấp nhất so với lưu trữ bằng file trên ổ cứng. Do đó, xTraffic.pep.vn sẽ hướng dẫn bạn cách cài đặt và sử dụng Memcached với PHP-FPM trên CentOS.

Cách cài đặt Memcached trên CentOS - CentOS Memcached PHP - Webmasters Tools Phát triển website
Memcached Logo

Điều kiện cần có để thực hiện cài đặt Memcached :

  • Bạn cần phải có VPS/Server có 512 RAM trở lên. Do dữ liệu được lưu trữ trên RAM nên bạn cần phải có VPS có RAM tương đối. Nếu bạn đang xài Shared Hosting thì nhà cung cấp đã cài đặt sẵn và bạn chỉ cần kích hoạt trên cPanel, nhưng đa số sẽ giới hạn rất thấp (từ 32MB trở xưống).
  • Bạn cần có quyền quản trị root của VPS/Server để thực hiện các lệnh cài đặt
  • Do CentOS là hệ điều hành phổ biến và ổn định cho Web Server nên xTraffic.pep.vn sẽ hướng dẫn bạn cách cài đặt trên phiên bản CentOS 6 (64bit)
  • Cài đặt REMI Repository theo hướng dẫn này
  • Bạn cần cài đặt LEMP Stack được hướng dẫn trong bài viết này

Thực hiện cài đặt Memcached Server trên CentOS

Memcached Server là một dịch vụ giống như Nginx và PHP-FPM, đây là phần mềm dùng để quản lý và lưu trữ dữ liệu cache từ phía client (client ở đây không phải là trình duyệt của người dùng, mà là phần mở rộng của PHP extension sẽ được hướng dẫn bên dưới).

Để cài đặt Memcached Server trên CentOS 6 64bit bạn thực hiện lệnh sau :

sudo yum install -y memcached

Sau khi cài đặt Memcached Server, bạn có thể quản lý dịch vụ Memcached bằng các lệnh sau :

service memcached start #Khởi động Memcached Server
service memcached stop #Dừng Memcached Server
service memcached restart #Khởi động lại Memcached Server

Bạn cần thực hiện lệnh sau để Memcached Server tự khởi động mỗi khi reboot

sudo chkconfig memcached on

File cấu hình của memcahed được đặt tại “/etc/sysconfig/memcached

PORT="11211" #port chạy memcached
USER="memcached" #user mà memcached sử dụng trên Linux
MAXCONN="1024" #Số kết nối đồng thời tối đa
CACHESIZE="128" #Dung lượng sử dụng lưu trữ dữ liệu của Memcached. Tính bằng Megabytes (MB)
OPTIONS="-l 192.168.1.12 -L" #Các tuỳ chọn khác khi Memcached khởi động, bạn có thể tham khảo thông tin bên dưới

Các tuỳ chọn của Memcached Server

OPTIONS
	These programs follow the usual GNU command line syntax. A summary of options is included below.

	-s <file>
		Unix socket path to listen on (disables network support).

	-a <perms>
		Permissions (in octal format) for Unix socket created with -s option.

	-l <ip_addr>
		Listen on <ip_addr>; default to INADDR_ANY. This is an important option to consider as there is no other way to secure the  installation.
		Binding to an internal or firewalled network interface is suggested.

	-d
		Run memcached as a daemon.

	-u <username>
		Assume the identity of <username> (only when run as root).

	-m <num>
		Use <num> MB memory max to use for object storage; the default is 64 megabytes.

	-c <num>
		Use <num> max simultaneous connections; the default is 1024.

	-R <num>
		This  option  seeks  to prevent client starvation by setting a limit to the number of sequential requests the server will process from an
		individual client connection. Once a connection has exceeded this value, the server will attempt to  process  I/O  on  other  connections
		before handling any further request from this connection. The default value for this option is 20.
		
	-k
		Lock down all paged memory. This is a somewhat dangerous option with large caches, so consult the README and memcached homepage for configuration suggestions.
	
	-p <num>
		Listen on TCP port <num>, the default is port 11211.
	
	-U <num>
		Listen on UDP port <num>, the default is port 11211, 0 is off.
	
	-M
		Disable automatic removal of items from the cache when out of memory. Additions will not be possible until adequate space is freed up.
	-r
		Raise the core file size limit to the maximum allowable.
	
	-f <factor>
		Use <factor> as the multiplier for computing the sizes of memory chunks that items are stored in. A lower value may result in less wasted memory depending on the total amount of memory available and the distribution of item sizes. The default is 1.25.
	
	-n <size>
		Allocate a minimum of <size> bytes for the item key, value, and flags. The default is 48. If you have a lot of small keys and values, you can get a significant memory efficiency gain with a lower value. If you use a high chunk growth factor (-f option), on the other hand, you may want to increase the size to allow a bigger percentage of your items to fit in the most densely packed (smallest) chunks.
	
	-C
		Disable the use of CAS (and reduce the per-item size by 8 bytes).
	
	-h
		Show the version of memcached and a summary of options.
	
	-v
		Be verbose during the event loop; print out errors and warnings.
	
	-vv
		Be even more verbose; same as -v but also print client commands and responses.
	
	-i
		Print memcached and libevent licenses.
	
	-P <filename>
		Print pidfile to <filename>, only used under -d option.
	
	-t <threads>
		Number of threads to use to process incoming requests. This option is only meaningful if memcached was compiled with thread support enabled. It is typically not useful to set this higher than the number of CPU cores on the memcached server. The default is 4.
	
	-D <char>
		Use <char> as the delimiter between key prefixes and IDs. This is used for per-prefix stats reporting. The default is ":" (colon). If this option is specified, stats collection is turned on automatically; if not, then it may be turned on by sending the "stats detail on" command to the server.
	
	-L
		Try to use large memory pages (if available). Increasing the memory page size could reduce the number of TLB misses and improve the performance. In order to get large pages from the OS, memcached will allocate the total item-cache in one large chunk. Only available if supported on your OS.
	
	-B <proto>
		Specify the binding protocol to use. By default, the server will autonegotiate client connections. By using this option, you can specify the protocol clients must speak. Possible options are "auto" (the default, autonegotiation behavior), "ascii" and "binary".
	
	-I <size>
		Override the default size of each slab page. Default is 1mb. Default is 1m, minimum is 1k, max is 128m. Adjusting this value changes the item size limit. Beware that this also increases the number of slabs (use -v to view), and the overal memory usage of memcached.

Để đảm bảo an toàn, bạn cần giới hạn một số địa chỉ IP mới có quyền truy cập vào Memcached Server, bạn mở file “/etc/sysconfig/iptables” và thêm vào dòng lệnh sau để giới hạn chỉ cho “192.168.1.10” truy cập vào port 11211 của Memcached

-A INPUT -m state --state NEW -s 192.168.1.10 -m tcp -p tcp --dport 11211 -j ACCEPT
-A INPUT -m state --state NEW -s 192.168.1.10 -m udp -p udp --dport 11211 -j ACCEPT

Lưu lại và khởi động lại iptables :

service iptables restart

Đối với các website có lượng truy cập cao thì bạn cần tăng giới hạn cho system file descriptor và tăng phạm vi của port của Server. Bạn mở file “/etc/sysctl.conf” tìm và chỉnh sửa các dòng sau (hoặc thêm vào nếu chưa có) :

# Increase system file descriptor limit to
fs.file-max = 50000
# Increase system IP port limits
net.ipv4.ip_local_port_range = 2000 65000

Lưu lại và nạp các thay đổi bằng lệnh sau :

sysctl -p

Cài đặt Memcached Extension PHP (php-pecl-memcached)

Bên trên là cách chúng ta cài đặt Memcached Server, nhưng để có thể làm việc được với Memcached Server với PHP thì bạn cần cài thêm Memcached Extension cho PHP (Memcached Client). Các bạn thực hiện các lệnh sau để cài đặt Memcached Extension cho PHP :

yum install -y libmemcached-devel php-pecl-memcached

Thông thường thì file cấu hình của Memcached Extension cho PHP sẽ nằm tại folder “/etc/php.d/“, các bạn tìm file có tên là “*memcached.ini” để cấu hình theo ý muốn của mình.

Chi tiết về các hàm và cách sử dụng Memcached Extension cho PHP (Memcached Client) tại đây

Leave a Comment