Browse Source

改进Redis

懒得勤快 7 years ago
parent
commit
191791ce70

+ 1 - 1
Masuit.Tools.Core/Masuit.Tools.Core.csproj

@@ -2,7 +2,7 @@
 
   <PropertyGroup>
     <TargetFramework>netcoreapp2.0</TargetFramework>
-    <Version>1.9.5</Version>
+    <Version>1.9.5.1</Version>
     <Authors>懒得勤快</Authors>
     <Company>masuit.com</Company>
     <Description>包含一些常用的操作类,大都是静态类,加密解密,反射操作,硬件信息,字符串扩展方法,日期时间扩展操作,大文件拷贝,图像裁剪,html处理,验证码、NoSql等常用封装。

+ 3 - 16
Masuit.Tools.Core/NoSQL/RedisConnectionManager.cs

@@ -1,7 +1,6 @@
 using System;
 using System.Collections.Concurrent;
 using System.Threading.Tasks;
-using Masuit.Tools.Core.Net;
 using Masuit.Tools.Core.Systems;
 using StackExchange.Redis;
 
@@ -26,7 +25,7 @@ namespace Masuit.Tools.Core.NoSQL
         private static readonly ConcurrentDictionary<string, ConcurrentLimitedQueue<ConnectionMultiplexer>> ConnectionCache = new ConcurrentDictionary<string, ConcurrentLimitedQueue<ConnectionMultiplexer>>();
 
         /// <summary>
-        /// 单例获取
+        /// 对象池获取线程内唯一对象
         /// </summary>
         public static ConnectionMultiplexer Instance
         {
@@ -40,13 +39,7 @@ namespace Masuit.Tools.Core.NoSQL
                         queue.Enqueue(GetManager(RedisConnectionString));
                     });
                 }
-                ConnectionMultiplexer multiplexer;
-                if (CallContext<ConnectionMultiplexer>.GetData(RedisConnectionString) == null)
-                {
-                    queue.TryDequeue(out multiplexer);
-                    CallContext<ConnectionMultiplexer>.SetData(RedisConnectionString, multiplexer);
-                }
-                multiplexer = CallContext<ConnectionMultiplexer>.GetData(RedisConnectionString);
+                queue.TryDequeue(out var multiplexer);
                 return multiplexer;
             }
         }
@@ -66,13 +59,7 @@ namespace Masuit.Tools.Core.NoSQL
                     queue.Enqueue(GetManager(connectionString));
                 });
             }
-            ConnectionMultiplexer multiplexer;
-            if (CallContext<ConnectionMultiplexer>.GetData(connectionString) == null)
-            {
-                queue.TryDequeue(out multiplexer);
-                CallContext<ConnectionMultiplexer>.SetData(connectionString, multiplexer);
-            }
-            multiplexer = CallContext<ConnectionMultiplexer>.GetData(connectionString);
+            queue.TryDequeue(out var multiplexer);
             return multiplexer;
         }
 

+ 1 - 1
Masuit.Tools/Masuit.Tools.csproj

@@ -50,7 +50,7 @@
     </Reference>
     <Reference Include="Microsoft.CSharp" />
     <Reference Include="Newtonsoft.Json, Version=11.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
-      <HintPath>..\packages\Newtonsoft.Json.11.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
+      <HintPath>..\..\MyBlogs\packages\Newtonsoft.Json.11.0.2\lib\net45\Newtonsoft.Json.dll</HintPath>
     </Reference>
     <Reference Include="StackExchange.Redis, Version=1.2.4.0, Culture=neutral, processorArchitecture=MSIL">
       <HintPath>..\packages\StackExchange.Redis.1.2.4\lib\net45\StackExchange.Redis.dll</HintPath>

+ 19 - 19
Masuit.Tools/Net/WebExtension.cs

@@ -41,7 +41,7 @@ namespace Masuit.Tools.Net
 
         #region 写Session
 
-        static RedisHelper helper = new RedisHelper(1);
+        private static readonly RedisHelper Helper = RedisHelper.GetInstance(1);
         /// <summary>
         /// 写Session
         /// </summary>
@@ -83,7 +83,7 @@ namespace Masuit.Tools.Net
                 HttpCookie cookie = new HttpCookie(cookieName, sessionId);
                 HttpContext.Current.Response.Cookies.Add(cookie);
             }
-            return helper.SetString(sessionId, obj, TimeSpan.FromMinutes(expire)); //存储数据到缓存服务器,这里将字符串"my value"缓存,key 是"test"
+            return Helper.SetString(sessionId, obj, TimeSpan.FromMinutes(expire)); //存储数据到缓存服务器,这里将字符串"my value"缓存,key 是"test"
         }
 
         /// <summary>
@@ -111,7 +111,7 @@ namespace Masuit.Tools.Net
                 HttpCookie cookie = new HttpCookie(cookieName, sessionId);
                 HttpContext.Current.Response.Cookies.Add(cookie);
             }
-            return helper.SetString(sessionId, obj, TimeSpan.FromMinutes(expire)); //存储数据到缓存服务器,这里将字符串"my value"缓存,key 是"test"
+            return Helper.SetString(sessionId, obj, TimeSpan.FromMinutes(expire)); //存储数据到缓存服务器,这里将字符串"my value"缓存,key 是"test"
         }
 
         #endregion
@@ -146,10 +146,10 @@ namespace Masuit.Tools.Net
         /// <returns></returns> 
         public static T GetByRedis<T>(this HttpSessionState _, string key, int expire = 20) where T : class
         {
-            if (helper.KeyExists(key))
+            if (Helper.KeyExists(key))
             {
-                helper.Expire(key, TimeSpan.FromMinutes(expire));
-                return helper.GetString<T>(key);
+                Helper.Expire(key, TimeSpan.FromMinutes(expire));
+                return Helper.GetString<T>(key);
             }
             return default(T);
         }
@@ -164,10 +164,10 @@ namespace Masuit.Tools.Net
         /// <returns></returns>
         public static T GetByRedis<T>(this HttpSessionStateBase _, string key, int expire = 20) where T : class
         {
-            if (helper.KeyExists(key))
+            if (Helper.KeyExists(key))
             {
-                helper.Expire(key, TimeSpan.FromMinutes(expire));
-                return helper.GetString<T>(key);
+                Helper.Expire(key, TimeSpan.FromMinutes(expire));
+                return Helper.GetString<T>(key);
             }
             return default(T);
         }
@@ -188,10 +188,10 @@ namespace Masuit.Tools.Net
             }
             var key = HttpContext.Current.Request.Cookies[cookieName]?.Value;
             if (string.IsNullOrEmpty(key)) return default(T);
-            if (helper.KeyExists(key))
+            if (Helper.KeyExists(key))
             {
-                helper.Expire(key, TimeSpan.FromMinutes(expire));
-                return helper.GetString<T>(key);
+                Helper.Expire(key, TimeSpan.FromMinutes(expire));
+                return Helper.GetString<T>(key);
             }
             return default(T);
         }
@@ -212,10 +212,10 @@ namespace Masuit.Tools.Net
             }
             var key = HttpContext.Current.Request.Cookies[cookieName]?.Value;
             if (string.IsNullOrEmpty(key)) return default(T);
-            if (helper.KeyExists(key))
+            if (Helper.KeyExists(key))
             {
-                helper.Expire(key, TimeSpan.FromMinutes(expire));
-                return helper.GetString<T>(key);
+                Helper.Expire(key, TimeSpan.FromMinutes(expire));
+                return Helper.GetString<T>(key);
             }
             return default(T);
         }
@@ -235,7 +235,7 @@ namespace Masuit.Tools.Net
             var key = HttpContext.Current.Request.Cookies[cookieName]?.Value;
             if (string.IsNullOrEmpty(key)) return true;
             HttpContext.Current.Response.Cookies[cookieName].Expires = DateTime.Now.AddDays(-1);
-            return helper.DeleteKey(key);
+            return Helper.DeleteKey(key);
         }
 
         /// <summary>
@@ -246,7 +246,7 @@ namespace Masuit.Tools.Net
         /// <returns></returns>
         public static bool RemoveByRedis(this HttpSessionStateBase _, string key = "sessionId")
         {
-            return helper.DeleteKey(key);
+            return Helper.DeleteKey(key);
         }
 
         /// <summary>
@@ -264,7 +264,7 @@ namespace Masuit.Tools.Net
             var key = HttpContext.Current.Request.Cookies[cookieName]?.Value;
             if (string.IsNullOrEmpty(key)) return true;
             HttpContext.Current.Request.Cookies[cookieName].Expires = DateTime.Now.AddDays(-1);
-            return helper.DeleteKey(key);
+            return Helper.DeleteKey(key);
         }
 
         /// <summary>
@@ -275,7 +275,7 @@ namespace Masuit.Tools.Net
         /// <returns></returns>
         public static bool RemoveByRedis(this HttpSessionState _, string key = "sessionId")
         {
-            return helper.DeleteKey(key);
+            return Helper.DeleteKey(key);
         }
 
         #endregion

+ 3 - 18
Masuit.Tools/NoSQL/RedisConnectionManager.cs

@@ -1,7 +1,6 @@
 using System;
 using System.Collections.Concurrent;
 using System.Configuration;
-using System.Runtime.Remoting.Messaging;
 using System.Threading.Tasks;
 using Masuit.Tools.Systems;
 using StackExchange.Redis;
@@ -21,12 +20,10 @@ namespace Masuit.Tools.NoSQL
         /// </summary>
         public static readonly string RedisConnectionString = ConfigurationManager.ConnectionStrings["RedisHosts"]?.ConnectionString ?? "127.0.0.1:6379,allowadmin=true";
 
-        //private static readonly object Locker = new object();
-        //private static ConnectionMultiplexer _instance;
         private static readonly ConcurrentDictionary<string, ConcurrentLimitedQueue<ConnectionMultiplexer>> ConnectionCache = new ConcurrentDictionary<string, ConcurrentLimitedQueue<ConnectionMultiplexer>>();
 
         /// <summary>
-        /// 单例获取
+        /// 对象池获取线程内唯一对象
         /// </summary>
         public static ConnectionMultiplexer Instance
         {
@@ -40,13 +37,7 @@ namespace Masuit.Tools.NoSQL
                         queue.Enqueue(GetManager(RedisConnectionString));
                     });
                 }
-                ConnectionMultiplexer multiplexer;
-                if (CallContext.GetData(RedisConnectionString) == null)
-                {
-                    queue.TryDequeue(out multiplexer);
-                    CallContext.SetData(RedisConnectionString, multiplexer);
-                }
-                multiplexer = (ConnectionMultiplexer)CallContext.GetData(RedisConnectionString);
+                queue.TryDequeue(out var multiplexer);
                 return multiplexer;
             }
         }
@@ -66,13 +57,7 @@ namespace Masuit.Tools.NoSQL
                     queue.Enqueue(GetManager(connectionString));
                 });
             }
-            ConnectionMultiplexer multiplexer;
-            if (CallContext.GetData(connectionString) == null)
-            {
-                queue.TryDequeue(out multiplexer);
-                CallContext.SetData(connectionString, multiplexer);
-            }
-            multiplexer = (ConnectionMultiplexer)CallContext.GetData(connectionString);
+            queue.TryDequeue(out var multiplexer);
             return multiplexer;
         }
 

+ 2 - 2
Masuit.Tools/Properties/AssemblyInfo.cs

@@ -36,7 +36,7 @@ using System.Runtime.InteropServices;
 // 方法是按如下所示使用“*”: :
 // [assembly: AssemblyVersion("1.0.*")]
 
-[assembly: AssemblyVersion("1.9.5.0")]
-[assembly: AssemblyFileVersion("1.9.5.0")]
+[assembly: AssemblyVersion("1.9.5.1")]
+[assembly: AssemblyFileVersion("1.9.5.1")]
 [assembly: NeutralResourcesLanguage("zh-CN")]
 

+ 1 - 1
Masuit.Tools/packages.config

@@ -2,7 +2,7 @@
 <packages>
   <package id="AngleSharp" version="0.9.9.2" targetFramework="net45" />
   <package id="HtmlSanitizer" version="4.0.185" targetFramework="net45" />
-  <package id="Newtonsoft.Json" version="11.0.1" targetFramework="net45" />
+  <package id="Newtonsoft.Json" version="11.0.2" targetFramework="net45" />
   <package id="SharpZipLib" version="0.86.0" targetFramework="net45" />
   <package id="StackExchange.Redis" version="1.2.4" targetFramework="net45" />
 </packages>

+ 31 - 114
Test/Program.cs

@@ -1,9 +1,6 @@
-using System.Collections.Generic;
-using System.Linq;
+using System;
+using System.Collections.Concurrent;
 using System.Threading.Tasks;
-using Masuit.Tools.NoSQL.MongoDBClient;
-using MongoDB.Bson;
-using MongoDB.Driver;
 
 namespace Test
 {
@@ -11,116 +8,36 @@ namespace Test
     {
         static void Main(string[] args)
         {
-            //FileStream fs = new FileStream(@"D:\boot.vmdk", FileMode.OpenOrCreate, FileAccess.ReadWrite);
-            //{
-            //    fs.CopyToFileAsync(@"D:\1.bak");
-            //    string md5 = fs.GetFileMD5Async().Result;//获取文件的MD5
-            //}
-            //Console.WriteLine("复制完成");
-
-            //bool isUrl;
-            //var match = "//music.163.com/#/search/m/?%23%2Fmy%2Fm%2Fmusic%2Fempty=&s=fade&type=1!k".MatchUrl(out isUrl);
-            //Console.WriteLine(isUrl);
-            //foreach (Group g in match.Groups)
-            //{
-            //    if (g.Captures.Count > 0)
-            //    {
-            //        foreach (Capture c in g.Captures)
-            //        {
-            //            Console.WriteLine(c.Index + " : " + c.Value);
-            //        }
-            //    }
-            //    else
-            //    {
-            //        Console.WriteLine(g.Index + " : " + g.Value);
-            //    }
-            //}
-
-            //bool b1 = "512002199509230611".MatchIdentifyCard();//False
-            //bool b2 = "140108197705058894".MatchIdentifyCard();//True
-            //Console.WriteLine(b1 + "----" + b2);
-
-            //bool isIP;
-            //"114.114.256.114".MatchInetAddress(out isIP);//False
-            //"114.114.114.114".MatchInetAddress(out isIP);//True
-            //Console.WriteLine(isIP);
-            //Console.WriteLine(WindowsCommand.Execute("help"));
-            //string match = "vawevbgw".MatchRandomImgSrc();
-            //Console.WriteLine(match);
-            //PhysicsAddress address = "4.2.2.1".GetPhysicsAddressInfo();
-
-            //List<MyClass> mc = new List<MyClass> {new MyClass() {Name = "aaa", Age = 10, MyClass3 = new MyClass3(), MyClass2s = new List<MyClass2>() {new MyClass2() {Age = 22, Name = "dddd"}}}, new MyClass() {Name = "aaa", Age = 10, MyClass3 = new MyClass3()}, new MyClass() {Name = "aaa", Age = 10, MyClass3 = new MyClass3(), MyClass2s = new List<MyClass2>() {new MyClass2() {Age = 22, Name = "dddd"}}}, new MyClass() {Name = "aaa", Age = 10, MyClass3 = new MyClass3(), MyClass2s = new List<MyClass2>() {new MyClass2() {Age = 22, Name = "dddd"}}}};
-            //List<MyClass2> list = mc.Map<MyClass, MyClass2>().ToList();
-
-            //MyClass mc = null;
-            //MyClass2 mc2 = mc.Map<MyClass, MyClass2>();
-            //Dictionary<string, object> dic = new Dictionary<string, object>();
-            //for (int i = 0; i < 100000; i++)
-            //{
-            //    string s = string.Empty.CreateShortToken(100);
-            //    Console.WriteLine(s);
-            //    dic.Add(s, s);
-            //}
-
-            //var list = MongoDbClient.GetInstance("mongodb://192.168.3.238:27017", "AccountBalance").Database.GetCollection<BsonDocument>("201803-NEO").Indexes.List();
-            //while (list.MoveNext())
-            //{
-            //    if (!list.Current.Any(doc => doc["name"].AsString.StartsWith("AccountId")))
-            //    {
-            //        string index = MongoDbClient.GetInstance("mongodb://192.168.3.238:27017", "AccountBalance").Database.GetCollection<BsonDocument>("201803-NEO").Indexes.CreateOne(Builders<BsonDocument>.IndexKeys.Ascending(doc => doc["AccountId"]));
-            //    }
-            //}
-            //LogManager.Event += s =>
-            //{
-            //    if (s.Contains("ERROR") || s.Contains("FATAL"))
-            //    {
-            //        Console.ForegroundColor = ConsoleColor.Red;
-            //    }
-            //    if (s.Contains("DEBUG"))
-            //    {
-            //        Console.ForegroundColor = ConsoleColor.Green;
-            //    }
-            //    Console.WriteLine(s);
-            //    Console.ForegroundColor = ConsoleColor.White;
-            //};
-            //LogManager.Info("aaaaaaaaaaaaaaaaaaaaaaaaa");
-            //LogManager.Debug("bbbbbbbbbbbbbbbbb");
-            //LogManager.Error(typeof(object), "bbbbbbbbbbbbbbbbb");
-            //LogManager.Info("aaaaaaaaaaaaaaaaaaaaaaaaa");
-
-            //bool b = "[email protected]".MatchEmail();
-
-            MongoDbClient mc = MongoDbClient.ThreadLocalInstance("mongodb://127.0.0.1:27000,127.0.0.1:27001,127.0.0.1:27002/?slaveOk=true;maxPoolSize=100000;minPoolSize=32", "repl");
-            Parallel.For(0, 100000, i => mc.InsertOne("repl",new { name = "aa", value = 100 }));
-            Parallel.For(0, 100000, i => mc.GetMany("repl",Builders<BsonDocument>.Filter.Eq(doc => doc["value"], 100)).ToList());
-
-            //Console.ReadKey();
+            Parallel.For(0, 100, i =>
+                 {
+                     var result = Test().Result;
+                 });
+            Console.WriteLine(Count);
+            Console.ReadKey();
         }
-    }
 
-    public class Banlance
-    {
-        public string Name { get; set; }
-        public int Amount { get; set; }
-    }
-    public class MyClass
-    {
-        public string Name { get; set; }
-        public int Age { get; set; }
-        public MyClass3 MyClass3 { get; set; }
-        public List<MyClass2> MyClass2s { get; set; }
-    }
-
-    public class MyClass2
-    {
-        public string Name { get; set; }
-        public int Age { get; set; }
-        public MyClass3 MyClass3 { get; set; }
-        public List<MyClass2> MyClass2s { get; set; }
-    }
-
-    public class MyClass3
-    {
-        public string MyProperty { get; set; }
+        public static ConcurrentDictionary<string, object> LockDic { get; set; } = new ConcurrentDictionary<string, object>();
+        public static int Count { get; set; }
+        public static async Task<string> Test()
+        {
+            //using (new AsyncLock(LockDic.GetOrAdd("aa", new object())).LockAsync())
+            {
+                await Task.Run(() =>
+                {
+                    for (int i = 0; i < 100; i++)
+                    {
+                        Count++;
+                    }
+                });
+                await Task.Run(() =>
+                {
+                    for (int i = 0; i < 100; i++)
+                    {
+                        Count--;
+                    }
+                });
+                return "";
+            }
+        }
     }
 }

+ 1 - 0
Test/Test.csproj

@@ -69,6 +69,7 @@
     <Reference Include="System.Xml" />
   </ItemGroup>
   <ItemGroup>
+    <Compile Include="AsyncLock.cs" />
     <Compile Include="Program.cs" />
     <Compile Include="Properties\AssemblyInfo.cs" />
   </ItemGroup>