C#redis缓存应用
Redis
redis是一种非关系型数据库(关系型数据库即SQL server,MySQL等),但多用于缓存技术.因为它是一种内存告诉缓存数据库,存储数据的方式为Key-value,即键值对.而且redis还支持多种数据类型,如:string、list、set、zset(sorted set)、hash。
redsi特点:
①redis以内存作为存储的介质,读写速率极高,远超过数据库,
②redis跟memcache不同,redis存储的数据是持久化的,不会因为断电重启造成的数据丢失.(reids的存储分为内存存储,磁盘存储和log文件三部分,重启后,redis从磁盘重新将数据加载到内存中,再通过配置文件对其进行配置,持久化的原因)
③redis可以配置集群,就像一些大公司的服务器一样,它可以建立多个redis用来缓存,而且redis不在客户端,也不再服务端,是一个独立的部分
redis两种文件格式:
①全量数据:是把内存中的数据写入磁盘,便于下次读取文件进行夹杂
②增量请求:是将内存中的数据序列化为操作请求,用于读取文件进行replay得到数据,序列化的操作包括SET,RPUSH,SADD,ZADD
Redis的安装:
包地址:https://files.cnblogs.com/files/lbjlbj/Redis3.7z
运行->cmd->CD C:\redis(C:\redis CD 进入到盘符(记得有空格),上面那个解压后把它改名为redis,放到了C盘,也可以放其他盘)
set auth 密码名,是用来设置密码.(如果忘记了密码:redis文件夹下redis.windows-service.conf记事本打开CTRL+F requirepass 即可)
redis在C#中的实际用法:
******在使用redis缓存时,须先启动服务器,CD C:\redis redis-server.exe redis.windows.conf
dll文件:https://files.cnblogs.com/files/lbjlbj/dll.7z
可能会存在ConfigurationManager会报错,还需自行搜索添加引用
奉上一个封装好的Helper类
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 操作类 /// </summary> public class RedisHelper { /// <summary> /// 连接字符串 /// </summary> private static readonly string ConnectionString = ConfigurationManager.ConnectionStrings["RedisConnectionString"].ConnectionString; /// <summary> /// 锁 /// </summary> private readonly object _lock = new object(); /// <summary> /// 连接对象 /// </summary> private volatile IConnectionMultiplexer _connection; /// <summary> /// 数据库 /// </summary> private IDatabase _db; public RedisHelper() { _connection = ConnectionMultiplexer.Connect(ConnectionString); _db = GetDatabase(); } /// <summary> /// 获取连接 /// </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> /// 获取数据库 /// </summary> /// <param name="db"></param> /// <returns></returns> public IDatabase GetDatabase(int? db = null) { return GetConnection().GetDatabase(db ?? -1); } /// <summary> /// 设置 /// </summary> /// <param name="key">键</param> /// <param name="data">值</param> /// <param name="cacheTime">时间</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> /// 根据键获取值 /// </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> /// 反序列化 /// </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> /// 判断是否已经设置 /// </summary> /// <param name="key"></param> /// <returns></returns> public virtual bool IsSet(string key) { return _db.KeyExists(key); } /// <summary> /// 序列化 /// </summary> /// <param name="data"></param> /// <returns>byte[]</returns> private byte[] Serialize(object data) { var json = JsonConvert.SerializeObject(data); return Encoding.UTF8.GetBytes(json); } } }
AppConfig中配置:
<connectionStrings> <add name="RedisConnectionString" connectionString="localhost"/> </connectionStrings>
最后功能实现:
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 on 2020-11-16 16:22 Asura&Angle 阅读(162) 评论(0) 编辑 收藏 举报