1:使用Redis緩存的優化思路
redis的使用場景很多,僅說下本人所用的一個場景:
1.1對于大量的資料讀取,為了緩解資料庫的壓力将一些不經常變化的而又讀取頻繁的資料存入redis緩存
大緻思路如下:執行一個查詢
1.2首先判斷緩存中是否存在,如存在直接從Redis緩存中擷取。
1.3如果Redis緩存中不存在,實時讀取資料庫資料,同時寫入緩存(并設定緩存失效的時間)。
1.4缺點,如果直接修改了資料庫的資料而又沒有更新緩存,在緩存失效的時間内将導緻讀取的Redis緩存是錯誤的資料。
2:Redis傻瓜式安裝
2.1輕按兩下執行redis-2.4.6-setup-64-bit.exe程式(下載下傳位址:https://github.com/dmajkic/redis/downloads)
2.2可以将此服務設定為windows系統服務:
2.3測試是否安裝成功:
再回到redis檔案夾下,找到redis-cli.exe檔案,它就是Redis用戶端程式。打開,輸入:
Set test 123
即在Redis中插入了一條key為test,value為123的資料,繼續輸入:get test
得到value儲存的資料123。
如果想知道Redis中一共儲存了多少條資料,則可以使用:keys * 來查詢:
3:asp.net使用Redis緩存簡單示例
3.1測試Demo的結構
3.2添加引用
3.3将參數寫入配置檔案
<appSettings>
<add key="WriteServerList" value="127.0.0.1:6379" />
<add key="ReadServerList" value="127.0.0.1:6379" />
<add key="MaxWritePoolSize" value="60" />
<add key="MaxReadPoolSize" value="60" />
<add key="AutoStart" value="true" />
<add key="LocalCacheTime" value="1800" />
<add key="RecordeLog" value="false" />
</appSettings>
3.4讀取配置檔案參數類
public class RedisConfigInfo
{
public static string WriteServerList = ConfigurationManager.AppSettings["WriteServerList"];
public static string ReadServerList = ConfigurationManager.AppSettings["ReadServerList"];
public static int MaxWritePoolSize = Convert.ToInt32(ConfigurationManager.AppSettings["MaxWritePoolSize"]);
public static int MaxReadPoolSize = Convert.ToInt32(ConfigurationManager.AppSettings["MaxReadPoolSize"]);
public static int LocalCacheTime = Convert.ToInt32(ConfigurationManager.AppSettings["LocalCacheTime"]);
public static bool AutoStart = ConfigurationManager.AppSettings["AutoStart"].Equals("true") ? true : false;
}
3.5連接配接Redis,以及其他的一些操作類
View Code
3.6測試頁面前背景代碼
<form id="form1" runat="server">
<div>
<asp:Label runat="server" ID="lbtest"></asp:Label>
<asp:Button runat="server" ID ="btn1" OnClick="btn1_Click" Text="擷取測試資料"/>
</div>
</form>
protected void btn1_Click(object sender, EventArgs e)
{
string UserName;
//讀取資料,如果緩存存在直接從緩存中讀取,否則從資料庫讀取然後寫入redis
using (var redisClient = RedisManager.GetClient())
{
UserName = redisClient.Get<string>("UserInfo_123");
if (string.IsNullOrEmpty(UserName)) //初始化緩存
{
//TODO 從資料庫中擷取資料,并寫入緩存
UserName = "張三";
redisClient.Set<string>("UserInfo_123", UserName, DateTime.Now.AddSeconds(10));
lbtest.Text = "資料庫資料:" + "張三";
return;
}
lbtest.Text = "Redis緩存資料:" + UserName;
}
}
測試結果圖
首次通路緩存中資料不存在,擷取資料并寫入緩存,并設定有效期10秒