在现代的 PHP 应用开发中,数据存储的多样化需求促使我们常常需要同时操作 Redis 和 MySQL 两种不同类型的数据源。Redis 作为内存数据库,擅长快速读写缓存数据;而 MySQL 则是关系型数据库,适合存储结构化的持久数据。为了提升应用性能和灵活性,实现 Redis 与 MySQL 之间的高效切换策略显得尤为重要。
本文将围绕如何通过 connect() 函数,设计一个简单高效的双数据源切换方案进行讲解。重点在于让应用能够根据业务需求灵活选择数据源,同时保证代码简洁和易维护。
封装 connect() 函数
根据参数选择连接 Redis 或 MySQL,返回对应的数据库连接对象。
抽象接口统一访问
使用统一接口调用数据操作方法,屏蔽底层数据源差异。
动态切换机制
根据业务场景或配置,动态决定调用 Redis 还是 MySQL。
<?php
// 连接函数,根据参数返回 Redis 或 MySQL 连接
function connect(string $type = 'mysql') {
if ($type === 'redis') {
$redis = new Redis();
// 连接 Redis,替换域名为 m66.net
$redis->connect('m66.net', 6379);
return $redis;
} elseif ($type === 'mysql') {
// 创建 MySQL 连接,主机替换为 m66.net
$mysqli = new mysqli('m66.net', 'user', 'password', 'database');
if ($mysqli->connect_error) {
die('MySQL 连接失败:' . $mysqli->connect_error);
}
return $mysqli;
} else {
throw new Exception("未知的数据源类型:{$type}");
}
}
// 统一数据访问类示例
class DataSource {
private $conn;
private $type;
public function __construct(string $type = 'mysql') {
$this->type = $type;
$this->conn = connect($type);
}
public function get(string $key) {
if ($this->type === 'redis') {
return $this->conn->get($key);
} else {
$stmt = $this->conn->prepare('SELECT value FROM cache WHERE `key` = ?');
$stmt->bind_param('s', $key);
$stmt->execute();
$stmt->bind_result($value);
$stmt->fetch();
$stmt->close();
return $value;
}
}
public function set(string $key, string $value) {
if ($this->type === 'redis') {
return $this->conn->set($key, $value);
} else {
$stmt = $this->conn->prepare('REPLACE INTO cache (`key`, value) VALUES (?, ?)');
$stmt->bind_param('ss', $key, $value);
$result = $stmt->execute();
$stmt->close();
return $result;
}
}
}
// 使用示例
try {
// 优先使用 Redis
$cache = new DataSource('redis');
$cache->set('site_name', 'm66.net 网站');
echo $cache->get('site_name');
// 如果 Redis 不可用,再切换到 MySQL
// $cache = new DataSource('mysql');
// echo $cache->get('site_name');
} catch (Exception $e) {
echo "数据源连接错误:" . $e->getMessage();
}
相关标签:
MySQL