【11】Redis .net 实例 StackExchange.Redis框架

1.创建测试项目并下载nuget包:StackExchange.Redis

PM> Install-Package StackExchange.Redis

【11】Redis .net 实例 StackExchange.Redis框架_第1张图片


2.创建 RedisHelper类

public class RedisHelper
{
	private static string _conn = "127.0.0.1:6379";

	#region string类型
	/// 
	/// 根据Key获取值
	/// 
	/// 键值
	/// System.String.
	public static string StringGet(string key)
	{
		try
		{
			using (var client = ConnectionMultiplexer.Connect(_conn))
			{
				return client.GetDatabase().StringGet(key);
			}
		}
		catch (Exception)
		{
			return null;
		}
	}

	/// 
	/// 批量获取值
	/// 
	public static string[] StringGetMany(string[] keyStrs)
	{
		var count = keyStrs.Length;
		var keys = new RedisKey[count];
		var addrs = new string[count];

		for (var i = 0; i < count; i++)
		{
			keys[i] = keyStrs[i];
		}
		try
		{
			using (var client = ConnectionMultiplexer.Connect(_conn))
			{
				var values = client.GetDatabase().StringGet(keys);
				for (var i = 0; i < values.Length; i++)
				{
					addrs[i] = values[i];
				}
				return addrs;
			}
		}
		catch (Exception)
		{
			return null;
		}
	}


	/// 
	/// 单条存值
	/// 
	/// key
	/// The value.
	/// true if XXXX, false otherwise.
	public static bool StringSet(string key, string value)
	{

		using (var client = ConnectionMultiplexer.Connect(_conn))
		{
			return client.GetDatabase().StringSet(key, value);
		}
	}


	/// 
	/// 批量存值
	/// 
	/// key
	/// The value.
	/// true if XXXX, false otherwise.
	public static bool StringSetMany(string[] keysStr, string[] valuesStr)
	{
		var count = keysStr.Length;
		var keyValuePair = new KeyValuePair[count];
		for (int i = 0; i < count; i++)
		{
			keyValuePair[i] = new KeyValuePair(keysStr[i], valuesStr[i]);
		}
		using (var client = ConnectionMultiplexer.Connect(_conn))
		{
			return client.GetDatabase().StringSet(keyValuePair);
		}
	}

	#endregion

	#region 泛型
	/// 
	/// 存值并设置过期时间
	/// 
	/// 
	/// key
	/// 实体
	/// 过期时间间隔
	/// true if XXXX, false otherwise.
	public static bool Set(string key, T t, TimeSpan ts)
	{
		var str = JsonConvert.SerializeObject(t);
		using (var client = ConnectionMultiplexer.Connect(_conn))
		{
			return client.GetDatabase().StringSet(key, str, ts);
		}
	}

	/// 
	/// 
	/// 根据Key获取值
	/// 
	/// 
	/// The key.
	/// T.
	public static T Get(string key) where T : class
	{
		using (var client = ConnectionMultiplexer.Connect(_conn))
		{
			var strValue = client.GetDatabase().StringGet(key);
			return string.IsNullOrEmpty(strValue) ? null : JsonConvert.DeserializeObject(strValue);
		}
	}
	#endregion
}


3.主程序调用

    class Program
    {
        static void Main(string[] args)
        {
            string key = "test", value = "http://www.sina.com";
            bool isRight = RedisHelper.StringSet(key, value);
            if(isRight)
                Console.WriteLine("保存Redis:key.{0} value.{1}成功", key, value);
            string result = RedisHelper.StringGet(key);
            Console.WriteLine("Redis:key.{0} value.{1}", key, result);
            var model = new TestModel() { Id = 100, Name = "RedisValue" };
            isRight = RedisHelper.Set("model", model, new TimeSpan(0, 10, 0));
            var modelResult = RedisHelper.Get("model");
            if(modelResult != null)
                Console.WriteLine("RedisModel:Id.{0} Name.{1}", modelResult.Id, modelResult.Name);
            Console.ReadLine();
        }
    }

    [Serializable]
    public class TestModel
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

4.运行结果

【11】Redis .net 实例 StackExchange.Redis框架_第2张图片


Windows环境安装参考上一篇



你可能感兴趣的:(.net技术积累)