我一直在读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']
)发送数据,这是搜索的参数。
所以我想做的是
第一次;
result_$_POST['restID']
第二次;
result_$_POST['restID']
存在,请检入redis 由于
答案 0 :(得分:0)
您有一些问题,第一$redis
必须在功能范围内。
接下来,您要保存并检索整个json字符串:
function getMenu ($connection) {
// Initiate redis instance
$redis = new Redis();
// Connect to elasticache instance
$redis->connect('redis-001.xxx.0001.euxw1.cache.amazonaws.com', 6379);
$restaurant_id = $_POST['restID'];
//check for redis cached data
if($redis->exists('menu_' . $restaurant_id)) {
// read json string from redit
$json = $redis->get('menu_' . $restaurant_id);
}else{
//if not in redis, do query
$data = [];
try {
// Menu category & items query
// array to store results
$query = "...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;
}
}
$data['success'] = true;
//create json string
$json = json_encode($data);
//save in redis for latter access
//probably you want to set expiry here as well, in case values change
$redis->set('menu_' . $restaurant_id, $json);
} catch (Exception $e){
$data = [];
$data['success'] = false;
$data['message'] = $e->getMessage();
$json = json_encode($data);
}
}
//echo json
header('Content-Type: application/json');
echo $json;
exit;
}