第一种:perl redis扩展; 第二种:ThinkPHP缓存扩展; 第三种:predis扩展; 第四种:自己简单封装第一种;
四种方式的演示代码
public function test31 ( ) {
echo "<hr/>" ;
$redis = new \ Redis( ) ;
$redis - > connect ( '127.0.0.1' , 6379 ) ;
$redis - > auth ( '12345' ) ;
$redis - > select ( 2 ) ;
$redis - > set ( "testKey" , "Hello Redis++++(原始方式)" ) ;
echo $redis - > get ( "testKey" ) ;
echo "<hr/>" ;
Cache: : store ( 'redis' ) - > set ( 'name' , 'Hello Redis++++(框架缓存方式)' , 3600 ) ;
$name = Cache: : store ( 'redis' ) - > get ( 'name' ) ;
echo $name ;
echo "<hr/>框架直接存对象:<br/>" ;
$t_stock = TStock: : where ( 'id' , '=' , 1 ) - > find ( ) ;
Cache: : store ( 'redis' ) - > set ( 't_stock:1' , $t_stock ) ;
$t_stock_r = Cache: : store ( 'redis' ) - > get ( 't_stock:1' ) ;
var_dump ( $t_stock_r ) ;
echo "<hr/>" ;
$p_redis = new PredisClient ( ) ;
$config = [ 'scheme' = > 'tcp' , 'host' = > '127.0.0.1' , 'port' = > 6379 ] ;
$p_redis - > connect ( $config ) ;
$p_redis - > auth ( 12345 ) ;
$p_redis - > select ( 2 ) ;
$p_redis - > set ( 'name' , 'Hello Redis++++(predis方式)' ) ;
$name = $p_redis - > get ( 'name' ) ;
echo $name ;
echo "<hr/>" ;
Redis: : set ( 'key5' , 'Hello Redis++++(自定义静态代理方式)' ) ;
echo Redis: : get ( 'key5' ) ;
echo '<br/>' ;
echo Redis: : getInstance ( ) - > get ( 'key5' ) ;
}
自定义静态代理
<?php
namespace app\ facade ;
use think\ Facade ;
class Redis extends Facade
{
protected static function getFacadeClass ( )
{
return 'app\common\Redis' ;
}
}
简单封装连接
<?php
namespace app\ common ;
use \ think\ facade\ Config;
class Redis
{
static private $instance ;
public static function getInstance ( ) {
if ( ! self: : $instance instanceof \ Redis) {
$redis = new \ Redis;
$redis - > connect ( Config: : get ( 'cache.redis.host' ) , Config: : get ( 'cache.redis.port' ) ) ;
$redis - > auth ( Config: : get ( 'cache.redis.password' ) ) ;
$redis - > select ( Config: : get ( 'cache.redis.select' ) ) ;
self: : $instance = $redis ;
}
return self: : $instance ;
}
public function __call ( $method , $ages ) {
self: : getInstance ( ) ;
switch ( $count = count ( $ages ) ) {
case 0 :
return self: : $instance - > $method ( ) ;
break ;
case 1 :
return self: : $instance - > $method ( $ages [ 0 ] ) ;
break ;
case 2 :
return self: : $instance - > $method ( $ages [ 0 ] , $ages [ 1 ] ) ;
break ;
case 3 :
return self: : $instance - > $method ( $ages [ 0 ] , $ages [ 1 ] , $ages [ 2 ] ) ;
break ;
case 4 :
return self: : $instance - > $method ( $ages [ 0 ] , $ages [ 1 ] , $ages [ 2 ] , $ages [ 3 ] ) ;
break ;
default :
return '无法处理' ;
}
}
}