PHP 连接示例

最近更新时间:2025-08-19 14:48:51

我的收藏

运行前必备

下载客户端 phpredis
说明:
若使用 TencentOS ,则可以使用yum install php-pecl-redis命令安装 phpredis。

示例代码

<?php
/**
* Tencent Cloud Redis Connection and Operation Example
* Documentation: https://github.com/phpredis/phpredis
*/
// Redis connection configuration
$host = "192.xx.xx.26"; // Redis instance private IP
$port = 6379; // Redis port
$instanceid = "crs-xxxxxxxx"; // Instance ID
$pwd = "your password"; // Instance password

// Create Redis client instance
$redis = new Redis();

// 1. Connect to Redis server
if (!$redis->connect($host, $port)) {
die("Connection failed: " . $redis->getLastError());
}

// 2. Authentication (Tencent Cloud format: instanceid:password)
$authString = $instanceid . ":" . $pwd;
if (!$redis->auth($authString)) {
die("Authentication failed: " . $redis->getLastError());
}

// 3. Key-value operation example
$key = "redis";
$value = "tencent";

// Set key-value pair
if (!$redis->set($key, $value)) {
die("Set key failed: " . $redis->getLastError());
}
echo "Successfully set key: $key, value: $value\\n";

// Get value by key
$result = $redis->get($key);
if ($result === false) {
die("Get key failed: " . $redis->getLastError());
}
echo "Retrieved key: $key, value: " . $result . "\\n";

// 4. Close connection when done (optional)
$redis->close();
?>

运行结果

说明:
若连接过程中出现异常,请参见 内网无法连接定位指南 处理。