【发布时间】:2015-12-02 23:54:24
【问题描述】:
我一直在阅读 redis,但无法决定如何保存和检索我的数据。下面是一个从 MySQL DB 中获取数据的函数;
// Initiate redis instance
$redis = new Redis();
// Connect to elasticache instance
$redis->connect('redis-001.xxx.0001.euxw1.cache.amazonaws.com', 6379);
function getMenu ($connection) {
$data = array();
$restaurant_id = $_POST['restID'];
try {
if($redis->exists('menu_uniqueID')) {
// read from redis and into 2D array
$data['data'][$row['cat_name']][] = $redis->get('menu_uniqueID');
$data['success'] = true;
echo json_encode($data);
exit;
} else {
// Menu category & items query
// array to store results
$query = "SELECT
cat.name AS cat_name,
i.id AS item_id,
i.name AS name,
i.description AS description,
i.price AS price
FROM menu_categories AS cat
INNER JOIN menu_items AS i
ON cat.id = i.cat_id
WHERE i.rest_id = $restaurant_id";
$result = mysqli_query($connection, $query);
if($result) {
while($row = mysqli_fetch_assoc($result)) {
// read into 2D array
$data['data'][$row['cat_name']][] = $row;
// save into Redis
$redis->set('menu_uniqueID', json_encode($row));
}
}
$data['success'] = true;
echo json_encode($data);
exit;
}
} catch (Exception $e){
$data = array();
$data['success'] = false;
$data['message'] = $e->getMessage();
echo json_encode($data);
exit;
}
}
如您所见,我正在检索一个二维数组并将其传递回我的前端 (AngularJS) t 使用 ng-repeat 进行消费和显示
我希望保存此查询的结果。您还可以看到我从我的前端 ($_POST['restID']) 发送数据,这是用于搜索的参数。
所以我想做的是
第一次;
- $query 照常进行
- 用
result_$_POST['restID']键将$query结果保存到Redis中
第二次;
- 如果键
result_$_POST['restID']存在,则签入 redis - 如果存在,则 JSON 编码并传回前端
谢谢
【问题讨论】:
-
redis 是键值存储,所以只需将 json 字符串保存在
$_POST['restID']键下。流程:检查redis,如果存在则回显结果,否则执行SQL查询,创建json字符串,保存在redis中然后回显 -
如何保存是我所追求的;
HASH?SET?LIST?任何机会您都可以显示一些代码 -
好吧,看起来您只是将 is 用作缓存,因此只需保存 json 字符串(作为字符串)-如果您显示用于访问 redis 的代码,我可以写一个答案
-
检查我的编辑、设置和获取为
STRING和json_encode