关于StackExchange.Redis的一些总结

NuGet包地址:

StackExchange.Redis

官网地址:

StackExchange.Redis

关于StackExchange.Redis的基本用法可以查看:

C# StackExchange.Redis 用法总结

其中讲到了使用StackExchange.Redis来启用分布式锁,这在微服务架构中很有用。

还可以参考:

StackExchange.Redis - LockTake / LockRelease Usage

关于Redis分布式锁可以查看下面几篇文章:

Redis分布式锁的正确实现方式(Java版)

redis 基于SETNX和EXPIRE的用法 实现redis 分布式锁

Redis分布式锁/Redis的setnx命令如何设置key的失效时间(同时操作setnx和expire)

那么下面我们给出一个示例(基于.NET Core控制台项目),来看看怎么使用StackExchange.Redis来进行Redis配置和数据存取:

using StackExchange.Redis;
using System;

namespace NetCoreRedis
{
    class Program
    {
        static void Main(string[] args)
        {
            ConfigurationOptions configuration = new ConfigurationOptions();
            configuration.ConnectTimeout = 5000;//设置建立连接到Redis服务器的超时时间为5000毫秒
            configuration.SyncTimeout = 5000;//设置对Redis服务器进行同步操作的超时时间为5000毫秒
            configuration.AsyncTimeout = 5000;//设置对Redis服务器进行异步操作的超时时间为5000毫秒
            configuration.EndPoints.Add("192.168.1.105:6380");//设置Redis的IP地址和端口号
            configuration.Password = "1qaz@WSX3edc$RFV";//设置连接Redis的密码
            configuration.Ssl = true;//设置启用SSL安全加密传输Redis数据
            //configuration.SslProtocols = System.Security.Authentication.SslProtocols.Tls;//还可以通过SslProtocols属性指定SSL具体用到的是什么协议,不过这个属性不是必须的

            using (ConnectionMultiplexer connectionMultiplexer = ConnectionMultiplexer.Connect(configuration))
            {
                var database = connectionMultiplexer.GetDatabase(0);

                //设置和获取字符串
                RedisKey redisStringKey = new RedisKey("DemoStringKey");
                RedisValue redisStringValue = new RedisValue();
                redisStringValue = "DemoValue";

                bool isSuccessful = database.StringSet(redisStringKey, redisStringValue, expiry: TimeSpan.FromSeconds(30), when: When.NotExists);//等于Redis命令setnx和expire的结合体,是原子性的。
                Console.WriteLine(isSuccessful);

                string redisReturnStringValue = database.StringGet(redisStringKey);

                //设置和获取字节数组
                RedisKey redisBytesKey = new RedisKey("DemoBytesKey");
                RedisValue redisBytesValue = new RedisValue();
                redisBytesValue = new byte[] { 0x01, 0x02, 0x03, 0x04, 0x05 };

                isSuccessful = database.StringSet(redisBytesKey, redisBytesValue, expiry: TimeSpan.FromSeconds(30), when: When.NotExists);//等于Redis命令setnx和expire的结合体,是原子性的。
                Console.WriteLine(isSuccessful);

                byte[] redisReturnBytesValue = database.StringGet(redisBytesKey);
            }

            Console.WriteLine("Press any key to end...");
            Console.ReadKey();
        }
    }
}

其中关于ConfigurationOptions的配置,可以查看:

https://stackexchange.github.io/StackExchange.Redis/Configuration.html

关于存取byte[]字节数组,可以查看:

How to store a byte array to StackExchange.Redis?

原文地址:https://www.cnblogs.com/OpenCoder/p/13236570.html