Asp.net mvc implements distributed cluster sharing Session with Redis

Source: Internet
Author: User
Tags install redis

Asp.net mvc implements distributed cluster sharing Session with Redis

1. During the past two days, we have studied the distributed session issue in Redis. All the information we are looking for online is ServiceStack. redis, but when performing a performance test, we found that the latest v4 version has a limit of up to 6000 requests per child, because the official website is charged for commercialization, fortunately, I got a performance test column in the early stage, or it would be troublesome if something went wrong after I went online. Next I found an NServiceKit. Redis (like ServiceStack. Redis's v3 version) to replace v4's paid version.

2. The solution is to record the user login status through Redis + cookie

Cookie: stores the user ID. This ID is encrypted and can be decrypted in the background using a key.

Redis: key/value storage, key storage for example: user_1. Value stores the user object.

3. First install a Redis instance. The windows version is tested locally. Later, replace the Redis instance in linux with the ip address.

4. Add a Session management class

Public class SessionHelper
{
Private const int secondsTimeOut = 60*20; // The default expiration time is 20 minutes, in seconds.


Public RedisHelper Redis = new RedisHelper (false );
Public LoginUserInfo this [string key]
{
Get
{
String webCookie = WebHelper. GetCookie (key );
If (webCookie = "")
{
Return null;
}
Key = key + "_" + SecureHelper. AESDecrypt (webCookie );

// How many seconds is there before the expiration time?
Long l = Redis. TTL (key );
If (l> = 0)
{
Redis. Expire (key, secondsTimeOut );
}

Return Redis. Get <LoginUserInfo> (key );
}
Set
{
SetSession (key, value );
}
}
Public void SetSession (string key, LoginUserInfo value)
{
If (string. IsNullOrWhiteSpace (key ))
{
Throw new Exception ("Key is Null or Epmty ");
}
WebHelper. SetCookie (key, SecureHelper. AESEncrypt (value. ID. ToString ()));
Key = key + "_" + value. ID;
Redis. Set <LoginUserInfo> (key, value, secondsTimeOut );
}

/// <Summary>
/// Remove the Session
/// </Summary>
/// <Param name = "key"> </param>
/// <Returns> </returns>
Public bool Remove (string key)
{
Var rs = Redis. Remove (key + "_" + SecureHelper. AESDecrypt (WebHelper. GetCookie (key )));
WebHelper. DeleteCookie (key );
Return rs;
}

}

5. Redis operations

Public class RedisHelper: IDisposable
{
Private RedisClient Redis = new RedisClient ("Wagner. 0.0.1", 6379 );
// Cache pool
PooledRedisClientManager prcm = new PooledRedisClientManager ();

// Default cache expiration time, in seconds
Public int secondsTimeOut = 20*60;

/// <Summary>
/// Buffer Pool
/// </Summary>
/// <Param name = "readWriteHosts"> </param>
/// <Param name = "readOnlyHosts"> </param>
/// <Returns> </returns>
Public static PooledRedisClientManager CreateManager (string [] readWriteHosts, string [] readOnlyHosts)
{
Return new PooledRedisClientManager (readWriteHosts, readOnlyHosts,
New RedisClientManagerConfig
{
MaxWritePoolSize = readWriteHosts. Length * 5,
MaxReadPoolSize = readOnlyHosts. Length * 5,
AutoStart = true,
});
}
/// <Summary>
/// Constructor
/// </Summary>
/// <Param name = "OpenPooledRedis"> whether to enable the buffer pool </param>
Public RedisHelper (bool OpenPooledRedis = false)
{

If (OpenPooledRedis)
{
Prcm = CreateManager (new string [] {"127.0.0.1: 6379"}, new string [] {"127.0.0.1: 6379 "});
Redis = prcm. GetClient () as RedisClient;
}
}
/// <Summary>
/// The number of seconds before the expiration time
/// </Summary>
/// <Param name = "key"> </param>
/// <Returns> </returns>
Public long TTL (string key)
{
Return Redis. Ttl (key );
}
/// <Summary>
/// Set the expiration time
/// </Summary>
/// <Param name = "key"> </param>
/// <Param name = "timeout"> </param>
Public void Expire (string key, int timeout = 0)
{
If (timeout> = 0)
{
If (timeout> 0)
{
SecondsTimeOut = timeout;
}
Redis. Expire (key, secondsTimeOut );
}
}

# Region Key/Value Storage
/// <Summary>
/// Set Cache
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
/// <Param name = "key"> cache creation </param>
/// <Param name = "t"> cache value </param>
/// <Param name = "timeout"> expiration time, in seconds,-1: No expiration, 0: Default expiration time </param>
/// <Returns> </returns>
Public bool Set <T> (string key, T t, int timeout = 0)
{
Redis. Set <T> (key, t );
If (timeout> = 0)
{
If (timeout> 0)
{
SecondsTimeOut = timeout;
}
Redis. Expire (key, secondsTimeOut );
}
Return true;

}
/// <Summary>
/// Obtain
/// </Summary>
/// <Typeparam name = "T"> </typeparam>
/// <Param name = "key"> </param>
/// <Returns> </returns>
Public T Get <T> (string key)
{
Return Redis. Get <T> (key );
}
/// <Summary>
/// Delete
/// </Summary>
/// <Param name = "key"> </param>
/// <Returns> </returns>
Public bool Remove (string key)
{
Return Redis. Remove (key );
}
# Endregion

// Release resources
Public void Dispose ()
{
If (Redis! = Null)
{
Redis. Dispose ();
Redis = null;
}
GC. Collect ();

}
}

Install Redis in Ubuntu 12.10 (graphic explanation) + Jedis to connect to Redis

Redis series-installation, deployment, and maintenance

Install Redis in CentOS 6.3

Learning notes on Redis installation and deployment

Redis. conf

Redis details: click here
Redis: click here

This article permanently updates the link address:

Related Article

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.