ASP.NET WebApi(.Net Framework) 应用CacheManager ,内存+Redis
1,WebApi 版本选.net4.6.2 以上版本
2,nuget包
Unity (4.0.0.1)
Unity.AspNet.WebApi (4.0.0.1)
CacheManager.Core
CacheManager.Microsoft.Extensions.Caching.Memory
CacheManager.Microsoft.Extensions.Configuration
CacheManager.Serialization.Json
CacheManager.StackExchange.Redis
CacheManager.SystemRuntimeCaching
3,web.config 添加
<connectionStrings>
<add name="redisConnection" connectionString="ip:6379,password=****" />
</connectionStrings>
4, 启动位置,添加代码
protected void Application_Start()
{
var container = new UnityContainer();
AreaRegistration.RegisterAllAreas();
GlobalConfiguration.Configure(WebApiConfig.Register);
GlobalConfiguration.Configuration.DependencyResolver = new UnityDependencyResolver(container);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
var cacheConfig = ConfigurationBuilder.BuildConfiguration(settings =>
{
settings.WithUpdateMode(CacheUpdateMode.Up)
.WithSystemRuntimeCacheHandle("inProcessCache")//内存缓存Handle
.WithExpiration(ExpirationMode.Sliding, TimeSpan.FromMinutes(60));
settings.WithJsonSerializer();
settings.WithRedisBackplane("redisConnection");
settings.WithRedisCacheHandle("redisConnection");
});
container.RegisterType(
typeof(ICacheManager<>),
new ContainerControlledLifetimeManager(),
new InjectionFactory(
(c, t, n) => CacheFactory.FromConfiguration(t.GetGenericArguments()[0], cacheConfig)));
}
5,Controller控制层
public class TestController : ApiController
{
[Dependency]
protected ICacheManager<Todo> TodoCache
{
get;
set;
}
6,测试代码
// GET api/Test/5
public string Get(int id)
{
Todo value1 = new Todo();
value1.Title = "test1-"+id.ToString();
TodoCache.Add("test1-" + id.ToString(), value1);
7,查看redis
推荐工具 Another Redis Desktop Manager
标签:WebApi,ASP,settings,Framework,CacheManager,new,Net From: https://www.cnblogs.com/luozhai714/p/17900743.html