php 连接redis【单机方式】 【集群方式】【redis连接池】

2 篇文章 0 订阅
本文介绍了如何在PHP中使用Redis进行单机连接、集群配置以及连接池的实现,包括连接建立、认证、数据操作和连接释放,以优化资源利用。
摘要由CSDN通过智能技术生成
单机方式

      

​
$redis = new \Redis();  // 连接 Redis 服务器 

$redis->connect('127.0.0.1', 6379);

$redis->auth('your_redis_password');// 如果 Redis 服务器设置了密码,需要进行认证

$redis->set('test_key', 'Hello Redis!'); // 设置一个键值对

$value = $redis->get('test_key');/ /获取键对应的值

echo $value; // 输出:Hello Redis!

$redis->close();// 关闭连接

​
集群方式

       

​
        $serv = ['127.0.0.0:6379'];

        $pass = 'password';

        try {

                $redis = new RedisCluster(null, $serv, 2, 2, true, $pass);

                $set = $redis->set("test1","value");

                $get = $redis->get('test1');

                 var_dump($get);

        } catch (RedisClusterException $e) {

                 var_dump($e->getMessage());        

        }

​
redis连接池

 redis的连接和断开都会消耗资源,最好把创建的redis连接,放到一个连接池中共享。

<?php

class MFacade_RedisConnectionPool {
    private $connections = [];
    private $maxConnections;
    private $host;
    private $port;
    private $auth;
    private $idleTimeout;

    public function __construct($host, $port, $auth,$maxConnections, $idleTimeout = 60) {
        $this->host = $host;
        $this->port = $port;
        $this->auth = $auth;
        $this->maxConnections = $maxConnections;
        $this->idleTimeout = $idleTimeout;
    }

    public function getConnection() {
        // 检查连接池中是否有可用连接
        foreach ($this->connections as $index => $connection) {
            if ($this->isConnectionValid($connection)) {
                unset($this->connections[$index]);
                return $connection['redis'];
            }
        }

        // 创建新的连接
        if (count($this->connections) < $this->maxConnections) {
            $redis = new \Redis();
            $redis->connect($this->host, $this->port);
            $redis->auth($this->auth);
            $this->connections[] = ['redis' => $redis, 'last_used_time' => time()]; // 记录连接的最后使用时间
            return $redis;
        }

        // 连接池已满,无法提供连接
        return null;
    }

    public function releaseConnection($redis) {
        foreach ($this->connections as &$connection) {
            if ($connection['redis'] === $redis) {
                $connection['last_used_time'] = time(); // 更新连接的最后使用时间
                break;
            }
        }
    }

    public function closeAllConnections() {
        foreach ($this->connections as $connection) {
            $connection['redis']->close();
        }
        $this->connections = [];
    }

    private function isConnectionValid($connection) {
        // 检查连接是否超时
        $lastUsedTime = $connection['last_used_time'] ?: time();
        return (time() - $lastUsedTime) <= $this->idleTimeout;
    }
}

$pool = new RedisConnectionPool('127.0.0.1', 6379, "password",5, 30); // 设置空闲超时时间为 30 秒

$redis1 = $pool->getConnection();
if ($redis1) {
    $redis1->set('key1', 'value1');
    echo $redis1->get('key1') . "\n";
    $pool->releaseConnection($redis1);
}

$redis2 = $pool->getConnection();
if ($redis2) {
    $redis2->set('key2', 'value2');
    echo $redis2->get('key2') . "\n";
    $pool->releaseConnection($redis2);
}

// 关闭连接池中的所有连接
$pool->closeAllConnections();

  • 8
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值