Mvc 5和Redis(ServiceStack.Redis)实现自定义会话提供程序

Models文件夹

 public class HomeViewModel
    {
        public string ValueStoredInRedis { get; set; }
    }

  public class RefreshMeViewModel : HomeViewModel
    {
    }

 public class ResultViewModel : HomeViewModel
    {
    }

Services文件夹

using ServiceStack.Redis;
namespace xxxx.yyyy
{
    public interface ICacheProvider
    {
        T Get<T>(string key);
        void Set<T>(string key, T value);
    }

    public class CacheProvider : ICacheProvider
    {
        public T Get<T>(string key)
        {
            using (var client = new RedisClient(new RedisEndpoint("127.0.0.1", 6379, "123456")))
            {
                if (!client.ContainsKey(key))
                    return default(T);

                return client.Get<T>(key);
            }
        }

        public void Set<T>(string key, T value)
        {
            using (var client = new RedisClient(new RedisEndpoint("127.0.0.1", 6379, "123456")))
            {
                client.Set(key, value);
            }
        }
    }
}

Controllers文件夹控制器类

  public class HomeController : Controller
    {
        private const string SessionName = "MyFistSessionVariableInRedis";
        private const string CacheName = "MyFirstCacheVariableInRedis";
        private readonly ICacheProvider _cacheProvider;
        public HomeController()
        {
            _cacheProvider = new CacheProvider();
        }
        // GET: Home
        public ActionResult Index()
        {
            HomeViewModel vm = new HomeViewModel();

            string sv = string.Format("将此值存储在Session中: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss.fff tt"));
            vm.ValueStoredInRedis = string.Format("将此值存储在Redis中: {0}", DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss.fff tt"));

            Session[SessionName] = sv;
            //缓存视图模型
            _cacheProvider.Set(CacheName,vm);

            return View(vm);
        }

        public ActionResult RefreshMe()
        {
            //浏览器回传后从会话中重新获得值
            RefreshMeViewModel vm = new RefreshMeViewModel();

            //Session获取失败,创建session是获取不到的,原因是因为创建的session是Controller下的(这里自己可以深入研究一下),
            //而不是System.Web.HttpContext.Current的session。
            vm.ValueStoredInRedis = Session[SessionName] as string;

            HomeViewModel vmHome = _cacheProvider.Get<HomeViewModel>(CacheName);

            TempData["IsCaching"] = (vmHome != null);

            ViewBag.RedisTimeV = vmHome.ValueStoredInRedis;

            return View(vm);
        }
    }

public class ResultController : Controller
    {
        private const string SessionName = "MyFistSessionVariableInRedis";
        private const string CacheName = "MyFirstCacheVariableInRedis";
        private readonly ICacheProvider _cacheProvider;
        public ResultController()
        {
            _cacheProvider = new CacheProvider();
        }
        // GET: Result
        public ActionResult Index()
        {
            ResultViewModel vm = new ResultViewModel();

            vm.ValueStoredInRedis = Session[SessionName] as string;

            HomeViewModel vmHome = _cacheProvider.Get<HomeViewModel>(CacheName);

            TempData["IsCaching"] = (vmHome != null);

            ViewBag.RedisTimeV = vmHome.ValueStoredInRedis;

            return View(vm);
        }
    }

试图层:

Home文件夹

Index.cshtml

@model xxxx.yyyy.HomeViewModel

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body>
    <div> 
        <h1>集成Asp.Net MVC 5 + Redis</h1>
        <br/>
        <b>会话中的变量值</b>
        <p>@Session["MyFistSessionVariableInRedis"]</p>
        <b>Redis中的变量值</b>
        <p>@Model.ValueStoredInRedis</p>
    </div>
    <br/>
    <br/>
    @Html.ActionLink("重定向到另一个页面...并检查具有相同的TimeStamp的Session仍然在那里", "RefreshMe", "Home")
</body>
</html>

RefreshMe.cshtml

@model xxxx.yyyy.RefreshMeViewModel

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>RefreshMe</title>
</head>
<body style="background-color:#f5f5f5;">
    <div>
        <h1>我刷新页面...刷新我,你会看到这个时间戳不会改变..redis正在工作</h1>
        <br />
        <b>会话中的变量值</b>
        <p>@Model.ValueStoredInRedis</p>
    </div>

    <b>在Redis中缓存: @TempData["IsCaching"],值为 @ViewBag.RedisTimeV </b>
    <br />
    <br />
    @Html.ActionLink("转到结果控制器并检查时间戳", "Index", "Result")
</body>
</html>

Result文件夹

Index.cshtml

@model xxxx.yyyy.ResultViewModel

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width" />
    <title>Index</title>
</head>
<body style="background-color:#008000">
    <div>
        <h1>嗯...会话中的时间戳总是一样的...</h1>
        <br />
        <b>会话中的变量值</b>
        <p>@Model.ValueStoredInRedis</p>
    </div>
    <b>在Redis中缓存: @TempData["IsCaching"],,值为 @ViewBag.RedisTimeV</b>
    <br />
    <br />
    @Html.ActionLink("转到刷新页面并检查时间戳", "RefreshMe", "Home")
</body>
</html>

Web.config

<?xml version="1.0" encoding="utf-8"?>

<configuration>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
  </appSettings>
  <system.web>
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime targetFramework="4.5" />
    <sessionState mode="Custom" customProvider="RedisSessionProvider">
      <providers>
        <add
          name="RedisSessionProvider" type="RedisSessionProvider.RedisSessionStateStoreProvider, RedisSessionProvider" />
      </providers>
    </sessionState>
  </system.web>
</configuration>

运行结果如图:

这里写图片描述


这里写图片描述


这里写图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值