標籤:
要安全的批量pop資料,有兩個辦法:
1、用事務(不用事務的話可能導致重複讀。ServiceStack的pipeline是沒有內建事務的。)
2、執行lua指令碼
我這裡提供用事務的實現方法:
public static string ReadLine(RedisNativeClient cln){MethodInfo mi = cln.GetType().GetMethod("ReadLine", BindingFlags.NonPublic | BindingFlags.Instance);string ret = (string)mi.Invoke(cln, new object[] { });return ret;}public static List<string> BatchDequeue(RedisNativeClient cln, string listID, int max_count){List<string> ret = new List<string>();var uListId = Encoding.UTF8.GetBytes(listID);var pipeline = cln.CreatePipelineCommand();pipeline.WriteCommand(Commands.Multi);pipeline.WriteCommand(Commands.LRange, uListId, Encoding.UTF8.GetBytes("0"), Encoding.UTF8.GetBytes((max_count - 1).ToString()));pipeline.WriteCommand(Commands.LTrim, uListId, Encoding.UTF8.GetBytes(max_count.ToString()), Encoding.UTF8.GetBytes("-1"));pipeline.WriteCommand(Commands.Exec);pipeline.Flush();var a1 = ReadLine(cln);//忽略Multi的OKvar a2 = ReadLine(cln);//忽略LRANGE的QUEUEDvar a3 = ReadLine(cln);//忽略LTRIM的QUEUEDvar a4 = ReadLine(cln);//忽略*2var b = cln.ReceiveMessages();foreach (var item in b){string ss = Encoding.UTF8.GetString(item);ret.Add(ss);}ReadLine(cln);//忽略EXEC的OKreturn ret;}
[C#] ServiceStack.Redis如何批量的pop資料?