Swoft 缓存及Redis使用

配置php

修改 /config/properties/cache.php 文件web

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

基本用法数据库

获取redis对象:json

  • 经过cache()函数
cache()->get('google');
  • 经过注入的方法:Inject(“实例名”),不填则使用默认
/** * @Inject() * @var \Swoft\Redis\Redis */
private $redis;

获取到redis对象后就能够调用下面的方法操做redisapp

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条商品记录,每次插入一条新记录就会删除掉一条最老的记录this

    /** * @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,如不存在则从数据库中查出而后存入redisgoogle

    /** * @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']); }
相关文章
相关标签/搜索