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']); }
相關文章
相關標籤/搜索