public class MemCachedHelper : ICacheHelper { private IMemcachedClient memcachedClient; public MemCachedHelper(IMemcachedClient memcachedClient) { this.memcachedClient = memcachedClient; } public object Get(string key) { return memcachedClient.Get(key); } public void Set(string key, object obj) { memcachedClient.Set(key, obj, int.MaxValue); } public void Set(string key, object obj, int seconds) { memcachedClient.Set(key, obj, seconds); } public void Remove(string key) { memcachedClient.Remove(key); } public void RemoveAllCache() { memcachedClient.FlushAll(); } }
放在类库项目中。那这个MemCachedHelper要如何使用?参数是?
MemCachedHelper cache= new MemCachedHelper (????);
Startup 中注册到依赖注入容器
public void ConfigureServices(IServiceCollection services)
{
services.AddTransient<MemCachedHelper>();
}
使用的地方通过构造函数注入
public class UserService
{
private readonly MemCachedHelper _memCachedHelper;
public UserService(MemCachedHelper memCachedHelper)
{
_memCachedHelper = memCachedHelper;
}
}
appsettings.json:
{ "enyimMemcached": { "Servers": [ { "Address": "127.0.0.1", "Port": 11211 } ] }, "Logging": { "LogLevel": { "Default": "Warning" } }, "AllowedHosts": "*" }
Startup.cs
public void ConfigureServices(IServiceCollection services) { services.AddEnyimMemcached(); services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; options.MinimumSameSitePolicy = SameSiteMode.None; }); services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); } public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseEnyimMemcached(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Home/Error"); app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); }
HomeController:
public IMemcachedClient _mm; public HomeController(IMemcachedClient mm) { _mm = mm; } public IActionResult Index() { _mm.Add("ddd","abc",600); return View(); } public IActionResult About() { ViewData["Message"] = "Your application description page."; ViewBag.v = _mm.Get("dddd"); return View(); }
在Memcached中是有数据的:
为什么在_mm.Get("dddd");中还是获取不到数据?