隐藏

.Net 站点在Windows环境借助Nginx和Redis实现负载均衡系列(三)

发布:2019/4/18 22:43:59作者:管理员 来源:本站 浏览次数:1042

.Net 站点使用Redis存储Session信息,借助Redis实现多个站点公用Session信息

1.新建一个web项目,我新建的是一个空的MVC的项目。

   新建好之后添加Home控制器,新建Index Action方法和View视图文件。

2.使用NuGet添加RedisSessionStateProvider这个引用。

   安装完成之后会自动添加三个引用:

        Microsoft.Web.RedisSessionStateProvider

        StackExchange.Redis.StrongName

        StackExchange.Redis

   Web.config 会自动添加如下的配置文件   

复制代码
<sessionState mode="Custom" customProvider="MySessionStateStore">
      <providers>
        <!-- For more details check https://github.com/Azure/aspnet-redis-providers/wiki --> <!-- Either use 'connectionString' OR 'settingsClassName' and 'settingsMethodName' OR use 'host','port','accessKey','ssl','connectionTimeoutInMilliseconds' and 'operationTimeoutInMilliseconds'. -->
        <!-- 'throwOnError','retryTimeoutInMilliseconds','databaseId' and 'applicationName' can be used with both options. -->
        <!--
          <add name="MySessionStateStore" host = "127.0.0.1" [String]
            port = "" [number]
            accessKey = "" [String]
            ssl = "false" [true|false]
            throwOnError = "true" [true|false]
            retryTimeoutInMilliseconds = "5000" [number]
            databaseId = "0" [number]
            applicationName = "" [String]
            connectionTimeoutInMilliseconds = "5000" [number]
            operationTimeoutInMilliseconds = "1000" [number]
            connectionString = "<Valid StackExchange.Redis connection string>" [String]
            settingsClassName = "<Assembly qualified class name that contains settings method specified below. Which basically return 'connectionString' value>" [String]
            settingsMethodName = "<Settings method should be defined in settingsClass. It should be public, static, does not take any parameters and should have a return type of 'String', which is basically 'connectionString' value.>" [String]
            loggingClassName = "<Assembly qualified class name that contains logging method specified below>" [String]
            loggingMethodName = "<Logging method should be defined in loggingClass. It should be public, static, does not take any parameters and should have a return type of System.IO.TextWriter.>" [String] />
        -->
        <add name="MySessionStateStore" type="Microsoft.Web.Redis.RedisSessionStateProvider" host="" accessKey="" ssl="true" />
      </providers>
    </sessionState>
复制代码

    host改为你的redis服务所在的ip地址,我的是127.0.0.1,ssl给为false,端口号如果不是默认的端口,就自行修改port="XXXX"。

3.在Index方法中添加Session的测试代码测试Redis保存数据是否成功。如果保存的是复杂类型,要加上可序列化标签[Serializable],如下是我的测试代码

复制代码
public class HomeController : Controller
    { private static string _webSiteStr; public static string WebSite
        { get { if (string.IsNullOrWhiteSpace(_webSiteStr))
                {
                    _webSiteStr = System.Configuration.ConfigurationManager.AppSettings["WebSite"];
                } return _webSiteStr;
            }
        } // GET: Home public ActionResult Index()
        {
            System.Web.HttpContext.Current.Session["firstTest"] = "1231";
            Student p = new Student()
            {
                 Age=26,Name="liuyu7177" };
            System.Web.HttpContext.Current.Session["Student"] = p; return View();
        } // GET: Home public ContentResult Two()
        { var str = (string)System.Web.HttpContext.Current.Session["firstTest"] + WebSite; var p = (Student)System.Web.HttpContext.Current.Session["Student"]; return Content(str);
        }
    }

    [Serializable] public class Student
    { public string Name { get; set; } public int Age { get; set; }
    }
复制代码

其中WebSite这个静态属性是在发布多个站点时用来区分访问到的是那个站点。

在Web.config 中添加一个节点  <add key="WebSite" value="WebSite1" />

启动调试,如果/Home/Two 页面成功返回Session里面的内容,说明借助Redis存储Session数据成功。

4.发布两个或两个以上的站点

  用刚刚新建的项目在IIS上挂两个站点。新建两个发布目录,更改Web.config文件,一个value设置WebSite1,一个value设置WebSite2.

  第一个站点命名为RedisSessionTest,绑定的ip为127.0.0.1 端口是88

  第二个站点命名为RedisSessionTestTwo,绑定的ip为127.0.0.1 端口是89

  打开浏览器分别访问:http://127.0.0.1:88/Home/Index,http://127.0.0.1:89/Home/Two,http://127.0.0.1:88/Home/Two

  第一个站点返回1231WebSite1,第二个站点返回1231WebSite2,说明Session共享成功。

  有两个问题要注意:

       1.这个两个站点是在同样的顶级域名之下。

       2.第二个站点不要打开Home/Index页面,不然就不能确定第二个站点是否和第一个站点共享Session了。

最后:Redis要安装比较新的版本,ssl要设置为false,不然可能会报 No connection is available to service this operation: EVAL 这个错误