C#redis cache application

Redis

Redis is a non relational database (relational database, i.e. SQL server,MySQL, etc.), but it is mostly used for caching technology Because it is a memory cache database, the way to store data is key value, that is, key value pair Moreover, redis also supports multiple data types, such as string, list, set, zset(sorted set) and hash.

redsi features:

① redis uses memory as the storage medium, and its read-write rate is very high, far exceeding that of the database,

② Unlike memcache, the data stored in redis is persistent and will not be lost due to power failure and restart (the storage of reids is divided into three parts: memory storage, disk storage and log file. After restart, redis reloads the data from disk to memory, and then configures it through the configuration file. The reason for persistence)

③ Redis can configure clusters. Just like the servers of some large companies, it can establish multiple redis for caching. Moreover, redis is not on the client or server, and it is an independent part

redis has two file formats:

① Full data: write the data in the memory to the disk, so as to read the file next time

② Incremental request: serialize the data in memory into an operation request, which is used to read the file and replay the data. The serialized operations include set, rpush, Sadd and zadd

Redis installation:

Package address: https://files.cnblogs.com/files/lbjlbj/Redis3.7z

Run - > CMD - > CD C: \ redis (C: \ redis CD enters the drive letter (remember there is a space), unzip the above one, change its name to redis, put it on drive C, or put other drives)

 

 redis-server.exe redis.windows.conf, and other instances as shown in the figure will prove successful (do not close the console first)
 
 
Open another console, the same: CD C:\redis
 redis-cli.exe -h 127.0.0.1 -p 6379
Set # myKey # abc(myKey is the Key,abc is the value,set save)
Get myKey(get read)

set auth password name is used to set the password (if you forget your password: open CTRL+F requirepass in redis.windows-service.conf Notepad under redis folder)

 

The actual usage of redis in C #:

******When using redis cache, you must first start the server, CD C: \ redis redis server exe redis.windows.conf

DLL file: https://files.cnblogs.com/files/lbjlbj/dll.7z

There may be errors reported by the configuration manager, and you need to search and add references by yourself

 

  

 

 

 

 

Offer a encapsulated Helper class

using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace ConsoleApp1
{
    /// <summary>
    ///Redis operation class
    /// </summary>
    public class RedisHelper
    {
        /// <summary>
        ///Connection string
        /// </summary>
        private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["RedisConnectionString"].ConnectionString;
        /// <summary>
        ///Lock
        /// </summary>
        private readonly object _lock = new object();
        /// <summary>
        ///Connection object
        /// </summary>
        private volatile IConnectionMultiplexer _connection;
        /// <summary>
        ///Database
        /// </summary>
        private IDatabase _db;
        public RedisHelper()
        {
            _connection = ConnectionMultiplexer.Connect(ConnectionString);
            _db = GetDatabase();
        }
        /// <summary>
        ///Get connection
        /// </summary>
        /// <returns></returns>
        protected IConnectionMultiplexer GetConnection()
        {
            if (_connection != null && _connection.IsConnected)
            {
                return _connection;
            }
            lock (_lock)
            {
                if (_connection != null && _connection.IsConnected)
                {
                    return _connection;
                }

                if (_connection != null)
                {
                    _connection.Dispose();
                }
                _connection = ConnectionMultiplexer.Connect(ConnectionString);
            }

            return _connection;
        }
        /// <summary>
        ///Get database
        /// </summary>
        /// <param name="db"></param>
        /// <returns></returns>
        public IDatabase GetDatabase(int? db = null)
        {
            return GetConnection().GetDatabase(db ?? -1);
        }
        /// <summary>
        ///Set
        /// </summary>
        ///< param name = "key" > key < / param >
        ///< param name = "data" > value < / param >
        ///< param name = "cachetime" > time < / param >
        public virtual void Set(string key, object data, int cacheTime)
        {
            if (data == null)
            {
                return;
            }
            var entryBytes = Serialize(data);
            var expiresIn = TimeSpan.FromMinutes(cacheTime);

            _db.StringSet(key, entryBytes, expiresIn);
        }
        /// <summary>
        ///Get value according to key
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public virtual T Get<T>(string key)
        {

            var rValue = _db.StringGet(key);
            if (!rValue.HasValue)
            {
                return default(T);
            }

            var result = Deserialize<T>(rValue);

            return result;
        }
        /// <summary>
        ///Deserialization
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="serializedObject"></param>
        /// <returns></returns>
        protected virtual T Deserialize<T>(byte[] serializedObject)
        {
            if (serializedObject == null)
            {
                return default(T);
            }
            var json = Encoding.UTF8.GetString(serializedObject);
            return JsonConvert.DeserializeObject<T>(json);
        }
        /// <summary>
        ///Judge whether it has been set
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public virtual bool IsSet(string key)
        {
            return _db.KeyExists(key);
        }
        /// <summary>
        ///Serialization
        /// </summary>
        /// <param name="data"></param>
        /// <returns>byte[]</returns>
        private byte[] Serialize(object data)
        {
            var json = JsonConvert.SerializeObject(data);
            return Encoding.UTF8.GetBytes(json);
        }
    }
}

Configuration in AppConfig:

 <connectionStrings>
    <add name="RedisConnectionString" connectionString="localhost"/>
  </connectionStrings>

Finally, function realization:

class Program
    {
        static void Main(string[] args)
        {
            var s = "a";
            //RedisCacheHelper.Add("abc",s,DateTime.Now.AddDays(1));

            //Console.WriteLine("ok");

            //Console.WriteLine(RedisCacheHelper.Get<string>("abc"));
            new RedisHelper().Set("abc", s, 10);
            Console.WriteLine("ok");
            Console.ReadKey();
        }
    }

 

 

Posted by joeynovak on Sat, 07 May 2022 09:58:23 +0300