对于大型网站来说,redis是非常受欢迎的,运用redis缓存之后,网站瞬间可以提速n倍。那么php如何连接redis呢,下面是一个入门的范例代码。
$redis = new Redis(); //创建一个对象
$redis->connect('127.0.0.1',6379); //连接redis
$redis->select(0); //选择数据库(默认16个数据库,0-15,这个值可以在配置文件修改。)
$redis->set('a1', 'www.daixiaorui.com'); //往redis写入一条记录
echo $redis->get('a1'); //从redis中读取一条记录
?>
Redis的PHP字符串实例
//Connecting to Redis server on localhost
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo "Connection to server sucessfully";
//set the data in redis string
$redis->set("tutorial-name", "Redis tutorial");
// Get the stored data and print it
echo "Stored string in redis:: " + jedis.get("tutorial-name");
?>
当执行程序时,会产生下面的结果:
Connection to server sucessfully
Stored string in redis:: Redis tutorial
Redis的PHP列表示例
//Connecting to Redis server on localhost
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo "Connection to server sucessfully";
//store data in redis list
$redis->lpush("tutorial-list", "Redis");
$redis->lpush("tutorial-list", "Mongodb");
$redis->lpush("tutorial-list", "Mysql");
// Get the stored data and print it
$arList = $redis->lrange("tutorial-list", 0 ,5);
echo "Stored string in redis:: "
print_r($arList);
?>
当执行程序时,会产生下面的结果:
Connection to server sucessfully
Stored string in redis::
Redis
Mongodb
Mysql
Redis的PHP键例
//Connecting to Redis server on localhost
$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
echo "Connection to server sucessfully";
// Get the stored keys and print it
$arList = $redis->keys("*");
echo "Stored keys in redis:: "
print_r($arList);
?>
当执行程序时,会产生下面的结果:
Connection to server sucessfully
Stored string in redis::
tutorial-name
tutorial-list
就是这么简单,感觉有点像连接mysql数据库一样。运行以上代码前,请确认您的电脑是否已安装并启动redis服务;请确认php已安装redis扩展,这个具体请在phpinfo查看。如果没有安装,去官网下一个对应php版本的扩展即可。