Memcached教程FG008-Memcached PHP客户端集成实战
本文档风哥主要介绍Memcached数据库PHP客户端集成相关知识,包括Memcached数据库PHP客户端概述、Memcached扩展介绍、Memcache扩展介绍、扩展安装规划、连接规划、基本操作实战、高级操作实战、框架集成实战等内容,风哥教程参考Memcached官方文档Client Libraries等内容编写,适合DBA人员和运维人员在学习和测试中使用,如果要应用于生产环境则需要自行确认。
Part01-基础概念与理论知识
1.1 Memcached数据库PHP客户端概述
PHP是Memcached最常用的客户端语言之一,主要有两种扩展可供选择。更多视频教程www.fgedu.net.cn
1.1.1 PHP客户端对比
┌─────────────────┬─────────────────┬─────────────────┐
│ 特性 │ Memcached │ Memcache │
│ │ 扩展 │ 扩展 │
├─────────────────┼─────────────────┼─────────────────┤
│ 一致性哈希 │ 支持 │ 不支持 │
│ CAS操作 │ 支持 │ 不支持 │
│ 二进制协议 │ 支持 │ 不支持 │
│ 延迟写入 │ 支持 │ 不支持 │
│ SASL认证 │ 支持 │ 不支持 │
│ Session处理 │ 支持 │ 支持 │
│ 维护状态 │ 活跃 │ 维护模式 │
│ 性能 │ 高 │ 中 │
│ 推荐度 │ 推荐 │ 不推荐 │
└─────────────────┴─────────────────┴─────────────────┘
# 推荐选择
Memcached扩展(推荐)
– 功能更完善
– 支持一致性哈希
– 支持CAS操作
– 支持二进制协议
– 持续维护更新
1.1.2 客户端架构
┌─────────────────────────────────────────────────────────────┐
│ PHP应用层 │
│ (Laravel/Symfony/原生PHP) │
└─────────────────────┬───────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Memcached扩展 │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 核心功能 │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │ 连接管理 │ │ 命令执行 │ │ 序列化 │ │ │
│ │ │ (Pool) │ │ (Protocol) │ │ (Encoder) │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
│ ┌─────────────────────────────────────────────────────┐ │
│ │ 分布式组件 │ │
│ │ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ │
│ │ │ 一致性哈希 │ │ 故障转移 │ │ 负载均衡 │ │ │
│ │ │ (Ketama) │ │ (Failover) │ │ (Balance) │ │ │
│ │ └─────────────┘ └─────────────┘ └─────────────┘ │ │
│ └─────────────────────────────────────────────────────┘ │
└─────────────────────┬───────────────────────────────────────┘
│
▼
┌─────────────────────────────────────────────────────────────┐
│ Memcached服务器集群 │
│ Server1 Server2 Server3 Server4 │
└─────────────────────────────────────────────────────────────┘
1.2 Memcached扩展介绍
Memcached扩展是PHP官方推荐的Memcached客户端,功能完善。学习交流加群风哥微信: itpux-com
1.2.1 Memcached扩展特性
# 1. 连接管理
– 支持持久连接
– 支持连接池
– 自动重连机制
# 2. 分布式支持
– 一致性哈希(Ketama)
– 虚拟节点支持
– 动态节点管理
# 3. 高级功能
– CAS(Check And Set)操作
– 延迟写入
– 批量操作
– 二进制协议
# 4. Session支持
– 支持Session存储
– 自动序列化
– 分布式Session
# 常用类和方法
# Memcached类
class Memcached {
// 构造函数
public __construct([string $persistent_id])
// 服务器管理
public addServer(string $host, int $port [, int $weight])
public addServers(array $servers)
public getServerList(): array
// 存储操作
public set(string $key, mixed $value [, int $expiration]): bool
public add(string $key, mixed $value [, int $expiration]): bool
public replace(string $key, mixed $value [, int $expiration]): bool
// 获取操作
public get(string $key [, callable $cache_cb [, int &$flags]])
public getMulti(array $keys [, array &$flags])
// 删除操作
public delete(string $key [, int $time]): bool
// 增减操作
public increment(string $key [, int $offset])
public decrement(string $key [, int $offset])
// CAS操作
public cas(float $cas_token, string $key, mixed $value)
// 配置选项
public setOption(int $option, mixed $value): bool
public getOption(int $option): mixed
// 统计信息
public getStats(): array
public getVersion(): array
}
1.2.2 Memcached扩展选项
# 分布相关选项
Memcached::OPT_DISTRIBUTION
– Memcached::DISTRIBUTION_MODULA # 取模分布
– Memcached::DISTRIBUTION_CONSISTENT # 一致性哈希
Memcached::OPT_LIBKETAMA_COMPATIBLE # 启用Ketama兼容模式
# 哈希相关选项
Memcached::OPT_HASH
– Memcached::HASH_DEFAULT # 默认哈希
– Memcached::HASH_MD5 # MD5哈希
– Memcached::HASH_CRC32 # CRC32哈希
# 连接相关选项
Memcached::OPT_CONNECT_TIMEOUT # 连接超时(毫秒)
Memcached::OPT_RETRY_TIMEOUT # 重试超时(秒)
Memcached::OPT_SEND_TIMEOUT # 发送超时(毫秒)
Memcached::OPT_RECV_TIMEOUT # 接收超时(毫秒)
# 行为相关选项
Memcached::OPT_BINARY_PROTOCOL # 使用二进制协议
Memcached::OPT_BUFFER_WRITES # 缓冲写入
Memcached::OPT_NO_BLOCK # 非阻塞模式
# 故障处理选项
Memcached::OPT_SERVER_FAILURE_LIMIT # 服务器故障限制
Memcached::OPT_AUTO_EJECT_HOSTS # 自动剔除故障主机
# 序列化选项
Memcached::OPT_SERIALIZER
– Memcached::SERIALIZER_PHP # PHP序列化
– Memcached::SERIALIZER_IGBINARY # Igbinary序列化
– Memcached::SERIALIZER_JSON # JSON序列化
# 压缩选项
Memcached::OPT_COMPRESSION # 启用压缩
1.3 Memcache扩展介绍
1.3.1 Memcache扩展特性
# 优点
– 安装简单
– 使用方便
– 稳定性好
# 缺点
– 不支持一致性哈希
– 不支持CAS操作
– 不支持二进制协议
– 功能较少
# Memcache类
class Memcache {
// 连接
public connect(string $host [, int $port [, int $timeout]]): bool
public pconnect(string $host [, int $port [, int $timeout]]): bool
public close(): bool
// 服务器管理
public addServer(string $host [, int $port [, bool $persistent]])
// 存储操作
public set(string $key, mixed $value [, int $flag [, int $expire]]): bool
public add(string $key, mixed $value [, int $flag [, int $expire]]): bool
public replace(string $key, mixed $value [, int $flag [, int $expire]]): bool
// 获取操作
public get(string $key [, int &$flags])
public get(array $keys [, array &$flags])
// 删除操作
public delete(string $key [, int $timeout]): bool
// 增减操作
public increment(string $key [, int $value]): int
public decrement(string $key [, int $value]): int
}
# 不推荐使用Memcache扩展
# 建议使用Memcached扩展获得更好的功能和性能
Part02-生产环境规划与建议
2.1 Memcached数据库扩展安装规划
正确的安装配置是PHP客户端稳定运行的基础。学习交流加群风哥QQ113257174
2.1.1 安装Memcached扩展
# 方式1:使用PECL安装
$ sudo pecl install memcached
# 方式2:使用包管理器安装
# Oracle Linux / RHEL / CentOS
$ sudo dnf install -y php-pecl-memcached
# Ubuntu / Debian
$ sudo apt install -y php-memcached
# 方式3:源码编译安装
$ cd /tmp
$ wget https://pecl.php.net/get/memcached-3.2.0.tgz
$ tar -xzf memcached-3.2.0.tgz
$ cd memcached-3.2.0
$ phpize
$ ./configure –enable-memcached
$ make -j$(nproc)
$ sudo make install
# 启用扩展
$ sudo vi /etc/php.d/memcached.ini
extension=memcached.so
# 验证安装
$ php -m | grep memcached
memcached
$ php -i | grep -i memcached
memcached support => enabled
2.1.2 安装依赖库
# 安装libmemcached
$ sudo dnf install -y libmemcached libmemcached-devel
# 安装igbinary(可选,提高序列化性能)
$ sudo pecl install igbinary
# 启用igbinary
$ sudo vi /etc/php.d/igbinary.ini
extension=igbinary.so
# 验证依赖
$ php -i | grep -E “libmemcached|igbinary”
libmemcached version => 1.0.18
igbinary support => enabled
2.2 Memcached数据库连接规划
2.2.1 连接配置建议
# 服务器配置
$servers = [
[‘192.168.1.101’, 11211, 20], // 主机, 端口, 权重
[‘192.168.1.102’, 11211, 20],
[‘192.168.1.103’, 11211, 30],
[‘192.168.1.104’, 11211, 30],
];
# 创建Memcached实例
$memcached = new Memcached(‘fgedu_pool’);
# 检查是否已添加服务器(持久连接场景)
if (!count($memcached->getServerList())) {
$memcached->addServers($servers);
}
# 配置选项
$memcached->setOptions([
// 启用一致性哈希
Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
// 连接超时
Memcached::OPT_CONNECT_TIMEOUT => 3000,
// 操作超时
Memcached::OPT_SEND_TIMEOUT => 3000,
Memcached::OPT_RECV_TIMEOUT => 3000,
// 重试配置
Memcached::OPT_RETRY_TIMEOUT => 1,
Memcached::OPT_SERVER_FAILURE_LIMIT => 3,
// 启用压缩
Memcached::OPT_COMPRESSION => true,
]);
# 验证连接
$stats = $memcached->getStats();
foreach ($stats as $server => $info) {
echo “Server: $server\n”;
echo ” Version: ” . $info[‘version’] . “\n”;
}
2.2.2 持久连接配置
# 持久连接的优势
– 减少连接开销
– 提高性能
– 复用连接
# 创建持久连接
// 使用持久ID创建实例
$memcached = new Memcached(‘fgedu_persistent_pool’);
// 检查服务器列表
if (!count($memcached->getServerList())) {
$memcached->addServers([
[‘192.168.1.101’, 11211],
[‘192.168.1.102’, 11211],
]);
}
# 持久连接配置选项
$memcached->setOptions([
Memcached::OPT_TCP_NODELAY => true,
Memcached::OPT_CONNECT_TIMEOUT => 1000,
Memcached::OPT_SEND_TIMEOUT => 1000,
Memcached::OPT_RECV_TIMEOUT => 1000,
]);
# 注意事项
// 持久连接在PHP-FPM环境下效果最好
// 每个持久ID对应一个连接池
// 不同持久ID的实例不共享连接
2.3 Memcached数据库配置规划
2.3.1 配置文件规划
# config/memcached.php
[
‘servers’ => [
[‘host’ => ‘192.168.1.101’, ‘port’ => 11211, ‘weight’ => 20],
[‘host’ => ‘192.168.1.102’, ‘port’ => 11211, ‘weight’ => 20],
[‘host’ => ‘192.168.1.103’, ‘port’ => 11211, ‘weight’ => 30],
[‘host’ => ‘192.168.1.104’, ‘port’ => 11211, ‘weight’ => 30],
],
‘options’ => [
Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
Memcached::OPT_CONNECT_TIMEOUT => 3000,
],
‘persistent_id’ => ‘fgedu_default_pool’,
],
];
2.3.2 php.ini配置
# Session存储配置
session.save_handler = memcached
session.save_path = “192.168.1.101:11211,192.168.1.102:11211”
# Memcached扩展配置
[memcached]
extension = memcached.so
# Session锁定
memcached.sess_locking = On
memcached.sess_lock_wait = 150000
# Session前缀
memcached.sess_prefix = “fgedu_sess_”
# 序列化
memcached.serializer = php
# 压缩
memcached.compression_type = fastlz
memcached.compression_threshold = 2000
# 验证配置
$ php -i | grep memcached
Part03-生产环境项目实施方案
3.1 Memcached数据库基本操作实战
3.1.1 连接与基本操作
addServers([
[‘192.168.1.101’, 11211],
[‘192.168.1.102’, 11211],
]);
// 配置选项
$memcached->setOptions([
Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
]);
// 存储数据
$memcached->set(‘fgedu_user:1001’, ‘张三’, 3600);
echo “存储用户数据成功\n”;
// 获取数据
$user = $memcached->get(‘fgedu_user:1001’);
echo “获取用户: $user\n”;
// 存储数组
$userData = [
‘id’ => 1001,
‘name’ => ‘fgedu’,
’email’ => ‘fgedu@fgedu.net.cn’,
];
$memcached->set(‘fgedu_user_data:1001’, $userData, 3600);
echo “存储用户数组成功\n”;
// 获取数组
$cachedUser = $memcached->get(‘fgedu_user_data:1001’);
print_r($cachedUser);
// 删除数据
$memcached->delete(‘fgedu_user:1001’);
echo “删除用户数据成功\n”;
// 获取结果码
$code = $memcached->getResultCode();
$message = $memcached->getResultMessage();
echo “结果码: $code, 消息: $message\n”;
?>
# 输出结果
存储用户数据成功
获取用户: 张三
存储用户数组成功
Array
(
[id] => 1001
[name] => fgedu
[email] => fgedu@fgedu.net.cn
)
删除用户数据成功
结果码: 0, 消息: SUCCESS
3.1.2 增减操作实战
addServer(‘192.168.1.101’, 11211);
// 初始化计数器
$memcached->set(‘fgedu_counter:page_views’, 0, 0);
echo “初始化计数器\n”;
// 自增操作
$value = $memcached->increment(‘fgedu_counter:page_views’, 1);
echo “自增后值: $value\n”;
$value = $memcached->increment(‘fgedu_counter:page_views’, 10);
echo “自增10后值: $value\n”;
// 自减操作
$value = $memcached->decrement(‘fgedu_counter:page_views’, 5);
echo “自减5后值: $value\n”;
// 带初始值的自增
$value = $memcached->increment(‘fgedu_counter:new’, 1, 0, 100);
echo “新计数器初始值: $value\n”;
?>
# 输出结果
初始化计数器
自增后值: 1
自增10后值: 11
自减5后值: 6
新计数器初始值: 100
3.2 Memcached数据库高级操作实战
3.2.1 CAS操作实战
addServer(‘192.168.1.101’, 11211);
// 初始化账户余额
$memcached->set(‘fgedu_balance:1001’, 1000, 0);
echo “初始化账户余额: 1000\n”;
// CAS更新函数
function updateBalance($memcached, $accountId, $amount) {
$key = “fgedu_balance:$accountId”;
$maxRetries = 3;
for ($i = 0; $i < $maxRetries; $i++) { // 获取当前值和CAS标识 $cas = null; $balance = $memcached->get($key, null, $cas);
echo “当前余额: $balance, CAS: $cas\n”;
// 计算新余额
$newBalance = $balance + $amount;
// 尝试CAS更新
$result = $memcached->cas($cas, $key, $newBalance, 0);
if ($result) {
echo “更新成功,新余额: $newBalance\n”;
return true;
}
// 检查是否是CAS冲突
$code = $memcached->getResultCode();
if ($code == Memcached::RES_DATA_EXISTS) {
echo “CAS冲突,重试…\n”;
continue;
}
return false;
}
return false;
}
// 测试CAS操作
updateBalance($memcached, 1001, 100); // 存款100
updateBalance($memcached, 1001, -50); // 取款50
?>
# 输出结果
初始化账户余额: 1000
当前余额: 1000, CAS: 123
更新成功,新余额: 1100
当前余额: 1100, CAS: 124
更新成功,新余额: 1050
3.2.2 批量操作实战
addServers([
[‘192.168.1.101’, 11211],
[‘192.168.1.102’, 11211],
]);
// 批量存储数据
$items = [
‘fgedu_product:1’ => [‘id’ => 1, ‘name’ => ‘商品A’, ‘price’ => 100],
‘fgedu_product:2’ => [‘id’ => 2, ‘name’ => ‘商品B’, ‘price’ => 200],
‘fgedu_product:3’ => [‘id’ => 3, ‘name’ => ‘商品C’, ‘price’ => 300],
];
// 批量设置
foreach ($items as $key => $value) {
$memcached->set($key, $value, 3600);
}
echo “批量存储完成\n”;
// 批量获取
$keys = array_keys($items);
$cachedItems = $memcached->getMulti($keys);
echo “批量获取结果:\n”;
foreach ($cachedItems as $key => $value) {
echo ” $key: ” . json_encode($value) . “\n”;
}
// 批量删除
$deleteKeys = [‘fgedu_product:2’, ‘fgedu_product:3’];
$memcached->deleteMulti($deleteKeys);
echo “批量删除完成\n”;
// 获取统计信息
$stats = $memcached->getStats();
echo “\n服务器统计:\n”;
foreach ($stats as $server => $info) {
echo “服务器: $server\n”;
echo ” 版本: ” . $info[‘version’] . “\n”;
echo ” 当前Item数: ” . $info[‘curr_items’] . “\n”;
}
?>
3.3 Memcached数据库框架集成实战
3.3.1 Laravel集成
# 1. 配置文件 config/cache.php
env(‘CACHE_DRIVER’, ‘memcached’),
‘stores’ => [
‘memcached’ => [
‘driver’ => ‘memcached’,
‘persistent_id’ => env(‘MEMCACHED_PERSISTENT_ID’, ‘fgedu_pool’),
‘servers’ => [
[
‘host’ => env(‘MEMCACHED_HOST_1’, ‘192.168.1.101’),
‘port’ => env(‘MEMCACHED_PORT_1’, 11211),
‘weight’ => 100,
],
[
‘host’ => env(‘MEMCACHED_HOST_2’, ‘192.168.1.102’),
‘port’ => env(‘MEMCACHED_PORT_2’, 11211),
‘weight’ => 100,
],
],
],
],
];
# 2. .env配置
CACHE_DRIVER=memcached
MEMCACHED_HOST_1=192.168.1.101
MEMCACHED_PORT_1=11211
# 3. 使用示例
3.3.2 Symfony集成
# 1. 安装依赖
$ composer require symfony/cache
# 2. 配置文件 config/packages/cache.yaml
framework:
cache:
default_memcached_provider: ‘memcached://192.168.1.101:11211’
pools:
cache.memcached:
adapter: cache.adapter.memcached
# 3. 使用示例
cache = $cache;
}
public function getUser($id)
{
return $this->cache->get(“fgedu_user:{$id}”, function ($item) use ($id) {
$item->expiresAfter(3600);
return $this->fetchUserFromDatabase($id);
});
}
}
Part04-生产案例与实战讲解
4.1 Memcached数据库缓存封装案例
以下是一个完整的缓存服务封装案例。更多学习教程公众号风哥教程itpux_com
4.1.1 缓存服务类实现
memcached = new Memcached($options[‘persistent_id’] ?? null);
if (!count($this->memcached->getServerList())) {
$this->memcached->addServers($servers);
}
$defaultOptions = [
Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
Memcached::OPT_CONNECT_TIMEOUT => 3000,
Memcached::OPT_COMPRESSION => true,
];
$this->memcached->setOptions(array_merge($defaultOptions, $options[‘options’] ?? []));
}
private function buildKey(string $namespace, string $key): string
{
return $this->prefix . $namespace . ‘:’ . $key;
}
public function set(string $namespace, string $key, $value, int $expire = null): bool
{
$cacheKey = $this->buildKey($namespace, $key);
return $this->memcached->set($cacheKey, $value, $expire ?? $this->defaultExpire);
}
public function get(string $namespace, string $key)
{
$cacheKey = $this->buildKey($namespace, $key);
return $this->memcached->get($cacheKey);
}
public function getOrLoad(string $namespace, string $key, callable $loader, int $expire = null)
{
$cacheKey = $this->buildKey($namespace, $key);
$value = $this->memcached->get($cacheKey);
if ($value !== false) {
return $value;
}
$value = $loader();
if ($value !== null) {
$this->memcached->set($cacheKey, $value, $expire ?? $this->defaultExpire);
}
return $value;
}
public function delete(string $namespace, string $key): bool
{
$cacheKey = $this->buildKey($namespace, $key);
return $this->memcached->delete($cacheKey);
}
public function multiGet(string $namespace, array $keys): array
{
$cacheKeys = [];
foreach ($keys as $key) {
$cacheKeys[$key] = $this->buildKey($namespace, $key);
}
$result = $this->memcached->getMulti(array_values($cacheKeys));
$finalResult = [];
foreach ($keys as $key) {
$cacheKey = $cacheKeys[$key];
if (isset($result[$cacheKey])) {
$finalResult[$key] = $result[$cacheKey];
}
}
return $finalResult;
}
public function increment(string $namespace, string $key, int $offset = 1): int
{
$cacheKey = $this->buildKey($namespace, $key);
$result = $this->memcached->increment($cacheKey, $offset);
if ($result === false) {
$this->memcached->set($cacheKey, $offset, 0);
return $offset;
}
return $result;
}
}
4.2 Memcached数据库Session缓存案例
4.2.1 Session存储配置
# 方式1:php.ini配置
session.save_handler = memcached
session.save_path = “192.168.1.101:11211,192.168.1.102:11211”
# 方式2:代码中配置
memcached = $memcached;
$this->ttl = $ttl;
}
public function read($sessionId): string
{
$data = $this->memcached->get($this->prefix . $sessionId);
return $data === false ? ” : $data;
}
public function write($sessionId, $data): bool
{
return $this->memcached->set($this->prefix . $sessionId, $data, $this->ttl);
}
public function destroy($sessionId): bool
{
return $this->memcached->delete($this->prefix . $sessionId);
}
public function gc($maxlifetime): int
{
return 0;
}
public function open($savePath, $sessionName): bool { return true; }
public function close(): bool { return true; }
}
// 使用自定义Session处理器
$memcached = new Memcached();
$memcached->addServers([
[‘192.168.1.101’, 11211],
[‘192.168.1.102’, 11211],
]);
$handler = new MemcachedSessionHandler($memcached, 1800);
session_set_save_handler($handler, true);
session_start();
$_SESSION[‘user_id’] = 1001;
?>
4.3 Memcached数据库数据缓存案例
4.3.1 商品缓存案例
memcached = new Memcached(‘product_cache_pool’);
if (!count($this->memcached->getServerList())) {
$this->memcached->addServers($servers);
}
$this->memcached->setOptions([
Memcached::OPT_DISTRIBUTION => Memcached::DISTRIBUTION_CONSISTENT,
Memcached::OPT_LIBKETAMA_COMPATIBLE => true,
]);
}
public function getProduct(int $productId): ?array
{
$key = $this->prefix . $productId;
$product = $this->memcached->get($key);
if ($product === false) {
$product = $this->loadProductFromDatabase($productId);
if ($product !== null) {
$this->memcached->set($key, $product, $this->defaultExpire);
}
}
return $product;
}
public function getProducts(array $productIds): array
{
$keys = [];
foreach ($productIds as $id) {
$keys[$id] = $this->prefix . $id;
}
$cached = $this->memcached->getMulti(array_values($keys));
$result = [];
foreach ($productIds as $id) {
$key = $keys[$id];
if (isset($cached[$key])) {
$result[$id] = $cached[$key];
}
}
return $result;
}
private function loadProductFromDatabase(int $productId): ?array
{
return [
‘id’ => $productId,
‘name’ => “商品{$productId}”,
‘price’ => rand(100, 1000),
];
}
}
// 使用示例
$cache = new ProductCacheService([
[‘192.168.1.101’, 11211],
[‘192.168.1.102’, 11211],
]);
$product = $cache->getProduct(1);
print_r($product);
$products = $cache->getProducts([1, 2, 3]);
print_r($products);
?>
Part05-风哥经验总结与分享
5.1 Memcached数据库PHP客户端最佳实践
5.1.1 客户端选择建议
- 推荐使用Memcached扩展,功能完善、支持一致性哈希
- 避免使用Memcache扩展,功能有限
- 使用持久连接提高性能
5.1.2 配置建议
# 1. 必须启用一致性哈希
$memcached->setOption(Memcached::OPT_DISTRIBUTION,
Memcached::DISTRIBUTION_CONSISTENT);
$memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
# 2. 合理设置超时
$memcached->setOption(Memcached::OPT_CONNECT_TIMEOUT, 3000);
# 3. 使用持久连接
$memcached = new Memcached(‘persistent_pool_id’);
# 4. 启用压缩
$memcached->setOption(Memcached::OPT_COMPRESSION, true);
# 5. 配置故障处理
$memcached->setOption(Memcached::OPT_SERVER_FAILURE_LIMIT, 3);
5.2 Memcached数据库性能调优建议
5.2.1 性能优化要点
- 使用持久连接减少连接开销
- 批量操作减少网络请求
- 合理设置Key前缀便于管理
- 控制Value大小,避免存储大对象
- 使用igbinary序列化提高性能
5.2.2 常见性能问题
# 1. 连接超时
解决:检查网络、增加超时时间、使用持久连接
# 2. 缓存穿透
解决:缓存空值、使用布隆过滤器
# 3. 缓存雪崩
解决:设置随机过期时间、使用互斥锁
# 4. 热点Key
解决:分散Key、增加本地缓存
# 5. 内存不足
解决:增加内存、优化过期时间
5.3 Memcached数据库PHP集成常见问题
5.3.1 连接问题排查
# 问题:无法连接到Memcached服务器
// 1. 检查服务器是否运行
$ telnet 192.168.1.101 11211
// 2. 检查防火墙
$ firewall-cmd –list-ports
// 3. 检查PHP扩展
$ php -m | grep memcached
// 4. 检查连接状态
$memcached = new Memcached();
$memcached->addServer(‘192.168.1.101’, 11211);
$stats = $memcached->getStats();
if (empty($stats)) {
echo “连接失败\n”;
} else {
echo “连接成功\n”;
}
5.3.2 序列化问题
# 问题:对象无法正确序列化
# 解决:使用JSON或实现Serializable接口
// 方式1:使用JSON
$data = json_encode($object);
$memcached->set(‘key’, $data, 3600);
// 方式2:转换为数组
$data = (array) $object;
$memcached->set(‘key’, $data, 3600);
// 方式3:使用igbinary(性能更好)
$memcached->setOption(Memcached::OPT_SERIALIZER,
Memcached::SERIALIZER_IGBINARY);
本文由风哥教程整理发布,仅用于学习测试使用,转载注明出处:http://www.fgedu.net.cn/10327.html
