使用composer安装 composer require predis/predis,.env加入如下配置:
[REDIS]
HOST=127.0.0.1
scheme=tcp
PORT=6379
CACHE_DB=0
TOKEN_DB=1
PASSWORD=admin
config下redis配置文件redis.php
<?php
//Redis配置文件
return [
'scheme' => env('redis.scheme', 'tcp'),
'host' => env('redis.host', '127.0.0.1'),
'port' => env('redis.port', '6379'),
'token' => env('redis.token_db', '1'), // token数据库:默认0~15个
'cache' => env('redis.cache_db', '0'), // 缓存数据库
'password' => env('redis.password', ''),
];
直接使用
use Predis\Client;
$redis = new Client([
'scheme' => config('redis.scheme'),
'host' => config('redis.host'),
'port' => config('redis.port'),
'cache' => config('redis.cache'),
'password' => config('redis.password'),
]);
print_r($redis->set('test','123'));
封装服务类使用
<?php
namespace common\Utils;
use Predis\Client;
class Redis
{
/**
* 静态调用redis
*/
public function __construct(){
$this->redis = new Client([
'scheme' => config('redis.scheme'),
'host' => config('redis.host'),
'port' => config('redis.port'),
'cache' => config('redis.cache'),
'password' => config('redis.password'),
]);
}
/**
* 如果不传入$host和$port默认读取Laravel环境变量的参数
* redis Set/setex封装,可直接传入数组,可设置过期时间 written:yangxingyi
*/
public function set($key,$value,$expire=0,$host='',$port=''){
if(!$key||!$value) return false;
$host = $host?$host:getenv('REDIS_HOST');
$port = $port?$port:getenv('REDIS_PORT');
$value = is_array($value)?json_encode($value):$value;
return $expire>0? $this->redis->setex(getenv('REDIS_PREFIX').$key, $expire,$value): $this->redis->set(getenv('REDIS_PREFIX').$key,$value);
}
/**
* redis get封装,如果传入的是数组,返回的也是数组,同理字符串 written:yangxingyi
*/
public function get($key,$host='',$port=''){
$host = $host?$host:getenv('REDIS_HOST');
$port = $port?$port:getenv('REDIS_PORT');
$result = $this->redis->get(getenv('REDIS_PREFIX').$key);
return is_null(json_decode($result))?$result:json_decode($result,true);
}
}
版权声明:本文为博主原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。