晓夏

北漂的女孩

Good Luck To You!

redis有序集合和哈希联合使用

浏览量:440

防止数据库挂掉,就不应该把数据放在缓存里面,下面就是我经常使用的一种方法

<?php
/**
 * 按照所属分类查询商品
 * @param int $cat_id 分类id
 * @param int $page 页数
 * @param int $limit 条数
 * @param string $sort 排序
 * @return bool  array  数组
 * author        : lianghuiju@chuchujie.com
 * function_name : get_mall_goods
 * date          :2016-08-19
 * description   :
 */
public function get_mall_goods($cat_id, $page = 1, $limit = 20, $sort = 'sort_order')
{
    $catgory_id = (int)trim($cat_id);
    $zset_key = "good_ids-zset:" . $catgory_id . ':' . $sort;
    $hash_key = "good_ids-hash:" . $catgory_id . ':' . $sort;
    $count_key = "count_goods";
    $this->load->driver('cache');
    $start = ($page - 1) * $limit;
    $end = $start + $limit - 1;
    $where = array(
        'cat_id' => $cat_id,
        'is_on_sale' => '1',
        'is_alone_sale' => '1',
        'is_delete' => '0',
        'is_team' => '1',
    );
    //按照sort从小到大排序
    $goodids = $this->cache->redis->Zrange($zset_key, $start, $end);
    //获取总页数
    $count_goods = $this->cache->redis->get($count_key);
    $query = array();
    if ($count_goods) {
        $query['page'] = $count_goods;
    } else {
        $count = $this->find($where, "count(*) as count_goods");
        $max_page = ($count > 0) ? ceil($count['count_goods'] / $limit) : 1;
        $this->cache->redis->save($count_key, $max_page, 600);
        $query['page'] = $max_page;
    }
    if (!empty($goodids)) {
        foreach ($goodids as $id) {
            //从缓存里面读取详情信息
            $json_array = $this->cache->redis->hGet($hash_key, $id);
            $query['data'][] = json_decode($json_array, TRUE);
        }
        return $query;
    }
    $data = $this->select($where, " * ", $sort, $page, $limit);
    $goods_info = array();
    foreach ($data as $row) {
        //写入缓存
        $this->cache->redis->zAdd($zset_key, $row['sort_order'], $row['goods_id']);
        $data_json = json_encode($row, JSON_UNESCAPED_UNICODE);
        $this->cache->redis->hSet($hash_key, $row['goods_id'], $data_json);
        $goods_info['data'][] = $row;
    }
    $goods_info['page'] = $query['page'];
    return $goods_info;
}


神回复

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。