自从使用Asp.net Core2.0 以来,不停摸索,查阅资料,这方面的资料是真的少,因此,在前人的基础上,摸索出了Asp.net Core2.0 缓存 MemoryCache 和 Redis的用法,并实现了简单的封装

那么,先给出几个参考资料吧

关于两种缓存:https://www.cnblogs.com/yuangang/p/5800113.html

关于redis持久化:https://blog.csdn.net/u010785685/article/details/52366977

两个nuget包,不用多说

接下来,贴出代码

首先在startup,我读取了appstting.json的数据,作为redis的配置

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Threading.Tasks;
  5. using Application.Common;
  6. using Application.Common.CommonObject;
  7. using Application.CoreWork;
  8. using Application.DAL;
  9. using Microsoft.AspNetCore.Builder;
  10. using Microsoft.AspNetCore.Hosting;
  11. using Microsoft.Extensions.Configuration;
  12. using Microsoft.Extensions.DependencyInjection;
  13.  
  14. namespace Application.web
  15. {
  16. public class Startup
  17. {
  18. public Startup(IConfiguration configuration)
  19. {
  20. Configuration = configuration;
  21. }
  22.  
  23. public IConfiguration Configuration { get; }
  24.  
  25. // This method gets called by the runtime. Use this method to add services to the container.
  26. public void ConfigureServices(IServiceCollection services)
  27. {
  28. Connection.MySqlConnection = Configuration.GetConnectionString("MySqlConnection");
  29. Connection.SqlConnection = Configuration.GetConnectionString("SqlConnection");
  30. RedisConfig.Connection = Configuration.GetSection("RedisConfig")["Connection"];
  31. RedisConfig.DefaultDatabase =Convert.ToInt32( Configuration.GetSection("RedisConfig")["DefaultDatabase"]);
  32. RedisConfig.InstanceName = Configuration.GetSection("RedisConfig")["InstanceName"];
  33. CommonManager.CacheObj.GetMessage<RedisCacheHelper>();
  34. services.AddMvc();
  35. }
  36.  
  37. // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
  38. public void Configure(IApplicationBuilder app, IHostingEnvironment env)
  39. {
  40. if (env.IsDevelopment())
  41. {
  42. app.UseBrowserLink();
  43. app.UseDeveloperExceptionPage();
  44. }
  45. else
  46. {
  47. app.UseExceptionHandler("/Home/Error");
  48. }
  49.  
  50. app.UseStaticFiles();
  51.  
  52. app.UseMvc(routes =>
  53. {
  54. routes.MapRoute(
  55. name: "default",
  56. template: "{controller=Home}/{action=Index}/{id?}");
  57. });
  58. }
  59. }
  60. }

再贴上配置

  1. "RedisConfig": {
  2. "Connection": "127.0.0.1:6379",
  3. "DefaultDatabase": 0,
  4. "InstanceName": "Redis1"
  5. },

  

用来放配置信息的静态类

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. namespace Application.Common
  6. {
  7. public static class RedisConfig
  8. {
  9. public static string configname { get; set; }
  10. public static string Connection { get; set; }
  11. public static int DefaultDatabase { get; set; }
  12. public static string InstanceName { get; set; }
  13. }
  14. }

然后ICacheHelper.cs,这个类是两种缓存通用的接口,让使用更方便

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Net;
  4. using System.Text;
  5.  
  6. namespace Application.Common.CommonObject
  7. {
  8. public interface ICacheHelper
  9. {
  10. bool Exists(string key);
  11.  
  12. T GetCache<T>(string key) where T : class;
  13.  
  14. void SetCache(string key, object value);
  15.  
  16. void SetCache(string key, object value, DateTimeOffset expiressAbsoulte);//设置绝对时间过期
  17.  
  18. void SetSlidingCache(string key, object value, TimeSpan t); //设置滑动过期, 因redis暂未找到自带的滑动过期类的API,暂无需实现该接口
  19.  
  20. void RemoveCache(string key);
  21.  
  22. void KeyMigrate(string key, EndPoint endPoint,int database,int timeountseconds);
  23.  
  24. void Dispose();
  25.  
  26. void GetMssages();
  27.  
  28. void Publish(string msg);
  29. }
  30. }

然后,实现接口,首先是MemoryCacheHelper

  1. using Microsoft.Extensions.Caching.Memory;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Net;
  5. using System.Text;
  6.  
  7. namespace Application.Common.CommonObject
  8. {
  9. public class MemoryCacheHelper : ICacheHelper
  10. {
  11. //public MemoryCacheHelper(/*MemoryCacheOptions options*/)//这里可以做成依赖注入,但没打算做成通用类库,所以直接把选项直接封在帮助类里边
  12. //{
  13. // //this._cache = new MemoryCache(options);
  14. // //this._cache = new MemoryCache(new MemoryCacheOptions());
  15. //}
  16. //public MemoryCacheHelper(MemoryCacheOptions options)//这里可以做成依赖注入,但没打算做成通用类库,所以直接把选项直接封在帮助类里边
  17. //{
  18. // this._cache = new MemoryCache(options);
  19. //}
  20.  
  21. public static IMemoryCache _cache=new MemoryCache(new MemoryCacheOptions());
  22.  
  23. /// <summary>
  24. /// 是否存在此缓存
  25. /// </summary>
  26. /// <param name="key"></param>
  27. /// <returns></returns>
  28. public bool Exists(string key)
  29. {
  30. if (string.IsNullOrWhiteSpace(key))
  31. throw new ArgumentNullException(nameof(key));
  32. object v = null;
  33. return _cache.TryGetValue<object>(key, out v);
  34. }
  35. /// <summary>
  36. /// 取得缓存数据
  37. /// </summary>
  38. /// <typeparam name="T"></typeparam>
  39. /// <param name="key"></param>
  40. /// <returns></returns>
  41. public T GetCache<T>(string key) where T : class
  42. {
  43. if (string.IsNullOrWhiteSpace(key))
  44. throw new ArgumentNullException(nameof(key));
  45.  
  46. T v = null;
  47. _cache.TryGetValue<T>(key, out v);
  48.  
  49. return v;
  50. }
  51. /// <summary>
  52. /// 设置缓存
  53. /// </summary>
  54. /// <param name="key"></param>
  55. /// <param name="value"></param>
  56. public void SetCache(string key, object value)
  57. {
  58. if (string.IsNullOrWhiteSpace(key))
  59. throw new ArgumentNullException(nameof(key));
  60. if (value == null)
  61. throw new ArgumentNullException(nameof(value));
  62.  
  63. object v = null;
  64. if (_cache.TryGetValue(key, out v))
  65. _cache.Remove(key);
  66. _cache.Set<object>(key, value);
  67. }
  68. /// <summary>
  69. /// 设置缓存,绝对过期
  70. /// </summary>
  71. /// <param name="key"></param>
  72. /// <param name="value"></param>
  73. /// <param name="expirationMinute">间隔分钟</param>
  74. /// CommonManager.CacheObj.Save<RedisCacheHelper>("test", "RedisCache works!", 30);
  75. public void SetCache(string key, object value, double expirationMinute)
  76. {
  77. if (string.IsNullOrWhiteSpace(key))
  78. throw new ArgumentNullException(nameof(key));
  79. if (value == null)
  80. throw new ArgumentNullException(nameof(value));
  81.  
  82. object v = null;
  83. if (_cache.TryGetValue(key, out v))
  84. _cache.Remove(key);
  85. DateTime now = DateTime.Now;
  86. TimeSpan ts = now.AddMinutes(expirationMinute) - DateTime.Now;
  87. _cache.Set<object>(key, value, ts);
  88. }
  89. /// <summary>
  90. /// 设置缓存,绝对过期
  91. /// </summary>
  92. /// <param name="key"></param>
  93. /// <param name="value"></param>
  94. /// <param name="expirationTime">DateTimeOffset 结束时间</param>
  95. /// CommonManager.CacheObj.Save<RedisCacheHelper>("test", "RedisCache works!", DateTimeOffset.Now.AddSeconds(30));
  96. public void SetCache(string key, object value, DateTimeOffset expirationTime)
  97. {
  98. if (string.IsNullOrWhiteSpace(key))
  99. throw new ArgumentNullException(nameof(key));
  100. if (value == null)
  101. throw new ArgumentNullException(nameof(value));
  102.  
  103. object v = null;
  104. if (_cache.TryGetValue(key, out v))
  105. _cache.Remove(key);
  106.  
  107. _cache.Set<object>(key, value, expirationTime);
  108. }
  109. /// <summary>
  110. /// 设置缓存,相对过期时间
  111. /// </summary>
  112. /// <param name="key"></param>
  113. /// <param name="value"></param>
  114. /// <param name="t"></param>
  115. /// CommonManager.CacheObj.SaveSlidingCache<MemoryCacheHelper>("test", "MemoryCache works!",TimeSpan.FromSeconds(30));
  116. public void SetSlidingCache(string key,object value,TimeSpan t)
  117. {
  118. if (string.IsNullOrWhiteSpace(key))
  119. throw new ArgumentNullException(nameof(key));
  120. if (value == null)
  121. throw new ArgumentNullException(nameof(value));
  122.  
  123. object v = null;
  124. if (_cache.TryGetValue(key, out v))
  125. _cache.Remove(key);
  126.  
  127. _cache.Set(key, value, new MemoryCacheEntryOptions()
  128. {
  129. SlidingExpiration=t
  130. });
  131. }
  132. /// <summary>
  133. /// 移除缓存
  134. /// </summary>
  135. /// <param name="key"></param>
  136. public void RemoveCache(string key)
  137. {
  138. if (string.IsNullOrWhiteSpace(key))
  139. throw new ArgumentNullException(nameof(key));
  140.  
  141. _cache.Remove(key);
  142. }
  143.  
  144. /// <summary>
  145. /// 释放
  146. /// </summary>
  147. public void Dispose()
  148. {
  149. if (_cache != null)
  150. _cache.Dispose();
  151. GC.SuppressFinalize(this);
  152. }
  153.  
  154. public void KeyMigrate(string key, EndPoint endPoint, int database, int timeountseconds)
  155. {
  156. throw new NotImplementedException();
  157. }
  158.  
  159. public void GetMssages()
  160. {
  161. throw new NotImplementedException();
  162. }
  163.  
  164. public void Publish(string msg)
  165. {
  166. throw new NotImplementedException();
  167. }
  168. }
  169. }

然后是RedisCacheHelper

  1. using Microsoft.Extensions.Caching.Redis;
  2. using Newtonsoft.Json;
  3. using StackExchange.Redis;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.Net;
  7. using System.Text;
  8.  
  9. namespace Application.Common.CommonObject
  10. {
  11. public class RedisCacheHelper : ICacheHelper
  12. {
  13. public RedisCacheHelper(/*RedisCacheOptions options, int database = 0*/)//这里可以做成依赖注入,但没打算做成通用类库,所以直接把连接信息直接写在帮助类里
  14. {
  15. options = new RedisCacheOptions();
  16. options.Configuration = "127.0.0.1:6379";//RedisConfig.Connection;
  17. options.InstanceName = RedisConfig.InstanceName;
  18. int database = RedisConfig.DefaultDatabase;
  19. _connection = ConnectionMultiplexer.Connect(options.Configuration);
  20. _cache = _connection.GetDatabase(database);
  21. _instanceName = options.InstanceName;
  22. _sub = _connection.GetSubscriber();
  23. }
  24.  
  25. public static RedisCacheOptions options;
  26. public static IDatabase _cache;
  27.  
  28. public static ConnectionMultiplexer _connection;
  29.  
  30. public static string _instanceName;
  31.  
  32. public static ISubscriber _sub;
  33.  
  34. /// <summary>
  35. /// 取得redis的Key名称
  36. /// </summary>
  37. /// <param name="key"></param>
  38. /// <returns></returns>
  39. private string GetKeyForRedis(string key)
  40. {
  41. return _instanceName + key;
  42. }
  43. /// <summary>
  44. /// 判断当前Key是否存在数据
  45. /// </summary>
  46. /// <param name="key"></param>
  47. /// <returns></returns>
  48. public bool Exists(string key)
  49. {
  50. if (string.IsNullOrWhiteSpace(key))
  51. throw new ArgumentNullException(nameof(key));
  52. return _cache.KeyExists(GetKeyForRedis(key));
  53. }
  54.  
  55. /// <summary>
  56. /// 取得缓存数据
  57. /// </summary>
  58. /// <typeparam name="T"></typeparam>
  59. /// <param name="key"></param>
  60. /// <returns></returns>
  61. public T GetCache<T>(string key) where T : class
  62. {
  63. if (string.IsNullOrWhiteSpace(key))
  64. throw new ArgumentNullException(nameof(key));
  65. var value = _cache.StringGet(GetKeyForRedis(key));
  66. if (!value.HasValue)
  67. return default(T);
  68. return JsonConvert.DeserializeObject<T>(value);
  69. }
  70. /// <summary>
  71. /// 设置缓存数据
  72. /// </summary>
  73. /// <param name="key"></param>
  74. /// <param name="value"></param>
  75. public void SetCache(string key, object value)
  76. {
  77. if (string.IsNullOrWhiteSpace(key))
  78. throw new ArgumentNullException(nameof(key));
  79. if (value == null)
  80. throw new ArgumentNullException(nameof(value));
  81.  
  82. if (Exists(GetKeyForRedis(key)))
  83. RemoveCache(GetKeyForRedis(key));
  84.  
  85. _cache.StringSet(GetKeyForRedis(key), JsonConvert.SerializeObject(value));
  86. }
  87. /// <summary>
  88. /// 设置绝对过期时间
  89. /// </summary>
  90. /// <param name="key"></param>
  91. /// <param name="value"></param>
  92. /// <param name="expiressAbsoulte"></param>
  93. public void SetCache(string key, object value, DateTimeOffset expiressAbsoulte)
  94. {
  95. if (string.IsNullOrWhiteSpace(key))
  96. throw new ArgumentNullException(nameof(key));
  97. if (value == null)
  98. throw new ArgumentNullException(nameof(value));
  99.  
  100. if (Exists(GetKeyForRedis(key)))
  101. RemoveCache(GetKeyForRedis(key));
  102. TimeSpan t = expiressAbsoulte - DateTimeOffset.Now;
  103. _cache.StringSet(GetKeyForRedis(key), JsonConvert.SerializeObject(value), t);
  104. }
  105. /// <summary>
  106. /// 设置相对过期时间
  107. /// </summary>
  108. /// <param name="key"></param>
  109. /// <param name="value"></param>
  110. /// <param name="expirationMinute"></param>
  111. public void SetCache(string key, object value, double expirationMinute)
  112. {
  113. if (Exists(GetKeyForRedis(key)))
  114. RemoveCache(GetKeyForRedis(key));
  115.  
  116. DateTime now = DateTime.Now;
  117. TimeSpan ts = now.AddMinutes(expirationMinute) - now;
  118. _cache.StringSet(GetKeyForRedis(key), JsonConvert.SerializeObject(value), ts);
  119. }
  120. /// <summary>
  121. ///
  122. /// </summary>
  123. /// <param name="key"></param>
  124. /// <param name="endPoint"></param>
  125. /// <param name="database"></param>
  126. /// <param name="timeountseconds"></param>
  127. public void KeyMigrate(string key, EndPoint endPoint, int database, int timeountseconds) {
  128. if (string.IsNullOrWhiteSpace(key))
  129. throw new ArgumentNullException(nameof(key));
  130. _cache.KeyMigrate(GetKeyForRedis(key), endPoint, database, timeountseconds);
  131. }
  132. /// <summary>
  133. /// 移除redis
  134. /// </summary>
  135. /// <param name="key"></param>
  136. public void RemoveCache(string key)
  137. {
  138. if (string.IsNullOrWhiteSpace(key))
  139. throw new ArgumentNullException(nameof(key));
  140.  
  141. _cache.KeyDelete(GetKeyForRedis(key));
  142. }
  143.  
  144. /// <summary>
  145. /// 销毁连接
  146. /// </summary>
  147. public void Dispose()
  148. {
  149. if (_connection != null)
  150. _connection.Dispose();
  151. GC.SuppressFinalize(this);
  152. }
  153.  
  154. public void SetSlidingCache(string key, object value, TimeSpan t)
  155. {
  156. throw new NotImplementedException();
  157. }
  158.  
  159. public void GetMssages()
  160. {
  161. using (_connection = ConnectionMultiplexer.Connect(options.Configuration))
  162. _sub.Subscribe("msg", (channel, message) =>
  163. {
  164. string result = message;
  165. });
  166. }
  167.  
  168. public void Publish(string msg)
  169. {
  170. using (_connection=ConnectionMultiplexer.Connect(options.Configuration))
  171. _sub.Publish("msg", msg);
  172. }
  173. }
  174. }

然后是Cache.cs,用来实例化,此处用单例模式,保证项目使用的是一个缓存实例,博主吃过亏,由于redis实例过多,构造函数运行太多次,导致client连接数过大,内存不够跑,速度卡慢

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4.  
  5. namespace Application.Common.CommonObject
  6. {
  7. public sealed class Cache
  8. {
  9. internal Cache() { }
  10. public static ICacheHelper cache;
  11. /// <summary>
  12. /// 判断缓存是否存在
  13. /// </summary>
  14. /// <typeparam name="CacheType">缓存类型</typeparam>
  15. /// <param name="key">键名</param>
  16. /// <returns></returns>
  17. public bool Exists<CacheType>(string key) where CacheType : ICacheHelper, new()
  18. {
  19. if (cache!=null&& typeof(CacheType).Equals(cache.GetType()))
  20. return cache.Exists(key);
  21. else
  22. {
  23. cache = new CacheType();
  24. return cache.Exists(key);
  25. }
  26. }
  27.  
  28. /// <summary>
  29. /// 获取缓存
  30. /// </summary>
  31. /// <typeparam name="T">转换的类</typeparam>
  32. /// <typeparam name="CacheType">缓存类型</typeparam>
  33. /// <param name="key">键名</param>
  34. /// <returns>转换为T类型的值</returns>
  35. public T GetCache<T,CacheType>(string key)
  36. where T:class
  37. where CacheType : ICacheHelper, new()
  38. {
  39. if (cache != null && typeof(CacheType).Equals(cache.GetType()))
  40. return cache.GetCache<T>(key);
  41. else
  42. {
  43. cache = new CacheType();
  44. return cache.GetCache<T>(key);
  45. }
  46. }
  47.  
  48. /// <summary>
  49. /// 保存缓存
  50. /// </summary>
  51. /// <typeparam name="CacheType">缓存类型</typeparam>
  52. /// <param name="key">键名</param>
  53. /// <param name="value">值</param>
  54. public void Save<CacheType>(string key,object value) where CacheType : ICacheHelper, new()
  55. {
  56. if (cache != null && typeof(CacheType).Equals(cache.GetType()))
  57. cache.SetCache(key, value);
  58. else
  59. {
  60. cache = new CacheType();
  61. cache.SetCache(key, value);
  62. }
  63. }
  64.  
  65. /// <summary>
  66. /// 保存缓存并设置绝对过期时间
  67. /// </summary>
  68. /// <typeparam name="CacheType">缓存类型</typeparam>
  69. /// <param name="key">键名</param>
  70. /// <param name="value">值</param>
  71. /// <param name="expiressAbsoulte">绝对过期时间</param>
  72. public void Save<CacheType>(string key, object value, DateTimeOffset expiressAbsoulte) where CacheType : ICacheHelper, new()
  73. {
  74. if (cache != null && typeof(CacheType).Equals(cache.GetType()))
  75. cache.SetCache(key, value, expiressAbsoulte);
  76. else
  77. {
  78. cache = new CacheType();
  79. cache.SetCache(key, value, expiressAbsoulte);
  80. }
  81. }
  82.  
  83. /// <summary>
  84. /// 保存滑动缓存
  85. /// </summary>
  86. /// <typeparam name="CacheType">只能用memorycache,redis暂不实现</typeparam>
  87. /// <param name="key"></param>
  88. /// <param name="value"></param>
  89. /// <param name="t">间隔时间</param>
  90. public void SaveSlidingCache<CacheType>(string key, object value,TimeSpan t) where CacheType : MemoryCacheHelper, new()
  91. {
  92. if (cache != null && typeof(CacheType).Equals(cache.GetType()))
  93. cache.SetSlidingCache(key, value, t);
  94. else
  95. {
  96. cache = new CacheType();
  97. cache.SetSlidingCache(key, value, t);
  98. }
  99. }
  100.  
  101. /// <summary>
  102. /// 删除一个缓存
  103. /// </summary>
  104. /// <typeparam name="CacheType">缓存类型</typeparam>
  105. /// <param name="key">要删除的key</param>
  106. public void Delete<CacheType>(string key)where CacheType : ICacheHelper, new()
  107. {
  108. if (cache != null && typeof(CacheType).Equals(cache.GetType()))
  109. cache.RemoveCache(key);
  110. else
  111. {
  112. cache = new CacheType();
  113. cache.RemoveCache(key);
  114. }
  115. }
  116.  
  117. /// <summary>
  118. /// 释放
  119. /// </summary>
  120. /// <typeparam name="CacheType"></typeparam>
  121. public void Dispose<CacheType>() where CacheType : ICacheHelper, new()
  122. {
  123. if (cache != null && typeof(CacheType).Equals(cache.GetType()))
  124. cache.Dispose();
  125. else
  126. {
  127. cache = new CacheType();
  128. cache.Dispose();
  129. }
  130. }
  131.  
  132. public void GetMessage<CacheType>() where CacheType:RedisCacheHelper,new()
  133. {
  134. if (cache != null && typeof(CacheType).Equals(cache.GetType()))
  135. cache.GetMssages();
  136. else
  137. {
  138. cache = new CacheType();
  139. cache.GetMssages();
  140. }
  141. }
  142.  
  143. public void Publish<CacheType>(string msg)where CacheType : RedisCacheHelper, new()
  144. {
  145. if (cache != null && typeof(CacheType).Equals(cache.GetType()))
  146. cache.Publish(msg);
  147. else
  148. {
  149. cache = new CacheType();
  150. cache.Publish(msg);
  151. }
  152. }
  153. }
  154. }

接下来,CommonManager.cs,该类主要是为了作为一个静态类调用缓存,由于Cache.cs并非静态类,方便调用

  1. using Application.Common.CommonObject;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Text;
  5.  
  6. namespace Application.Common
  7. {
  8. public class CommonManager
  9. {
  10. private static readonly object lockobj = new object();
  11. private static volatile Cache _cache = null;
  12. /// <summary>
  13. /// Cache
  14. /// </summary>
  15. public static Cache CacheObj
  16. {
  17. get
  18. {
  19. if (_cache == null)
  20. {
  21. lock (lockobj)
  22. {
  23. if (_cache == null)
  24. _cache = new Cache();
  25. }
  26. }
  27. return _cache;
  28. }
  29. }
  30. }
  31. }

最后呢就是使用啦随便建的一个控制器

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Net;
  5. using System.Threading;
  6. using System.Threading.Tasks;
  7. using Application.Common;
  8. using Application.Common.CommonObject;
  9. using Application.CoreWork;
  10. using Microsoft.AspNetCore.Mvc;
  11.  
  12. namespace Application.web.Controllers
  13. {
  14. public class DefaultController : BaseController
  15. {
  16. public IActionResult Index()
  17. {
  18. for (int i = ; i < ; i++)
  19. {
  20. CommonManager.CacheObj.Save<RedisCacheHelper>("key" + i, "key" + i + " works!");
  21. }
  22. return View();
  23. }
  24.  
  25. public IActionResult GetStrin(int index)
  26. {
  27. string res = "已经过期了";
  28. if (CommonManager.CacheObj.Exists<RedisCacheHelper>("key" + index))
  29. {
  30. res = CommonManager.CacheObj.GetCache<String, RedisCacheHelper>("key" + index);
  31. }
  32. return Json(new ExtJson { success = true, code = , msg = "成功", jsonresult = res });
  33. }
  34.  
  35. public IActionResult Publish(string msg)
  36. {
  37. try
  38. {
  39. CommonManager.CacheObj.Publish<RedisCacheHelper>(msg);
  40. return Json(new ExtJson { success = true, code = , msg = "成功", jsonresult = msg });
  41. }
  42. catch
  43. {
  44. return Json(new ExtJson
  45. {
  46. success = true,
  47. code = ,
  48. msg = "失败",
  49. jsonresult = msg
  50. });
  51. }
  52. }
  53. }
  54. }

那么,有的朋友在json处可能会报错,自己封装下,或者用原来的json吧

如果有不懂的地方,可以在评论中提问,有更好的改进方式,也请联系我,共同进步,感谢阅读

2019-5-23更新

在实际运行过程中,发现大量用户请求,并且两种缓存混合使用时,redis和memory的单例会多次创建,导致redis连接数达到上限,下面贴出修改后的cache.cs

  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Text;
  5.  
  6. namespace Application.Common.CommonObject
  7. {
  8. public sealed class Cache
  9. {
  10. internal Cache() { }
  11. public static ICacheHelper cache;
  12.  
  13. public static RedisCacheHelper redis;
  14. public static MemoryCacheHelper memory;
  15.  
  16. public ICacheHelper Getcachehelper<CacheType>()
  17. {
  18. if (typeof(CacheType).Equals(typeof(RedisCacheHelper)))
  19. {
  20. if (redis == null)
  21. {
  22. redis = new RedisCacheHelper();
  23. Process pc = Process.GetCurrentProcess();
  24. CommonManager.TxtObj.Log4netError("进程ID:"+pc.Id+";redis为null,创建一个新的实例",typeof(Cache),null);
  25. }
  26. return redis;
  27. }
  28. else if (typeof(CacheType).Equals(typeof(MemoryCacheHelper)))
  29. {
  30. if (memory == null)
  31. memory = new MemoryCacheHelper();
  32. return memory;
  33. }
  34. else
  35. return null;
  36. }
  37. /// <summary>
  38. /// 判断缓存是否存在
  39. /// </summary>
  40. /// <typeparam name="CacheType">缓存类型</typeparam>
  41. /// <param name="key">键名</param>
  42. /// <returns></returns>
  43. public bool Exists<CacheType>(string key) where CacheType : ICacheHelper, new()
  44. {
  45. cache = Getcachehelper<CacheType>();
  46. return cache.Exists(key);
  47. }
  48.  
  49. /// <summary>
  50. /// 获取缓存
  51. /// </summary>
  52. /// <typeparam name="T">转换的类</typeparam>
  53. /// <typeparam name="CacheType">缓存类型</typeparam>
  54. /// <param name="key">键名</param>
  55. /// <returns>转换为T类型的值</returns>
  56. public T GetCache<T, CacheType>(string key)
  57. where T : class
  58. where CacheType : ICacheHelper, new()
  59. {
  60. cache = Getcachehelper<CacheType>();
  61. return cache.GetCache<T>(key);
  62. }
  63.  
  64. /// <summary>
  65. /// 保存缓存
  66. /// </summary>
  67. /// <typeparam name="CacheType">缓存类型</typeparam>
  68. /// <param name="key">键名</param>
  69. /// <param name="value">值</param>
  70. public void Save<CacheType>(string key, object value) where CacheType : ICacheHelper, new()
  71. {
  72. cache = Getcachehelper<CacheType>();
  73. cache.SetCache(key, value);
  74. }
  75.  
  76. /// <summary>
  77. /// 保存缓存并设置绝对过期时间
  78. /// </summary>
  79. /// <typeparam name="CacheType">缓存类型</typeparam>
  80. /// <param name="key">键名</param>
  81. /// <param name="value">值</param>
  82. /// <param name="expiressAbsoulte">绝对过期时间</param>
  83. public void Save<CacheType>(string key, object value, DateTimeOffset expiressAbsoulte) where CacheType : ICacheHelper, new()
  84. {
  85. cache = Getcachehelper<CacheType>();
  86. cache.SetCache(key, value, expiressAbsoulte);
  87. }
  88.  
  89. /// <summary>
  90. /// 保存滑动缓存
  91. /// </summary>
  92. /// <typeparam name="CacheType">只能用memorycache,redis暂不实现</typeparam>
  93. /// <param name="key"></param>
  94. /// <param name="value"></param>
  95. /// <param name="t">间隔时间</param>
  96. public void SaveSlidingCache<CacheType>(string key, object value, TimeSpan t) where CacheType : MemoryCacheHelper, new()
  97. {
  98. cache = Getcachehelper<CacheType>();
  99. cache.SetSlidingCache(key, value, t);
  100. }
  101.  
  102. /// <summary>
  103. /// 删除一个缓存
  104. /// </summary>
  105. /// <typeparam name="CacheType">缓存类型</typeparam>
  106. /// <param name="key">要删除的key</param>
  107. public void Delete<CacheType>(string key) where CacheType : ICacheHelper, new()
  108. {
  109. cache = Getcachehelper<CacheType>();
  110. cache.RemoveCache(key);
  111. }
  112.  
  113. /// <summary>
  114. /// 释放
  115. /// </summary>
  116. /// <typeparam name="CacheType"></typeparam>
  117. public void Dispose<CacheType>() where CacheType : ICacheHelper, new()
  118. {
  119. cache = Getcachehelper<CacheType>();
  120. cache.Dispose();
  121. }
  122. public List<string> GetCacheKeys<CacheType>() where CacheType : ICacheHelper, new()
  123. {
  124. cache = Getcachehelper<CacheType>();
  125. return cache.GetCacheKeys();
  126. }
  127. public void GetMessage<CacheType>() where CacheType : RedisCacheHelper, new()
  128. {
  129. cache = Getcachehelper<CacheType>();
  130. cache.GetMssages();
  131. }
  132.  
  133. public void Publish<CacheType>(string msg) where CacheType : RedisCacheHelper, new()
  134. {
  135. cache = Getcachehelper<CacheType>();
  136. cache.Publish(msg);
  137. }
  138. }
  139. }

  

Asp.net Core2.0 缓存 MemoryCache 和 Redis的更多相关文章

  1. Asp.net Core 缓存 MemoryCache 和 Redis

    Asp.net Core 缓存 MemoryCache 和 Redis 目录索引 [无私分享:ASP.NET CORE 项目实战]目录索引 简介 经过 N 久反复的尝试,翻阅了网上无数的资料,GitH ...

  2. 一步一步带你做WebApi迁移ASP.NET Core2.0

    随着ASP.NET Core 2.0发布之后,原先运行在Windows IIS中的ASP.NET WebApi站点,就可以跨平台运行在Linux中.我们有必要先说一下ASP.NET Core. ASP ...

  3. 【翻译】asp.net core2.0中的token认证

    原文地址:https://developer.okta.com/blog/2018/03/23/token-authentication-aspnetcore-complete-guide token ...

  4. 【转】Asp.Net Core2.0获取客户IP地址,及解决发布到Ubuntu服务器获取不到正确IP解决办法

    1.获取客户端IP地址实现方法(扩展类) using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ModelBinding; u ...

  5. [翻译]在asp.net core2.0 OpenID Connect Handler中丢失了声明(CLaims)?

    注:这是一篇翻译,来自这里.这篇文章讲述了在asp.net core2.0中使用openid connect handler的过程中解析不到你想要的claim时,你可以参考这篇文章. Missing ...

  6. Asp.Net Core2.0获取客户IP地址,及解决发布到Ubuntu服务器获取不到正确IP解决办法

    1.获取客户端IP地址实现方法(扩展类) using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc.ModelBinding; u ...

  7. VS2017创建一个 ASP.NET Core2.0 应用,并搭建 MVC 框架

    https://testerhome.com/topics/11747 1.使用最新版本的VS2017,并安装.NET Core2.0中相关开发工具   2.打开VS2017,点击文件-新建-项目,选 ...

  8. 在阿里云Windows Server 上部署ASP .NET CORE2.0项目

    近期使用ASP.NET Core2.0对博客进行了重写,在部署到服务器时遇到了一些问题,来记录一下留用. 配置环境 安装 .Net Framework3.5 在IIS管理器上直接开启,这里总是失败,上 ...

  9. 通过Mysql连接ASP.Net Core2.0(Code First模式)

    ASP.NET Core2.0连接Mysql,首先新建项目 选择Web应用程序 选择需要身份验证: 通过Nuget安装Mysql驱动,这里推荐>Pomelo.EntityFrameworkCor ...

随机推荐

  1. C++中输出流的刷新问题和 endl和 \n的区别

    <C++ Primer>第5版 P6中提到endl具有换行和刷新输出流两个作用,那么没有 endl是否还会将输出流中的内容输出到设备中,再刷新输出流呢? cout << &qu ...

  2. 集大1513 & 1514班 软件工程第二次作业评分与点评

    谢谢按时完成作业的同学. 请大家在今后的作业中多思考,认真完成并注意作业的原创性. 学号 作业标题 作业地址 提交日期 分数 201521121087 微信APP简要分析 http://www.cnb ...

  3. C语言博客作业—数据类型

    一.PTA实验作业 题目1: 1. 本题PTA提交列表 2. 设计思路 (2)if(输入的n为奇数){ for(行数小于n/2+1时){ for(空格数等于n-2*k+1) printf(" ...

  4. github上传时出现error: src refspec master does not match any解决办法

    github上传时出现error: src refspec master does not match any解决办法 这个问题,我之前也遇到过,这次又遇到了只是时间间隔比较长了,为了防止以后再遇到类 ...

  5. scrapy 数据存储mysql

    #spider.pyfrom scrapy.linkextractors import LinkExtractor from scrapy.spiders import CrawlSpider, Ru ...

  6. C++中文件的读写

    C++中文件的读写 在C++中如何实现文件的读写? 一.ASCII 输出 为了使用下面的方法, 你必须包含头文件<fstream.h>(译者注:在标准C++中,已经使用<fstrea ...

  7. 【iOS】swift-ObjectC 在iOS 8中使用UIAlertController

    iOS 8的新特性之一就是让接口更有适应性.更灵活,因此许多视图控制器的实现方式发生了巨大的变化.全新的UIPresentationController在实现视图控制器间的过渡动画效果和自适应设备尺寸 ...

  8. java利用iTextWorker生成pdf

    使用itext生成pdf,在linux环境下,中文全部失踪,因为itext要在linux下支持中文字体需要引入itext-asian, 并添加一个字体类. public static class Pd ...

  9. MYSQL中group_concat有长度限制!默认1024

    在mysql中,有个函数叫"group_concat",平常使用可能发现不了问题,在处理大数据的时候,会发现内容被截取了,其实MYSQL内部对这个是有设置的,默认不设置的长度是10 ...

  10. 用Vue.js开发微信小程序:开源框架mpvue解析

    前言 mpvue 是一款使用 Vue.js 开发微信小程序的前端框架.使用此框架,开发者将得到完整的 Vue.js 开发体验,同时为 H5 和小程序提供了代码复用的能力.如果想将 H5 项目改造为小程 ...