Nginx+redis implement session sharing. NET Distributed architecture

Source: Internet
Author: User
Tags redis server

On two documents describes how to install and encapsulate Redis This article is mainly recorded under how to implement Nginx+redis implementation session sharing

Current session Problem Point

and Love and hate. Session

Just contact the development of the program people must love the session, because the session to let the HTTP from stateless to stateful, the page between the value, user-related information, some unchanged data, and even find out the DataTable can also be put in, the value of the time only need session[ Key] can be, it is very convenient. The session is really a weapon, people block killing Buddha, but any thing is sealed as a sharp weapon is also a double-edged sword, the session of many problems we have to face.

"Frequently asked questions, see"

I believe that the first to see this problem, the old programmer will be a shiver in the heart, the session is one of the causes, we will also think of this scenario, "I go, is not the session and lost, let users re-login", the incident report will fill in:. NET provisions, the user login after a long period of no operation caused. The solution is: The session time is adjusted to 9999.

The result is that it continues to occur, and the session is still lost.

" Common cause of session loss"

1, session timeout, the user opens the page, the page for a long time does not operate will cause this cause

2. IIS application pool recycle, or restart

3. Web. config modification, that is, IIS application pool restart

4. dll is replaced or dynamic page modified, that is, IIS application pool restarts

5. The antivirus software scans the. config file, which may cause IIS application pool Recycling

6. Cookies are disabled by the user's browser

7. Other reasons

Other reasons are a bit irresponsible, but a lot of programmers can not find out what causes the session is lost, but the session is lost I boil down to two categories, one is the data key lost, one is the session content database lost, everyone so good understanding, User browser Disable cookie must be key gone. IIS application pool recycling must result in the loss of the content cache table for the session and, of course, some other reasons.

3. Solve the long Way to lose the session

These methods can be used to solve the missing session.

1. InProc: The session is stored in the process.

2. StateServer: The session is stored in a separate state service (ASP.

3. SQL Server: Save the session to SQL Server.

4, cookieless: Set the way the client session is stored.

After using these methods, some of them should be lost, some stable speed but slow.

The following step-by-step implementation of Nginx+redis instead of session

We've installed it in front of Redis.

1. Download Nginx .

Address: Http://nginx.org/download/nginx-1.9.9.zip

2. Write the bat file operation Nginx

cls @ECHO OFF SET Nginx_path=D:set Nginx_dir="D:\Test\nginx-1.9.3\ "Color 0a TITLE Nginx hypervisor Power by Ants (http://leleroyn.cnblogs.com)GOTO menu:menu CLS ECHO. ECHO. * * * * Nginx hypervisor Power by Ants (http://leleroyn.cnblogs.com) * * *ECHO. * *ECHO.*1Start Nginx *ECHO.* *ECHO.*2Close Nginx *ECHO.* *ECHO.*3Restart Nginx *ECHO.* *ECHO.*4ExitECHO.* *ECHO.* * * * * * * * * * * * * * * * * * * * * * * *ECHO. ECHO. Please enter the serial number of the selected item:Set/P id=IF"%id%"=="1"GOTO cmd1 IF"%id%"=="2"GOTO cmd2 IF"%id%"=="3"GOTO cmd3 IF"%id%"=="4"EXIT pause:cmd1 ECHO. ECHO. Start Nginx ... IF not EXIST%nginx_dir%nginx.exe ECHO%nginx_dir%Nginx.exe does not exist%nginx_path%CD%nginx_dir%IF EXIST%nginx_dir%nginx.exe start Nginx.exe ECHO. OK PAUSE GOTO menu:cmd2 ECHO. ECHO. Close Nginx ... taskkill/f/im Nginx.exe >nul ECHO. OK PAUSE GOTO menu:cmd3 ECHO. ECHO. Close Nginx ... taskkill/f/im Nginx.exe >nul ECHO. OK goto cmd1 Goto MENU

3. Configure Nginx

#user nobody;worker_processes1; #error_log logs/Error.log, #error_log logs/error.log notice; #error_log logs/error.log info; #pid logs/nginx.pid;events {worker_connections1024x768;}    HTTP {include mime.types; Default_type Application/octet-stream; #log_format Main'$remote _addr-$remote _user [$time _local] "$request"'    #                  '$status $body _bytes_sent "$http _referer"'    #                  '"$http _user_agent" "$http _x_forwarded_for "'; #access_log logs/Access.log Main;    Sendfile on;    #tcp_nopush on; #keepalive_timeout0; Keepalive_timeout $; Upstream Jq_one {server10.110.1.42:1100; Server10.110.1.42:1101;    } #gzip on; server {Listen1108;        server_name localhost; #charset Koi8-R; #access_log logs/Host.access.log Main; Location/{root HTML;            Index index.html index.htm; #其中jq_one the cluster name Proxy_pass HTTP that corresponds to the upstream setting://Jq_one;#设置主机头和客户端真实地址 so that the server obtains the client real IP proxy_set_header Host $host; Proxy_set_header X-real-IP $remote _addr; Proxy_set_header X-forwarded-For $proxy _add_x_forwarded_for; } #error_page404/404. html; # REDIRECT Server error pages to theStaticPage/50x.html # Error_page - 502 503 504/50x.html; Location= /50x.html {root html; } # Proxy The PHP scripts to Apache listening on127.0.0.1: the# #location~\.php$ {# Proxy_pass http://127.0.0.1;#} # Pass the PHP scripts to FastCGI server listening on127.0.0.1:9000# #location~\.php$ {# root HTML; # Fastcgi_pass127.0.0.1:9000;        # Fastcgi_index index.php; # Fastcgi_param Script_filename/Scripts$fastcgi_script_name;        # include Fastcgi_params; #} # Deny access to. htaccess files,ifApache's Document Root# concurs with Nginx'S One# #location~ /\.ht {# deny all; #}} # anotherVirtualHostusingMix of ip-, name-, and port-based configuration # #server {# listen8000; # Listen Somename:8080;    # server_name somename alias Another.alias; # Location/{# root HTML;    # index index.html index.htm; #} #} # HTTPS Server # #server {# listen443SSL;    # server_name localhost;    # ssl_certificate Cert.pem;    # Ssl_certificate_key Cert.key;    # Ssl_session_cache shared:ssl:1m;    # ssl_session_timeout 5m; # Ssl_ciphers High:!anull:!MD5;    # ssl_prefer_server_ciphers on; # Location/{# root HTML;    # index index.html index.htm; #    }    #}}

Its important note upstream Jq_one {server 10.110. 1.42:1100; server 10.110.   1.42:1101;} Be sure to put it in http{} or the Nginx will not start.

4. After launching Nginx successfully, build your own two websites to publish to IIS

What I'm building here a Webapi a WEBMVC note redis Test These are the values I stored with Redis instead of session.

5. Detailed construction site precautions

First download Redissessionprovider/stackexchange.redis via NuGet

Modify the webconfig of two sites

<system.web>    <!--redis session Sharing--    <sessionstate mode="Custom" customprovider="redissessionprovider">      <providers>        <add Name="redissessionprovider " type= " Redissessionprovider.redissessionstatestoreprovider, Redissessionprovider" />      </ providers>    </sessionState>  </system.web>

Registering the Redis session share in the Global.asax file

protected voidApplication_Start () {//Redis implements session sharingStackExchange.Redis.ConfigurationOptions redisconfigopts = StackExchange.Redis.ConfigurationOptions.Parse ("127.0.0.1:6379"); RedisSessionProvider.Config.RedisConnectionConfig.GetSERedisServerConfig= (HttpContextBase context) =            {                return Newkeyvaluepair<string, stackexchange.redis.configurationoptions>(                    "defaultconnection", redisconfigopts);            };            Arearegistration.registerallareas ();            Globalconfiguration.configure (Webapiconfig.register);            Filterconfig.registerglobalfilters (globalfilters.filters);            Routeconfig.registerroutes (routetable.routes);        Bundleconfig.registerbundles (Bundletable.bundles); }

The Redis server address and port at the time of registration can be stored and retrieved in a configured manner.

After the registration is complete, the following test uses the Redis session

 public   ActionResult Index () {View Bag.title  =  " home page  "  ; session[  " test   "] =  " redis test   "            ; Viewbag.session  = Session[ " test  Span style= "COLOR: #800000" > " ".            ToString ();         return   View (); }

Storage session["test"] = "redis test";

Read session["test"]. ToString ();

Redis accepts stored data when you open a Web page

6. Test Nginx+redis+session

MVC website

F5 Refresh several times

WEBAPI website

Success!!!

Nginx+redis implement session sharing. NET Distributed architecture

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.