配置
修改 /config/properties/cache.php 文件
return [
'redis' => [
'name' => 'redis',
'uri' => [
'127.0.0.1:6379'
],
'minActive' => 8,
'maxActive' => 8,
'maxWait' => 8,
'maxWaitTime' => 3,
'maxIdleTime' => 60,
'timeout' => 8,
'db' => 0,
'prefix' => '',
'serialize' => 0,
],
'demoRedis' => [
'db' => 2,
'prefix' => 'demo_redis_',
]
];
redis可以配置多个实例,相同的配置仅需要在第一个实例配置一次即可
基本用法
获取redis对象:
- 通过cache()函数
cache()->get('google');
- 通过注入的方法:Inject(“实例名”),不填则使用默认
/**
* @Inject()
* @var \Swoft\Redis\Redis
*/
private $redis;
获取到redis对象后就可以调用下面的方法操作redis
class RedisController
{
/**
* @Inject()
* @var \Swoft\Redis\Redis
*/
private $redis;
/**
* @Inject("demoRedis")
* @var \Swoft\Redis\Redis
*/
private $demoRedis;
public function set(){
return $this->redis->set('apple','www.apple.com');
}
public function get(){
return cache()->get('google');
}
public function set2(){
return $this->demoRedis->set('google','www.google.com');
}
public function get2(){
return $this->demoRedis->get('google');
}
public function hSet(){
return $this->redis->hSet('website','google','www.google.com');
}
public function hGet(){
return $this->redis->hGet('website','google');
}
public function hMset(){
$websites = [
'sina' => 'www.sina.com.cn',
'baidu' => 'www.baidu.com'
];
return cache()->hMset('website',$websites);
}
public function hMget(){
return cache()->hMget('website',['baidu','google']);
}
}
实际应用
1. 队列操作,队列存放10条商品记录,每次插入一条新记录就会删除掉一条最老的记录
/**
* @return array
*/
public function queuein(){
//$data 模拟从数据库中查询出的数据
$data = [
'id' => rand(1,9999),
'goods_name' => '商品'.rand(0,99999),
'create_time' => date('Y-m-d')
];
$this->redis->lPush('goods',json_encode($data));
$this->redis->lTrim('goods',0,10);
$goods = array();
foreach($this->redis->lRange('goods',0,10) as $item){
$goods[] = json_decode($item);
}
return $goods;
}
2. 图片点赞,如果redis中存在该图片记录,则对应的赞 +1,如不存在则从数据库中查出然后存入redis
/**
* @RequestMapping(route="thumb/{id}")
*/
public function thumb($id){
if($this->redis->exists('img_'.$id)){
$this->redis->hIncrBy('img_'.$id,'img_prise',1);
}else{
//$data 模拟从数据库中查询出的数据
$data = [
'img_id' => $id,
'img_prise' => rand(1,999),
'img_url' => md5(rand(999,99999))
];
$this->redis->hMset('img_'.$id,$data);
}
return $this->redis->hMget('img_'.$id, ['img_id','img_prise','img_url']);
}