1. 首页 > Memcached教程 > 正文

Memcached教程FG002-Memcached安装与生产配置优化实战

本文档风哥主要介绍Memcached数据库安装与生产配置优化相关知识,包括Memcached数据库安装方式、环境要求、核心配置参数、YUM包安装、源码编译安装、生产配置优化、多实例部署、Systemd服务配置等内容,风哥教程参考Memcached官方文档Installation & Deployment、Server Startup & Configuration等内容编写,适合DBA人员和运维人员在学习和测试中使用,如果要应用于生产环境则需要自行确认。

Part01-基础概念与理论知识

1.1 Memcached数据库安装方式概述

Memcached提供了多种安装方式,用户可以根据实际需求选择合适的安装方法。更多视频教程www.fgedu.net.cn

1.1.1 安装方式对比

# Memcached安装方式对比

# 方式1:系统包管理器安装(YUM/APT)
优点:
– 安装简单快捷
– 自动解决依赖
– 方便升级维护
缺点:
– 版本可能较旧
– 定制性较差

# 方式2:源码编译安装
优点:
– 可选择最新版本
– 可自定义编译选项
– 更灵活的配置
缺点:
– 需要手动解决依赖
– 安装过程较复杂
– 升级维护较麻烦

# 方式3:Docker容器安装
优点:
– 环境隔离
– 快速部署
– 便于迁移
缺点:
– 性能有轻微损耗
– 需要Docker环境

1.1.2 推荐安装方式

  • 开发测试环境:推荐使用YUM/APT包管理器安装,快速便捷
  • 生产环境:推荐使用源码编译安装,可获取最新版本和最优性能
  • 容器化环境:推荐使用Docker容器安装,便于管理和扩展

1.2 Memcached数据库安装环境要求

在安装Memcached之前,需要确保系统满足必要的环境要求。学习交流加群风哥微信: itpux-com

1.2.1 软件依赖

# Memcached核心依赖

# libevent(必需)
– 版本要求:2.0.x 或更高版本
– 作用:事件通知库,处理网络连接

# 可选依赖
– libmemcached:客户端库
– SASL:认证支持
– openssl:TLS/SSL支持

# 查看libevent版本
$ rpm -qa | grep libevent
libevent-2.1.12-6.el9.x86_64

# 查看libevent开发包
$ rpm -qa | grep libevent-devel
libevent-devel-2.1.12-6.el9.x86_64

1.2.2 系统资源要求

# Memcached系统资源要求

# 内存要求
– 最小:256MB
– 推荐:4GB以上
– 生产环境:根据缓存数据量规划

# CPU要求
– 最小:1核
– 推荐:2核以上
– 生产环境:4核以上

# 磁盘要求
– 安装空间:50MB
– 日志空间:根据日志量规划
– 持久化:如需持久化,需要额外磁盘空间

# 网络要求
– 带宽:100Mbps以上
– 延迟:局域网<1ms

1.3 Memcached数据库核心配置参数解析

Memcached通过命令行参数进行配置,理解这些参数对于优化性能至关重要。

1.3.1 核心启动参数

# Memcached核心启动参数

# 内存相关参数
-m 最大内存使用量(MB),默认64MB
-M 内存耗尽时返回错误,而不是淘汰数据

# 网络相关参数
-p TCP端口,默认11211
-U UDP端口,默认11211,0表示禁用
-l 监听IP地址,默认所有接口
-s UNIX socket路径(禁用网络)

# 连接相关参数
-c 最大并发连接数,默认1024
-t 工作线程数,默认4

# 存储相关参数
-n key+value+flags最小空间,默认48
-f slab大小增长因子,默认1.25
-I 每个slab页大小,默认1MB

# 运行模式参数
-d 以守护进程模式运行
-u 运行用户
-P PID文件路径

# 日志相关参数
-v 详细输出(打印错误和警告)
-vv 更详细的输出(打印客户端命令)
-vvv 最详细的输出(打印内部状态)

# 其他参数
-h 显示帮助信息
-i 显示memcached和libevent的许可证

1.3.2 高级配置参数

# Memcached高级配置参数

# LRU相关参数
-o lru_crawler 启用LRU爬虫,后台清理过期数据
-o lru_maintainer 启用LRU维护线程
-o hot_lru_pct HOT LRU百分比,默认20
-o warm_lru_pct WARM LRU百分比,默认40

# slab相关参数
-o slab_reassign 启用slab页重新分配
-o slab_automove 启用slab自动移动

# 安全相关参数
-S 启用SASL认证
-o ssl_chain_cert SSL证书链文件
-o ssl_key SSL私钥文件

# 性能相关参数
-R 每个事件最大请求数,默认20
-C 禁用CAS(Compare And Swap)
-b 积压队列长度,默认1024

Part02-生产环境规划与建议

2.1 Memcached数据库安装规划

生产环境的安装规划需要考虑版本选择、目录结构、用户权限等多个方面。学习交流加群风哥QQ113257174

2.1.1 版本选择建议

# Memcached版本选择建议

# 稳定版本(推荐生产环境)
– 1.6.x系列:最新稳定版本
– 1.5.x系列:成熟稳定版本

# 查看可用版本
# 官方下载地址
https://memcached.org/downloads

# 版本选择原则
– 生产环境选择稳定版本
– 新功能测试选择最新版本
– 考虑与客户端库的兼容性

2.1.2 目录结构规划

# Memcached生产环境目录规划

# 安装目录
/memcached/app/bin/memcached # 主程序
/memcached/app/bin/memcached-tool # 管理工具

# 配置目录
/memcached/conf/memcached.conf # 配置文件

# 数据目录
/memcached/fgdata # 数据文件(如需持久化)

# 日志目录
/memcached/logs/memcached.log # 日志文件

# 脚本目录
/memcached/scripts/start.sh # 启动脚本
/memcached/scripts/stop.sh # 停止脚本
/memcached/scripts/status.sh # 状态检查脚本

# PID文件目录
/var/run/memcached/memcached.pid # PID文件

2.1.3 用户权限规划

# Memcached用户权限规划

# 创建专用用户
$ sudo useradd -r -s /sbin/nologin -d /memcached memcached

# 用户属性说明
– -r:创建系统用户
– -s /sbin/nologin:禁止登录
– -d /memcached:指定家目录

# 目录权限设置
$ sudo chown -R memcached:memcached /memcached
$ sudo chmod -R 755 /memcached

# 验证用户
$ id memcached
uid=991(memcached) gid=989(memcached) groups=989(memcached)

2.2 Memcached数据库配置规划

2.2.1 内存配置规划

# Memcached内存配置规划

# 小型应用(单机)
内存总量:16GB
Memcached分配:8GB
配置:-m 8192

# 中型应用(集群)
内存总量:64GB
Memcached分配:48GB
配置:-m 49152

# 大型应用(分布式)
内存总量:128GB
Memcached分配:100GB
配置:-m 102400

# 内存规划原则
– 预留20%给操作系统
– 预留10%给其他进程
– Memcached使用约70%总内存

2.2.2 连接配置规划

# Memcached连接配置规划

# 连接数规划
小型应用:1024连接
中型应用:4096连接
大型应用:8192连接

# 线程数规划
CPU核心数 <= 4:线程数 = CPU核心数 CPU核心数 > 4:线程数 = 4-8

# 示例配置(8核CPU)
-t 8 # 8个工作线程
-c 4096 # 最大4096连接
-b 1024 # 积压队列1024

# 网络参数优化
net.core.somaxconn = 65535
net.ipv4.tcp_max_syn_backlog = 65535

2.3 Memcached数据库安全规划

Memcached默认没有认证机制,生产环境需要做好安全防护。更多学习教程公众号风哥教程itpux_com

2.3.1 网络安全规划

# Memcached网络安全规划

# 绑定内网IP
-l 192.168.1.100

# 禁用UDP(防止反射攻击)
-U 0

# 使用防火墙限制访问
$ sudo firewall-cmd –permanent –add-rich-rule=’rule family=”ipv4″ source address=”192.168.1.0/24″ port protocol=”tcp” port=”11211″ accept’
$ sudo firewall-cmd –reload

# 验证防火墙规则
$ sudo firewall-cmd –list-all
public (active)
target: default
icmp-block-inversion: no
interfaces: eth0
sources:
services: ssh dhcpv6-client
ports:
protocols:
forward: no
masquerade: no
forward-ports:
source-ports:
icmp-blocks:
rich rules:
rule family=”ipv4″ source address=”192.168.1.0/24″ port protocol=”tcp” port=”11211″ accept

2.3.2 认证安全规划

# Memcached认证安全规划

# 启用SASL认证
-S

# 配置SASL用户
$ sudo yum install -y cyrus-sasl-devel cyrus-sasl-plain

# 创建SASL配置文件
$ sudo vi /etc/sasl2/memcached.conf
mech_list: plain
log_level: 5
sasldb_path: /etc/sasl2/memcached-sasldb

# 创建认证用户
$ sudo saslpasswd2 -a memcached -c fgedu
Password:
Again (for verification):

# 验证用户
$ sudo sasldblistusers2 -f /etc/sasl2/memcached-sasldb
fgedu@fgedu.net.cn: userPassword

# 设置权限
$ sudo chown memcached:memcached /etc/sasl2/memcached-sasldb
$ sudo chmod 600 /etc/sasl2/memcached-sasldb

Part03-生产环境项目实施方案

3.1 Memcached数据库YUM包安装实战

3.1.1 安装前准备

# 检查系统版本
$ cat /etc/os-release
NAME=”Oracle Linux Server”
VERSION=”9.3″
ID=”ol”
ID_LIKE=”fedora”
VERSION_ID=”9.3″

# 更新系统包
$ sudo dnf update -y

# 安装EPEL仓库(如需要)
$ sudo dnf install -y epel-release

# 查看可用的Memcached版本
$ dnf info memcached
Available Packages
Name : memcached
Version : 1.6.22
Release : 1.el9
Architecture : x86_64
Size : 124 k
Source : memcached-1.6.22-1.el9.src.rpm
Repository : ol9_appstream
Summary : High Performance, Distributed Memory Object Cache
URL : https://www.memcached.org/
License : BSD
Description : memcached is a high-performance, distributed memory object caching
: system, generic in nature, but intended for use in speeding up dynamic
: web applications by alleviating database load.

3.1.2 执行安装

# 安装Memcached
$ sudo dnf install -y memcached
Dependencies resolved.
================================================================================
Package Architecture Version Repository Size
================================================================================
Installing:
memcached x86_64 1.6.22-1.el9 ol9_appstream 124 k

Transaction Summary
================================================================================
Install 1 Package

Total download size: 124 k
Installed size: 267 k
Downloading Packages:
memcached-1.6.22-1.el9.x86_64.rpm 2.1 MB/s | 124 kB 00:00
——————————————————————————–
Total 2.0 MB/s | 124 kB 00:00
Running transaction check
Transaction check succeeded.
Running transaction test
Transaction test succeeded.
Running transaction
Preparing : 1/1
Running scriptlet: memcached-1.6.22-1.el9.x86_64 1/1
Installing : memcached-1.6.22-1.el9.x86_64 1/1
Running scriptlet: memcached-1.6.22-1.el9.x86_64 1/1
Verifying : memcached-1.6.22-1.el9.x86_64 1/1

Installed:
memcached-1.6.22-1.el9.x86_64

Complete!

# 验证安装
$ memcached -h
memcached 1.6.22
-p TCP port number to listen on (default: 11211)
-U UDP port number to listen on (default: 11211, 0 is off)
-s UNIX socket path to listen on (disables network support)
-a access mask for UNIX socket, in octal (default: 0700)
-l interface to listen on (default: INADDR_ANY, all addresses)
may be specified as host:port. If you don’t specify
a port number, the value you specify will be used for the TCP
port (default: 11211), and for the UDP port (default: 0, off)
-d run as a daemon
-r maximize core file limit
-u assume identity of (only when run as root)
-m max memory to use for items in megabytes (default: 64 MB)
-M return error on memory exhausted (rather than removing items)
-c max simultaneous connections (default: 1024)
-k lock down all paged memory. Note that there is a
limit on how much memory you may lock. Trying to
allocate more than that would fail, so be sure you
set the limit correctly for the user you started
the daemon with (not for -u user;
under sh this is done with ‘ulimit -S -l NUM_KB’).
-v verbose (print errors/warnings while in event loop)
-vv very verbose (also print client commands/reponses)
-vvv extremely verbose (also print internal state transitions)
-h print this help and exit
-i print memcached and libevent license
-V print version and exit
-P save PID in , only used with -d option
-f chunk size growth factor (default: 1.25)
-n minimum space allocated for key+value+flags (default: 48)
-L Try to use large memory pages (if available). Increasing
the page size may reduce the number of TLB misses
and improve performance. In order to get large pages
memcached must allocate the total item-cache in one large
chunk.
-D Use as the delimiter between key prefixes and IDs.
This is used for per-prefix statistics reporting. The default is
(“:”), which provides for backwards compatibility.
-t number of threads to use (default: 4)
-R Maximum number of requests per event, limits the number of
requests processed for a given connection to prevent
starvation (default: 20)
-C Disable use of CAS
-b Set the backlog queue limit (default: 1024)
-B Binding protocol – one of ascii, binary, or auto (default)
-I Override the size of each slab page. Adjusts max item size
(default: 1mb, min: 1k, max: 1024m)
-S Turn on Sasl authentication
-o Comma separated list of extended or experimental options
– (EXPERIMENTAL) maxconns_fast: immediately close new
connections if over maxconns limit
– (EXPERIMENTAL) slab_reassign: Enable slab page reassignment
once memory is fully allocated.
– (EXPERIMENTAL) slab_automove: Enable slab page automove.
The value is optional, and specifies the aggressiveness
(default: 1)
– lru_crawler: Enable LRU Crawler background thread
– lru_maintainer: Enable LRU Crawler background thread
– hot_lru_pct: Pct of slab memory to reserve for hot lru.
(default: 20)
– warm_lru_pct: Pct of slab memory to reserve for warm lru.
(default: 40)
– no_lru_maintainer: Disable LRU maintainer thread
– temporary_ttl: TTL for temporary items (default: 0)
– idle_timeout: Timeout for idle connections (default: 0)
– hash_algorithm: The hash table algorithm
default is jenkins hash. options: jenkins, murmur3
– no_modern: Disables modern features.
– modern: Enables modern features.
– no_lru_crawler: Disable LRU crawler.
– track_sizes: Enable slab size tracking
– no_hashexpand: Disable hash table expansion

# 查看安装位置
$ which memcached
/usr/bin/memcached

# 查看版本
$ memcached -V
memcached 1.6.22

3.1.3 配置文件修改

# 查看默认配置文件
$ cat /etc/sysconfig/memcached
PORT=”11211″
USER=”memcached”
MAXCONN=”1024″
CACHESIZE=”64″
OPTIONS=””

# 修改配置文件
$ sudo vi /etc/sysconfig/memcached
PORT=”11211″
USER=”memcached”
MAXCONN=”4096″
CACHESIZE=”8192″
OPTIONS=”-l 192.168.1.100 -U 0 -v”

# 配置说明
PORT:监听端口
USER:运行用户
MAXCONN:最大连接数
CACHESIZE:内存大小(MB)
OPTIONS:其他选项
-l:绑定IP地址
-U 0:禁用UDP
-v:启用日志

# 验证配置文件
$ cat /etc/sysconfig/memcached
PORT=”11211″
USER=”memcached”
MAXCONN=”4096″
CACHESIZE=”8192″
OPTIONS=”-l 192.168.1.100 -U 0 -v”

3.2 Memcached数据库源码编译安装实战

3.2.1 安装编译依赖

# 安装编译工具
$ sudo dnf groupinstall -y “Development Tools”

# 安装依赖包
$ sudo dnf install -y libevent-devel cyrus-sasl-devel

# 验证libevent安装
$ rpm -qa | grep libevent
libevent-2.1.12-6.el9.x86_64
libevent-devel-2.1.12-6.el9.x86_64

# 验证编译工具
$ gcc –version
gcc (GCC) 11.4.1 20230605 (Red Hat 11.4.1-2.0.1)
Copyright (C) 2021 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

$ make –version
GNU Make 4.3
Built for x86_64-redhat-linux-gnu
Copyright (C) 1988-2020 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.

3.2.2 下载源码包

# 创建下载目录
$ mkdir -p /tmp/memcached && cd /tmp/memcached

# 下载源码包
$ wget https://memcached.org/files/memcached-1.6.22.tar.gz
–2026-04-08 10:00:00– https://memcached.org/files/memcached-1.6.22.tar.gz
Resolving memcached.org (memcached.org)… 107.170.238.202
Connecting to memcached.org (memcached.org)|107.170.238.202|:443… connected.
HTTP request sent, awaiting response… 200 OK
Length: 621897 (607K) [application/octet-stream]
Saving to: ‘memcached-1.6.22.tar.gz’

memcached-1.6.22.tar.gz 100%[====================================================>] 607.32K 1.23MB/s in 0.5s

2026-04-08 10:00:01 (1.23 MB/s) – ‘memcached-1.6.22.tar.gz’ saved [621897/621897]

# 验证下载
$ ls -lh memcached-1.6.22.tar.gz
-rw-r–r–. 1 root root 608K Apr 8 10:00 memcached-1.6.22.tar.gz

# 解压源码包
$ tar -xzf memcached-1.6.22.tar.gz

# 进入源码目录
$ cd memcached-1.6.22

# 查看源码目录
$ ls -la
total 1120
drwxrwxrwx. 2 root root 4096 Apr 8 10:00 .
drwxrwxrwx. 3 root root 25 Apr 8 10:00 ..
-rw-r–r–. 1 root root 18011 Apr 8 10:00 aclocal.m4
drwxrwxrwx. 2 root root 42 Apr 8 10:00 assoc
-rw-r–r–. 1 root root 2856 Apr 8 10:00 AUTHORS
drwxrwxrwx. 2 root root 23 Apr 8 10:00 cache
drwxrwxrwx. 2 root root 23 Apr 8 10:00 crawler
-rwxrwxrwx. 1 root root 46013 Apr 8 10:00 configure
-rw-r–r–. 1 root root 31145 Apr 8 10:00 configure.ac
drwxrwxrwx. 2 root root 23 Apr 8 10:00 daemon
drwxrwxrwx. 2 root root 23 Apr 8 10:00 doc
-rw-r–r–. 1 root root 1736 Apr 8 10:00 items.c
-rw-r–r–. 1 root root 10461 Apr 8 10:00 items.h
-rw-r–r–. 1 root root 8256 Apr 8 10:00 jenkins_hash.c
-rw-r–r–. 1 root root 1917 Apr 8 10: jenkins_hash.h
-rw-r–r–. 1 root root 4364 Apr 8 10:00 logger.c
-rw-r–r–. 1 root root 1313 Apr 8 10:00 logger.h
drwxrwxrwx. 2 root root 23 Apr 8 10:00 m4
-rw-r–r–. 1 root root 3515 Apr 8 10:00 Makefile.am
-rw-r–r–. 1 root root 35789 Apr 8 10:00 Makefile.in
-rw-r–r–. 1 root root 3515 Apr 8 10:00 memcached.c
-rw-r–r–. 1 root root 3515 Apr 8 10:00 memcached.h
-rw-r–r–. 1 root root 7120 Apr 8 10:00 NEWS
-rw-r–r–. 1 root root 1500 Apr 8 10:00 README
-rw-r–r–. 1 root root 1500 Apr 8 10:00 sasl_defs.c
-rw-r–r–. 1 root root 1500 Apr 8 10:00 sasl_defs.h
drwxrwxrwx. 2 root root 23 Apr 8 10:00 scripts
drwxrwxrwx. 2 root root 23 Apr 8 10:00 slabs
drwxrwxrwx. 2 root root 23 Apr 8 10:0 storage
drwxrwxrwx. 2 root root 23 Apr 8 10:00 testapp
drwxrwxrwx. 2 root root 23 Apr 8 10:00 thread
drwxrwxrwx. 2 root root 23 Apr 8 10:00 trace
drwxrwxrwx. 2 root root 23 Apr 8 10:00 util
-rw-r–r–. 1 root root 1500 Apr 8 10:00 version.m4

3.2.3 编译安装

# 配置编译选项
$ ./configure –prefix=/memcached/app \
–enable-sasl \
–enable-sasl-pwdb \
–enable-threads \
–enable-64bit

checking build system type… x86_64-pc-linux-gnu
checking host system type… x86_64-pc-linux-gnu
checking target system type… x86_64-pc-linux-gnu
checking for a BSD-compatible install… /usr/bin/install -c
checking whether build environment is sane… yes
checking for a thread-safe mkdir -p… /usr/bin/mkdir -p
checking for gawk… gawk
checking whether make sets $(MAKE)… yes
checking whether make supports nested variables… yes
checking for gcc… gcc
checking whether the C compiler works… yes
checking for C compiler default output file name… a.out
checking for suffix of executables…
checking whether we are cross compiling… no
checking for suffix of object files… o
checking whether we are using the GNU C compiler… yes
checking whether gcc accepts -g… yes
checking for gcc option to accept ISO C89… none needed
checking whether gcc understands -c and -o together… yes
checking for style of include used by make… GNU
checking dependency style of gcc… gcc3
checking how to run the C preprocessor… gcc -E
checking for grep that handles long lines and -e… /usr/bin/grep
checking for egrep… /usr/bin/grep -E
checking for ANSI C header files… yes
checking for sys/types.h… yes
checking for sys/stat.h… yes
checking for stdlib.h… yes
checking for string.h… yes
checking for memory.h… yes
checking for strings.h… yes
checking for inttypes.h… yes
checking for stdint.h… yes
checking for unistd.h… yes
checking minix/config.h usability… no
checking minix/config.h presence… no
checking for minix/config.h… no
checking whether it is safe to define __EXTENSIONS__… yes
checking for event_init in -levent… yes
checking for library containing socket… none required
checking for library containing gethostbyname… none required
checking for library containing umem_cache_create… no
checking for library containing gethugepagesizes… no
checking for stdbool.h that conforms to C99… yes
checking for _Bool… yes
checking for inline… inline
checking for uint8_t… yes
checking for uint16_t… yes
checking for uint32_t… yes
checking for int32_t… yes
checking for size_t… yes
checking for ssize_t… yes
checking for sasl_server_init in -lsasl2… yes
checking for SASL_CB_GETCONF… yes
checking for SASL_CB_GETCONFPATH… yes
checking for SASL_CB_GETOPT… yes
checking for drop_privileges… yes
checking for pthread.h… yes
checking for pthread_create in -lpthread… yes
checking for library containing clock_gettime… none required
checking for clock_gettime… yes
checking for an ANSI C-conforming const… yes
checking for struct sockaddr_storage… yes
checking for socklen_t… yes
checking for struct sockaddr.sa_len… no
checking for struct sockaddr_in.sin_len… no
checking for struct sockaddr_in6.sin6_len… no
checking for struct sockaddr_un.sun_len… no
checking for struct sockaddr_un.sun_len… no
checking for getopt_long… yes
checking for getpwuid… yes
checking for getrlimit… yes
checking for setrlimit… yes
checking for setsid… yes
checking for sigaction… yes
checking for sigignore… yes
checking for socketpair… yes
checking for uname… yes
checking for setppriv… no
checking for getpeereid… no
checking for getpeerucred… no
checking for accept4… yes
checking for memcached with SASL support… yes
checking for memcached with SASL pwdb support… yes
checking that generated files are newer than configure… done
configure: creating ./config.status
config.status: creating Makefile
config.status: creating config.h
config.status: executing depfiles commands

# 编译
$ make -j$(nproc)
make all-am
make[1]: Entering directory ‘/tmp/memcached/memcached-1.6.22’
gcc -DHAVE_CONFIG_H -I. -DNDEBUG -g -O2 -pthread -pthread -MT memcached-memcached.o -MD -MP -MF .deps/memcached-memcached.Tpo -c -o memcached-memcached.o `test -f ‘memcached.c’ || echo ‘./’`memcached.c
mv -f .deps/memcached-memcached.Tpo .deps/memcached-memcached.Po
gcc -DHAVE_CONFIG_H -I. -DNDEBUG -g -O2 -pthread -pthread -MT memcached-thread.o -MD -MP -MF .deps/memcached-thread.Tpo -c -o memcached-thread.o `test -f ‘thread.c’ || echo ‘./’`thread.c
mv -f .deps/memcached-thread.Tpo .deps/memcached-thread.Po

make[1]: Leaving directory ‘/tmp/memcached/memcached-1.6.22’

# 安装
$ sudo make install
make[1]: Entering directory ‘/tmp/memcached/memcached-1.6.22’
/usr/bin/mkdir -p ‘/memcached/app/bin’
/usr/bin/install -c memcached ‘/memcached/app/bin’
/usr/bin/mkdir -p ‘/memcached/app/bin’
/usr/bin/install -c scripts/memcached-tool scripts/start-memcached scripts/damemtop ‘/memcached/app/bin’
make[1]: Nothing to be done for ‘install-data-am’.
make[1]: Leaving directory ‘/tmp/memcached/memcached-1.6.22’

# 验证安装
$ /memcached/app/bin/memcached -V
memcached 1.6.22

# 查看安装文件
$ ls -la /memcached/app/bin/
total 240
drwxr-xr-x. 2 root root 107 Apr 8 10:00 .
drwxr-xr-x. 3 root root 6 Apr 8 10:00 ..
-rwxr-xr-x. 1 root root 211056 Apr 8 10:00 memcached
-rwxr-xr-x. 1 root root 4547 Apr 8 10:00 memcached-tool
-rwxr-xr-x. 1 root root 4547 Apr 8 10:00 start-memcached
-rwxr-xr-x. 1 root root 4547 Apr 8 10:00 damemtop

3.3 Memcached数据库生产配置优化实战

3.3.1 创建生产配置文件

# 创建配置文件目录
$ sudo mkdir -p /memcached/conf

# 创建生产配置文件
$ sudo vi /memcached/conf/memcached.conf

# Memcached生产配置文件
# 端口配置
-p 11211

# 监听地址(绑定内网IP)
-l 192.168.1.100

# 禁用UDP端口(防止反射攻击)
-U 0

# 运行用户
-u memcached

# 内存大小(8GB)
-m 8192

# 内存耗尽时返回错误
-M

# 最大连接数
-c 4096

# 工作线程数
-t 8

# 每个slab页大小
-I 1m

# slab大小增长因子
-f 1.25

# 最小分配空间
-n 48

# 积压队列长度
-b 1024

# 每个事件最大请求数
-R 20

# 启用LRU爬虫
-o lru_crawler

# 启用LRU维护线程
-o lru_maintainer

# 启用slab重新分配
-o slab_reassign

# 启用slab自动移动
-o slab_automove

# HOT LRU百分比
-o hot_lru_pct=20

# WARM LRU百分比
-o warm_lru_pct=40

# 启用SASL认证
-S

# 日志级别
-v

# 守护进程模式
-d

# PID文件
-P /var/run/memcached/memcached.pid

# 验证配置文件
$ cat /memcached/conf/memcached.conf
-p 11211
-l 192.168.1.100
-U 0
-u memcached
-m 8192
-M
-c 4096
-t 8
-I 1m
-f 1.25
-n 48
-b 1024
-R 20
-o lru_crawler
-o lru_maintainer
-o slab_reassign
-o slab_automove
-o hot_lru_pct=20
-o warm_lru_pct=40
-S
-v
-d
-P /var/run/memcached/memcached.pid

3.3.2 创建启动脚本

# 创建脚本目录
$ sudo mkdir -p /memcached/scripts

# 创建启动脚本
$ sudo vi /memcached/scripts/start.sh
#!/bin/bash
# start.sh
# from:www.itpux.com.qq113257174.wx:itpux-com
# web: http://www.fgedu.net.cn

MEMCACHED_HOME=/memcached/app
MEMCACHED_CONF=/memcached/conf/memcached.conf
MEMCACHED_BIN=$MEMCACHED_HOME/bin/memcached
PID_FILE=/var/run/memcached/memcached.pid

# 检查是否已运行
if [ -f $PID_FILE ]; then
PID=$(cat $PID_FILE)
if ps -p $PID > /dev/null 2>&1; then
echo “Memcached is already running (PID: $PID)”
exit 1
fi
fi

# 创建PID目录
mkdir -p /var/run/memcached
chown memcached:memcached /var/run/memcached

# 启动Memcached
echo “Starting Memcached…”
$MEMCACHED_BIN -v < $MEMCACHED_CONF # 检查启动状态 sleep 2 if [ -f $PID_FILE ]; then PID=$(cat $PID_FILE) echo "Memcached started successfully (PID: $PID)" else echo "Failed to start Memcached" exit 1 fi # 设置脚本权限 $ sudo chmod +x /memcached/scripts/start.sh # 创建停止脚本 $ sudo vi /memcached/scripts/stop.sh #!/bin/bash # stop.sh # from:www.itpux.com.qq113257174.wx:itpux-com # web: http://www.fgedu.net.cn PID_FILE=/var/run/memcached/memcached.pid if [ ! -f $PID_FILE ]; then echo "Memcached is not running" exit 1 fi PID=$(cat $PID_FILE) if ! ps -p $PID > /dev/null 2>&1; then
echo “Memcached is not running”
rm -f $PID_FILE
exit 1
fi

echo “Stopping Memcached (PID: $PID)…”
kill $PID

# 等待进程结束
for i in {1..10}; do
if ! ps -p $PID > /dev/null 2>&1; then
echo “Memcached stopped successfully”
rm -f $PID_FILE
exit 0
fi
sleep 1
done

# 强制杀死进程
echo “Force killing Memcached…”
kill -9 $PID
rm -f $PID_FILE
echo “Memcached stopped”

# 设置脚本权限
$ sudo chmod +x /memcached/scripts/stop.sh

# 创建状态检查脚本
$ sudo vi /memcached/scripts/status.sh
#!/bin/bash
# status.sh
# from:www.itpux.com.qq113257174.wx:itpux-com
# web: http://www.fgedu.net.cn

PID_FILE=/var/run/memcached/memcached.pid

if [ ! -f $PID_FILE ]; then
echo “Memcached is not running”
exit 1
fi

PID=$(cat $PID_FILE)

if ps -p $PID > /dev/null 2>&1; then
echo “Memcached is running (PID: $PID)”
# 显示进程信息
ps -p $PID -o pid,ppid,user,%cpu,%mem,vsz,rss,stat,start,time,command
exit 0
else
echo “Memcached is not running (stale PID file)”
exit 1
fi

# 设置脚本权限
$ sudo chmod +x /memcached/scripts/status.sh

Part04-生产案例与实战讲解

4.1 Memcached数据库多实例部署实战

在生产环境中,可以通过部署多个Memcached实例来提高性能和可用性。from Memcached视频:www.itpux.com

4.1.1 创建多实例配置

# 创建多实例配置目录
$ sudo mkdir -p /memcached/conf/instances

# 创建实例1配置
$ sudo vi /memcached/conf/instances/memcached-11211.conf
-p 11211
-l 192.168.1.100
-U 0
-u memcached
-m 4096
-c 2048
-t 4
-v
-d
-P /var/run/memcached/memcached-11211.pid

# 创建实例2配置
$ sudo vi /memcached/conf/instances/memcached-11212.conf
-p 11212
-l 192.168.1.100
-U 0
-u memcached
-m 4096
-c 2048
-t 4
-v
-d
-P /var/run/memcached/memcached-11212.pid

# 创建实例3配置
$ sudo vi /memcached/conf/instances/memcached-11213.conf
-p 11213
-l 192.168.1.100
-U 0
-u memcached
-m 4096
-c 2048
-t 4
-v
-d
-P /var/run/memcached/memcached-11213.pid

# 验证配置文件
$ ls -la /memcached/conf/instances/
total 12
drwxr-xr-x. 2 root root root 78 Apr 8 10:00 .
drwxr-xr-x. 3 root root root 20 Apr 8 10:00 ..
-rw-r–r–. 1 root root root 85 Apr 8 10:00 memcached-11211.conf
-rw-r–r–. 1 root root root 85 Apr 8 10:00 memcached-11212.conf
-rw-r–r–. 1 root root root 85 Apr 8 10:00 memcached-11213.conf

4.1.2 创建多实例管理脚本

# 创建多实例启动脚本
$ sudo vi /memcached/scripts/start_all.sh
#!/bin/bash
# start_all.sh
# from:www.itpux.com.qq113257174.wx:itpux-com
# web: http://www.fgedu.net.cn

MEMCACHED_HOME=/memcached/app
MEMCACHED_BIN=$MEMCACHED_HOME/bin/memcached
CONF_DIR=/memcached/conf/instances

echo “Starting all Memcached instances…”

for conf in $CONF_DIR/*.conf; do
port=$(grep “^-p” $conf | awk ‘{print $2}’)
echo “Starting Memcached on port $port…”
$MEMCACHED_BIN -v < $conf done sleep 2 echo "All instances started" # 显示运行状态 ps aux | grep memcached | grep -v grep # 设置权限 $ sudo chmod +x /memcached/scripts/start_all.sh # 创建多实例停止脚本 $ sudo vi /memcached/scripts/stop_all.sh #!/bin/bash # stop_all.sh # from:www.itpux.com.qq113257174.wx:itpux-com # web: http://www.fgedu.net.cn echo "Stopping all Memcached instances..." pkill -u memcached memcached sleep 2 # 清理PID文件 rm -f /var/run/memcached/*.pid echo "All instances stopped" # 验证 ps aux | grep memcached | grep -v grep || echo "No Memcached processes running" # 设置权限 $ sudo chmod +x /memcached/scripts/stop_all.sh

4.2 Memcached数据库Systemd服务配置

4.2.1 创建Systemd服务文件

# 创建Systemd服务文件
$ sudo vi /etc/systemd/system/memcached.service
[Unit]
Description=Memcached Daemon
After=network.target

[Service]
Type=simple
User=memcached
Group=memcached
ExecStart=/memcached/app/bin/memcached -u memcached -p 11211 -l 192.168.1.100 -m 8192 -c 4096 -t 8 -v
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
Restart=on-failure
RestartSec=5
LimitNOFILE=65535
PrivateTmp=true

[Install]
WantedBy=multi-user.target

# 重载Systemd配置
$ sudo systemctl daemon-reload

# 启用开机自启
$ sudo systemctl enable memcached
Created symlink /etc/systemd/system/multi-user.target.wants/memcached.service → /etc/systemd/system/memcached.service.

# 启动服务
$ sudo systemctl start memcached

# 查看服务状态
$ sudo systemctl status memcached
● memcached.service – Memcached Daemon
Loaded: loaded (/etc/systemd/system/memcached.service; enabled; preset: disabled)
Active: active (running) since Mon 2026-04-08 10:00:00 CST; 5s ago
Main PID: 12345 (memcached)
Tasks: 9 (limit: 23456)
Memory: 8.2G
CPU: 10ms
CGroup: /system.slice/memcached.service
└─12345 /memcached/app/bin/memcached -u memcached -p 11211 -l 192.168.1.100 -m 8192 -c 4096 -t 8 -v

Apr 08 10:00:00 fgedu.net.cn systemd[1]: Started Memcached Daemon.

4.2.2 创建多实例Systemd服务

# 创建模板服务文件
$ sudo vi /etc/systemd/system/memcached@.service
[Unit]
Description=Memcached Instance %i
After=network.target

[Service]
Type=simple
User=memcached
Group=memcached
EnvironmentFile=/memcached/conf/instances/memcached-%i.conf
ExecStart=/memcached/app/bin/memcached -u memcached -p ${PORT} -l ${LISTEN} -m ${MEMORY} -c ${MAXCONN} -t ${THREADS} -v
ExecReload=/bin/kill -HUP $MAINPID
ExecStop=/bin/kill -s QUIT $MAINPID
Restart=on-failure
RestartSec=5
LimitNOFILE=65535
PrivateTmp=true

[Install]
WantedBy=multi-user.target

# 修改配置文件格式
$ sudo vi /memcached/conf/instances/memcached-11211.conf
PORT=11211
LISTEN=192.168.1.100
MEMORY=4096
MAXCONN=2048
THREADS=4

$ sudo vi /memcached/conf/instances/memcached-11212.conf
PORT=11212
LISTEN=192.168.1.100
MEMORY=4096
MAXCONN=2048
THREADS=4

# 重载配置
$ sudo systemctl daemon-reload

# 启动多实例
$ sudo systemctl start memcached@11211
$ sudo systemctl start memcached@11212

# 启用开机自启
$ sudo systemctl enable memcached@11211
$ sudo systemctl enable memcached@11212

# 查看状态
$ sudo systemctl status memcached@11211
● memcached@11211.service – Memcached Instance 11211
Loaded: loaded (/etc/systemd/system/memcached@.service; disabled; preset: disabled)
Active: active (running) since Mon 2026-04-08 10:00:00 CST; 5s ago
Main PID: 12346 (memcached)
Tasks: 5 (limit: 23456)
Memory: 4.1G
CPU: 5ms
CGroup: /system.slice/memcached@11211.service
└─12346 /memcached/app/bin/memcached -u memcached -p 11211 -l 192.168.1.100 -m 4096 -c 2048 -t 4 -v

Apr 08 10:00:00 fgedu.net.cn systemd[1]: Started Memcached Instance 11211.

4.3 Memcached数据库启动与验证测试

4.3.1 启动Memcached服务

# 使用Systemd启动
$ sudo systemctl start memcached

# 查看进程
$ ps aux | grep memcached | grep -v grep
memcach+ 12345 0.0 12.5 6815744 8396800 ? Ssl 10:00 0:00 /memcached/app/bin/memcached -u memcached -p 11211 -l 192.168.1.100 -m 8192 -c 4096 -t 8 -v

# 查看端口
$ netstat -tlnp | grep memcached
tcp 0 0 192.168.1.100:11211 0.0.0.0:* LISTEN 12345/memcached

# 使用ss命令查看
$ ss -tlnp | grep 11211
LISTEN 0 1024 192.168.1.100:11211 *:* users:((“memcached”,pid=12345,fd=26))

4.3.2 连接测试

# 使用telnet测试连接
$ telnet 192.168.1.100 11211
Trying 192.168.1.100…
Connected to 192.168.1.100.
Escape character is ‘^]’.

# 测试存储数据
set fgedu_test 0 3600 12
Hello World!
STORED

# 测试读取数据
get fgedu_test
VALUE fgedu_test 0 12
Hello World!
END

# 测试删除数据
delete fgedu_test
DELETED

# 查看统计信息
stats
STAT pid 12345
STAT uptime 120
STAT time 1712534520
STAT version 1.6.22
STAT libevent 2.1.12-stable
STAT pointer_size 64
STAT rusage_user 0.012345
STAT rusage_system 0.023456
STAT max_connections 4096
STAT curr_connections 1
STAT total_connections 2
STAT connection_structures 2
STAT reserved_fds 20
STAT cmd_get 1
STAT cmd_set 1
STAT cmd_flush 0
STAT cmd_touch 0
STAT get_hits 1
STAT get_misses 0
STAT delete_misses 0
STAT delete_hits 1
STAT incr_misses 0
STAT incr_hits 0
STAT decr_misses 0
STAT decr_hits 0
STAT cas_misses 0
STAT cas_hits 0
STAT cas_badval 0
STAT touch_hits 0
STAT touch_misses 0
STAT auth_cmds 0
STAT auth_errors 0
STAT bytes_read 50
STAT bytes_written 50
STAT limit_maxbytes 8589934592
STAT accepting_conns 1
STAT listen_disabled_num 0
STAT threads 8
STAT conn_yields 0
STAT hash_power_level 16
STAT hash_bytes 524288
STAT hash_is_expanding 0
STAT slab_reassign_running 0
STAT slab_global_page_pool 0
STAT lru_maintainer_juggles 0
STAT malloc_fails 0
STAT log_worker_dropped 0
STAT log_worker_written 0
STAT log_watcher_skipped 0
STAT log_watcher_sent 0
STAT bytes 0
STAT curr_items 0
STAT total_items 1
STAT slab_global_page_pool 0
STAT expired_unfetched 0
STAT evicted_unfetched 0
STAT evictions 0
STAT reclaimed 0
STAT crawler_reclaimed 0
STAT crawler_items_checked 0
STAT lrutail_reflocked 0
STAT moves_to_cold 0
STAT moves_to_warm 0
STAT moves_within_lru 0
STAT direct_reclaims 0
END

# 退出
quit
Connection closed by foreign host.

4.3.3 性能测试

# 安装测试工具
$ sudo dnf install -y libmemcached

# 使用memslap进行性能测试
$ memslap –servers=192.168.1.100:11211 –concurrency=10 –test=10000
memslap: Created 10 threads
memslap: Running test for 10000 operations
memslap: Test completed
Threads: 10
Concurrency: 10
Run time: 5.234 Seconds
Operations: 10000
Ops/sec: 1910.56
Avg time: 0.000523 ms

# 使用memcapable测试功能
$ memcapable -h 192.168.1.100 -p 11211
All tests passed

# 查看测试后的统计信息
$ echo “stats” | nc 192.168.1.100 11211 | grep -E “cmd_get|cmd_set|get_hits|get_misses”
STAT cmd_get 5000
STAT cmd_set 5000
STAT get_hits 4500
STAT get_misses 500

Part05-风哥经验总结与分享

5.1 Memcached数据库安装最佳实践

5.1.1 安装方式选择建议

  • 快速部署:使用YUM/APT包管理器安装
  • 生产环境:推荐源码编译安装,可获取最新版本
  • 容器环境:使用Docker镜像部署

5.1.2 版本选择建议

# Memcached版本选择建议

# 稳定版本(推荐生产环境)
– 1.6.22:最新稳定版本
– 1.6.x系列:经过充分测试

# 新特性版本(测试环境)
– 最新开发版本

# 版本升级原则
– 先在测试环境验证
– 做好回滚准备
– 选择业务低峰期升级

5.2 Memcached数据库配置最佳实践

5.2.1 内存配置建议

  • 根据业务数据量合理规划内存大小
  • 预留足够的内存给操作系统
  • 监控内存使用率,及时扩容
  • 使用-M参数防止内存耗尽时数据丢失

5.2.2 性能优化建议

# Memcached性能优化建议

# 线程数配置
– 线程数 = CPU核心数(建议不超过8)
– 过多线程会增加锁竞争

# 连接数配置
– 根据并发量合理设置
– 预留一定余量

# Slab配置
– 根据数据大小调整增长因子
– 使用memcached-tool分析slab使用情况

# LRU配置
– 启用lru_crawler和lru_maintainer
– 合理设置hot_lru_pct和warm_lru_pct

5.3 Memcached数据库安装常见问题

5.3.1 启动失败:地址已被占用

# 问题现象
$ sudo systemctl start memcached
Job for memcached.service failed because the control process exited with error code.

# 查看日志
$ journalctl -u memcached -n 20
Apr 08 10:00:00 fgedu.net.cn memcached[12345]: failed to listen on TCP port 11211: Address already in use

# 解决方案
# 查找占用端口的进程
$ netstat -tlnp | grep 11211
tcp 0 0 0.0.0.0:11211 0.0.0.0:* LISTEN 54321/memcached

# 停止旧进程
$ sudo kill 54321

# 或修改配置使用其他端口
$ sudo vi /etc/sysconfig/memcached
PORT=”11212″

5.3.2 启动失败:权限不足

# 问题现象
$ sudo systemctl start memcached
Job for memcached.service failed.

# 查看日志
$ journalctl -u memcached -n 20
Apr 08 10:00:00 fgedu.net.cn memcached[12345]: failed to set uid to memcached: Operation not permitted

# 解决方案
# 检查用户是否存在
$ id memcached
id: ‘memcached’: no such user

# 创建用户
$ sudo useradd -r -s /sbin/nologin memcached

# 检查目录权限
$ ls -la /memcached/
drwxr-xr-x. 2 root root 6 Apr 8 10:00 app

# 修改权限
$ sudo chown -R memcached:memcached /memcached

5.3.3 连接被拒绝

# 问题现象
$ telnet 192.168.1.100 11211
telnet: connect to address 192.168.1.100: Connection refused

# 排查步骤
# 1. 检查服务是否运行
$ sudo systemctl status memcached
● memcached.service – Memcached Daemon
Loaded: loaded (/etc/systemd/system/memcached.service; enabled; preset: disabled)
Active: inactive (dead)

# 2. 启动服务
$ sudo systemctl start memcached

# 3. 检查防火墙
$ sudo firewall-cmd –list-all
public (active)

ports:

# 4. 开放端口
$ sudo firewall-cmd –permanent –add-port=11211/tcp
$ sudo firewall-cmd –reload

# 5. 检查SELinux
$ getenforce
Enforcing

# 6. 临时关闭SELinux测试
$ sudo setenforce 0

# 7. 或配置SELinux策略
$ sudo setsebool -P memcached_can_network_connect 1

风哥总结:Memcached安装配置相对简单,但生产环境需要仔细规划内存、连接数、线程数等参数。建议使用Systemd管理服务,配置好监控和日志,确保服务稳定运行。安全方面要特别注意绑定内网IP、禁用UDP、配置防火墙规则。

本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html

联系我们

在线咨询:点击这里给我发消息

微信号:itpux-com

工作日:9:30-18:30,节假日休息