学习总结
如果想在larave中使用redis,需要引入use Illuminate\Support\Facades\Redis;
类,然后进行redis的操作
设置redis数据存储的过期时间使用Redis::setex(key,ttl,value)
其中ttl是整数,按秒计算
使用json_decode('json字符串',true)
解码json字符串时,第二个参数设置为true解码的数据转换为数组,否则转换为对象
1.在phpstudy中下载redis服务
环境>工具>redis>更多

redis3.0.504是redis服务,下载
redisClient2.0.0是redis可视化存储工具,下载

下载后在服务中启动redis服务

2.php中安装redis扩展
在“环境”中选择所用的php版本,点“设置”

在“扩展组件”中打开redis扩展的开关

3.Shop控制器中的redis_test是redis的测试代码
<?php
namespace App\Http\Controllers\homes;
use App\Http\Controllers\Controller;
//引入数据库查询构造器,链式调用
use Illuminate\Support\Facades\DB;
//引入redis
use Illuminate\Support\Facades\Redis;
use Illuminate\Http\Request;
//商城相关
class Shop extends Controller
{
public function index()
{
$res = [];
$res['products'] = DB::table('product')->limit(12)->lists();
//存放显示的商品类别的编号
$cates = [];
if($res['products']){
$cates = array_column($res['products'],'cid');
}
//有选择的加载商品分类
$res['cates'] = DB::table('product_cate')->whereIn('id',$cates)->cate('id');
// echo '<pre>';
// print_r($res);
// exit;
return view('/homes/shop/index',$res);
}
public function list()
{
return view('/homes/shop/list');
}
public function detail(Request $req)
{
$pid =(int)$req->pid;
$res['product'] = DB::table('product')->where('id',$pid)->item();
$res['detail'] = DB::table('product_detail')->where('proid',$pid)->item();
// echo '<pre>';
// print_r($res);
// exit;
//如果数据库中有这条数据则渲染,否则跳转到商品首页
if($res['product'])
{
return view('/homes/shop/detail',$res);
}
else
{
return redirect('/homes/shop/index');
}
}
public function create_order(Request $req)
{
$pid = $req->pid;
}
//接入微信支付,形成微信支付二维码
public function wxpay()
{
}
//redis测试
public function redis_test(Request $req)
{
$pid =(int)$req->pid;
$redisPro = 'product_'.$pid;
//从redis取数据
$data = Redis::get($redisPro);
// var_dump($data);
if($data)
{
//从redis中取出的数据是json,转换为数组 ,第二个参数是true转换为数组,否则转换为对象
$res = json_decode($data,true);//
}
else
{
$res['product'] = DB::table('product')->where('id',$pid)->item();
$res['detail'] = DB::table('product_detail')->where('proid',$pid)->item();
//如果
if($res['product'])
{
// Redis::setex('key','过期时间(秒)','value')数据存入redis后,多少秒后删除
Redis::setex($redisPro,86400,json_encode($res));//存一天
//Redis::set('key','value'); 存入redis
// Redis::set($redisPro,json_encode($res));
}
else
{
return redirect('/homes/shop/index');
}
}
// echo '<pre>';
// print_r($res);
// exit;
return view('/homes/shop/detail',$res);
}
}
redis保存后,打开redisClient查看数据是否保存成功

页面刷新效果图
