1. 程式人生 > 實用技巧 >Redis 快取實現儲存和讀取歷史搜尋關鍵字

Redis 快取實現儲存和讀取歷史搜尋關鍵字

一、本案例涉及知識

  1. Layui
  2. Redis
  3. Vue.js
  4. jQuery Ajax

二、效果圖

三、功能實現

(一)使用 Layui 的樣式構建頁面
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Redis應用 - 搜尋歷史</title>
    <!-- 引入 Layui CSS -->
    <link rel="stylesheet" href="css/layui.css">
</head>
<body>
<div class="layui-form" style="width: 50%;margin-top: 20px;" id="app">
    <div class="layui-form-item">
        <label class="layui-form-label"></label>
        <div class="layui-input-block">
            <input type="text" class="layui-input">
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label"></label>
        <div class="layui-input-block">
            <button class="layui-btn">搜尋</button>
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label"></label>
        <div class="layui-input-block">
            搜尋歷史
        </div>
    </div>
    <div class="layui-form-item">
        <label class="layui-form-label"></label>
        <div class="layui-input-block">
            <span class="layui-badge layui-bg-gray" style="margin-left: 5px;">PHP</span>
            <span class="layui-badge layui-bg-gray" style="margin-left: 5px;">JavaScript</span>
        </div>
    </div>
</div>
<!-- 引入 jQuery -->
<script src="js/jquery-3.5.1.min.js"></script>
<!-- 引入 Layui JS -->
<script src="js/layui.js"></script>
<!-- 引入 Vue.js -->
<script src="js/vue.min.js"></script>
</body>
</html>
(二)點選搜尋時儲存本次搜尋的關鍵字

給文字框新增 Vue 雙向繫結

<input type="text" class="layui-input" v-model="keyword">

給搜尋按鈕新增點選事件

<button class="layui-btn" @click="addHistory()">搜尋</button>
<script type="text/javascript">
    var vm = new Vue({
        el: "#app",
        data: {
            keyword: ""
        },
        methods: {
            addHistory: function () {}
        }
    });
</script>

當文字框被輸入內容後,輸入的內容將繫結給 Vue 中 datakeyword 欄位。

點選搜尋按鈕時,觸發 addHistory() 函式,此函式將輸入的內容傳送給 PHP ,PHP 操作 Redis 將內容進行快取。

addHistory() 函式中:

addHistory: function () {
    $.ajax({
        url: "history.php",
        type: "GET",
        data: {type: 'add', keyword: this.keyword},
        success: function () {
        	// 請求成功後重新整理本頁面
            window.location.reload();
        }
    });
}

data 中傳值兩個欄位,type 表示本次請求的型別,其中 add 代表往快取中新增關鍵字,read 代表從快取中讀取關鍵字。

history.php 中:

<?php
$redis = new Redis();
$con = $redis->connect('localhost', 6379);
if (!$con) {
    echo 'Redis連線失敗';
}
// 接收請求型別引數的值
$type = $_GET['type'];
// 模擬使用者的id,因為每個使用者搜尋的內容不同,需要進行區分
$user_id = 'user-1';
// 如果請求型別為新增
if ($type == 'add') {
	// 接收輸入的關鍵字
    $keyword = $_GET['keyword'];
    // 讀取當前使用者佇列中儲存的關鍵字個數,即佇列的長度
    $len = $redis->llen($user_id);
    // 如果個數大於等於 5 個,則刪除最開始搜尋的關鍵字,加入最新搜尋的關鍵字
    if ($len >= 5) {
    	// 移除佇列左側的第一個關鍵字
        $redis->lPop($user_id);
        // 在佇列右側加入新的關鍵字
        $redis->rPush($user_id, $keyword);
    } else {
    	// 不多於 5 個直接在佇列右側加入新的關鍵字
        $redis->rPush($user_id, $keyword);
    }
}
(三)讀取並展示歷史搜尋的關鍵字

第二步中加入了當請求新增快取成功後會重新整理頁面的程式碼,

window.location.reload();

在這個基礎上,我們希望重新整理的同時執行另一個 Ajax 請求從 PHP 中操作 Redis 將所有的歷史搜尋關鍵字讀取出來並在頁面中展示。

所以在 Vue 中加入頁面載入完成自動呼叫getHistory()函式:

methods: {
    getHistory: function () {},
    addHistory: function () {
        $.ajax({
            url: "history.php",
            type: "GET",
            data: {type: 'add', keyword: this.keyword},
            success: function () {
                window.location.reload();
            }
        });
    }
},
// 頁面載入完成自動呼叫 getHistory()
created () {
    this.getHistory();
}

getHistory()函式中:

getHistory: function () {
    $.ajax({
        url: "history.php",
        type: "GET",
        data: {type: 'read'},
        success: function (r) {
        	// JSON.parse(r) 將讀取到的 json 字串轉為 json 物件
            vm.history = JSON.parse(r);
        }
    });
}

data 中傳值一個欄位,read 代表從快取中讀取關鍵字,請求成功後將返回的結果賦值給 Vue 中 datahistory 欄位。

history.php 中新增讀取操作:

// 如果請求型別為讀取
if ($type == 'read') {
	// 從佇列左側依次取出 5 個關鍵字
    $history = $redis->lrange($user_id, 0, 4);
    // 轉為 json 格式的資料並輸出到頁面中供 Ajax 使用
    echo json_encode($history, JSON_UNESCAPED_UNICODE);
}

將讀取到的資料成功賦值給 Vue 中 datahistory 欄位後,頁面中即可將資料迴圈輸出展示:

<span class="layui-badge layui-bg-gray" v-for="item in history" style="margin-left: 5px;">{{item}}</span>

連貫過程為:使用者輸入關鍵字並點選搜尋按鈕,Ajax 請求 PHP 操作 Redis 進行資料快取且快取成功後重新整理頁面,頁面重新整理後自動呼叫函式執行 Ajax 請求 PHP 操作 Redis 進行快取資料的讀取並返回於頁面中同時進行渲染展示。