2022-02-18

[OpenSource] 使用 Azure Table Storage 自己寫一個 KeyValue 的簡單的快取服務

這是一個實驗計畫,我不建議你商用,但是我自己已經商用了:P ,主要是因為為了測試我之前寫的一個 library - No2verse.AzureTable 

因為做的專案也有一些需求,就是他需要一些可以做快取的需要,而且他只會 Key Value 存取,當然也可以用 Redis ,但是我就是客家人本性?

也不完全是,只是因為我覺得 Azure Table Storage 是一個值得研究的技術低價好用。


home template from : https://codepen.io/toomuchome/pen/QZPYqm


1. 就 open source ,所以你可以到這裡下載 source code:  https://github.com/donma/Tatakosan

2. 然後你要去   Azure Table Storage  開戶,拿到 connection string  



3. 之後就是開啟專案的  Startup.cs :


/// <summary>
/// Azure Blob Table Connection String.
/// </summary>
public static readonly string _BlobConnectionString = "DefaultEndpointsProtocol=https;AccountName=...";
/// <summary>
/// /api/Op/ClearPool?token=token 的token
/// </summary>
public readonly static string ClearToken = "token";
public readonly static string HashToken = "TATAKOSAN";
/// <summary>
/// 五分鐘請檢查一下快取有沒有過期
/// </summary>
private readonly static int RecycleMinutes = 5;
/// <summary>
/// 如果 60 秒,都沒有人請求,在進行回收
/// </summary>
private readonly static int HowManySecondsNoDataRequest = 60;
/// <summary>
/// 如果多少分鐘沒有人存取就回收
/// default : 4hr * 60=2400;
/// </summary>
private readonly static int KeepMinutesInMemory = 2400;

4.設定完之後,就可以 去看一下 swagger 



大概就是這樣 剩下來就是 處理 每一個 操作時候的 Sign 需要透過 MD5 做 hash 一些資料進行驗證

code:

data.Sign = ToMD5(data.Table + data.Group + data.Id + ",TATAKOSAN");
var request =new HttpRequestMessage(HttpMethod.Post, new Uri($"http://tatakosan.ina9.win/api/Op/Update"))
{
Content = new StringContent(JsonConvert.SerializeObject(data), Encoding.UTF8, "application/json"),
};
var response = await client.SendAsync(request);
if (response.IsSuccessStatusCode)
{
var result = await response.Content.ReadAsStringAsync();
return JsonConvert.DeserializeObject<Response<string>>(result);
}
public static string ToMD5(string input, string salt = "no2don")
{
var x = new MD5CryptoServiceProvider();
byte[] bs = Encoding.UTF8.GetBytes(input + salt);
bs = x.ComputeHash(bs);
var s = new System.Text.StringBuilder();
foreach (byte b in bs)
{
s.Append(b.ToString("x2").ToLower());
}
string password = s.ToString();
return password;
}
view raw tomd5.cs hosted with ❤ by GitHub

簡單結論一下,因為目前真的只是拿來做快取還有一些不是很重要的資料,掉了也會有其他手段處理,所以用起來就還算順手簡單

就看看需求吧自行取用 :)