Redis practice and Session cache, redis practice session

Source: Internet
Author: User

Redis practice and Session cache, redis practice session

C # There are many Redis database operations, such as C # Redis Client is very useful,

Search on NuGetServiceStack. Redis

Install it in the project. The following references will be added

 

The ServiceStack. Redis database provides us with the RedisClient class, which inherits the IDisposable interface, so we can use the using block instead of try-catch-finally.

Redis has several common data types:

1. String

2. Hash (Hash table)

3. List (two-way linked List)

4. Set (Set type)

5. Sorted set

Common Methods in RedisClient

Method Description
Add Adds a record based on the input key-value. If the key already exists, false is returned.
FlushAll Invalidate all caches (clear all keys of all Redis databases)
Get Obtains the value of a record based on the input key.
GetAll Obtains the value of multiple records based on multiple input keys.
Remove Removes a record based on the input key.
RemoveAll Removes multiple records based on multiple input keys.
Replace Overwrites the value of a record based on the input key. If the key does not exist, it is not added.
Set Modifies the value of a record based on the input key. If the key does not exist, add
SetAll Overwrite multiple records based on multiple input keys
Increment  
Decrement  

 

For Object Storage, RedisClient provides:

Public bool Set <T> (string key, T value );
Public bool Set <T> (string key, T value, TimeSpan expiresIn );
Public bool Set <T> (string key, T value, DateTime expiresAt );

Public T Get <T> (string key );

Generic method, which can easily store object.

For some transactions,RedisClientProvided:

Method Description
AcquireLock Apply to lock a Key (other objects cannot be accessed during this period)
CreateTransaction Creates a transaction and returns an IRedisTransaction object.
Createsub.pdf Create a subscription event and return an iredissubscribe object.
CreatePipeline Returns an IRedisPipeline object.

 

Next we will write a simple Redis help class named RedisHelper to prepare for SessionHelper.

Here, _ ip = "127.0.0.1" indicates the local return address, and _ port = 6379 indicates the Redis service port.

  public class RedisHelper : IRedisHelper    {        private readonly string _ip = "127.0.0.1";        private readonly int _port = 6379;        private readonly string _passWord = string.Empty;        public int Expire { get; set; }        public RedisHelper(int expireTime=1200)        {            Expire = expireTime;        }        public RedisHelper(string ip, int port, string passWord, int expireTime=1200)        {            _ip = ip;            _port = port;            _passWord = passWord;            Expire = expireTime;        }        public T GetValue<T>(string key)        {            using (var redisClient = GetRedisClient())            {                return redisClient.Get<T>(key);            }        }        public bool SetValue(string key,string value)        {            using (var redisClient = GetRedisClient())            {                if (!redisClient.Set(key, value)) return false;                SetExpire(redisClient, key);                return true;            }        }        public void SetValue<T>(string key,T value)        {            using (var redisClient = GetRedisClient())            {                if (redisClient.Set<T>(key, value))                     SetExpire(redisClient, key);            }        }        public void Delete(string key)        {            using (var redisClient = GetRedisClient())            {                redisClient.Remove(key);            }        }        private RedisClient GetRedisClient()        {            return new RedisClient(_ip, _port, _passWord);        }        private void SetExpire(IRedisNativeClient redisClient,string key)        {            redisClient.Expire(key, Expire);        }    }

  

 

With RedisHelper, let's write a class for Session management:

    public class SessionHelper<T>:RedisHelper, ISessionHelper<T>    {        public T GetSession(string token)        {            return !string.IsNullOrEmpty(token) ? GetValue<T>(token) : default(T);        }        public string CreateSession(T value)        {            var guid = Guid.NewGuid().ToString("D");            SetValue<T>(guid,value);                        return guid;        }        public void RemoveSession(string token)        {            Delete(token);        }    }

 

So far, we have written a Login method in the Controller to test it.

Public ActionResult Login () {// logon logic var userLoginInfo = new UserSession {Id = 12, Name = "Test", Permissions = new List <string> {"Home. page "}}; var token = _ sessionHelper. createSession (userLoginInfo); var cookie = new HttpCookie ("User") {Expires = DateTime. now. addMinutes (20), Value = token}; Response. appendCookie (cookie); return View ();}

 

Of course, if the result is a successful image, it will not be pasted. This is the most basic session management mechanism implemented by Cookie + cache.

Some content is referenced in the Development of ASP. NET Redis

Servicdisclient of ServiceStack. Redis <Article 3>

 

 

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.