本系列博文已經所有完成,完整系列請訪問:https://blog.zhuliang.ltd/tags/StackExchange-Redis%E7%B3%BB%E5%88%97/html
本文轉自:https://blog.zhuliang.ltd/2020/01/redis/StackExchangeRedis-BasicUsage.htmlgit
- 本系列博文是「僞」官方文檔翻譯,並不是徹底將官方文檔進行翻譯,而是我在查閱、測試原始文檔並轉換爲本身東西后進行的「準」翻譯。
- 原始文檔見此:https://stackexchange.github.io/StackExchange.Redis/
- 本系列本博文基於 redis 5.0.6,系列中部分博文跟官方文檔有出入,有不一樣看法 / 說明不當的地方,還請你們不吝拍磚。
命名空間位於:StackExchange.Redis.ConnectionMultiplexergithub
ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("server1:6379,server2:6379");
說明:示例基於 .NET CORE 2.1,經過 IoC 進行注入,生命週期爲「單例」。
若是不經過 IoC 的話建議直接使用「單例模式」。redis
public class RedisClient : ICache { private readonly RedisSettings _redisSettings; private static IDatabaseAsync _db; public RedisClient(IOptions<RedisSettings> redisSettings) { _redisSettings = redisSettings.Value; var redis = ConnectionMultiplexer.Connect($"{_redisSettings.Address}:{_redisSettings.Port}"); _db = redis.GetDatabase(_redisSettings.DataBase); } #region Implementation of ICache public async Task<bool> SetStringAsync(string key, string content) { return true; } public async Task<string> GetStringAsync(string key) { var result = await _db.StringGetAsync(key); return result; } #endregion }
db.StringIncrement(cacheKey, flags: CommandFlags.FireAndForget);
例子:
客戶端json
private readonly RedisSettings _redisSettings; private static IDatabaseAsync _db; private static ConnectionMultiplexer _redis; public RedisClient(IOptions<RedisSettings> redisSettings) { _redisSettings = redisSettings.Value; _redis = ConnectionMultiplexer.Connect($"{_redisSettings.Address}:{_redisSettings.Port}"); _db = _redis.GetDatabase(_redisSettings.DataBase); } public async Task Subscribe(string channel, Action<RedisChannel, RedisValue> fun) { var sub = _redis.GetSubscriber(); await sub.SubscribeAsync(channel, fun); } public async Task Publish(string channel, string message) { var sub = _redis.GetSubscriber(); await sub.PublishAsync(channel, message); }
訂閱者安全
class Program { static void Main(string[] args) { var builder = new ConfigurationBuilder().AddJsonFile("appsettings.json"); var configuration = builder.Build(); var subscriber = configuration["Subscriber"]; var settings = configuration.GetSection("RedisSettings").Get<RedisSettings>(); var redisClient = new RedisClient(settings); redisClient.Subscribe(settings.ChannelName, (channel, message) => { System.Console.WriteLine($"{subscriber}:{message}"); }).Wait(); System.Console.WriteLine("started"); System.Console.ReadKey(); } }
測試效果:服務器
若要使用服務器命令,須要經過 ConnectionMultiplexer 對象獲取 Server 對象,以下:app
var server = _redis.GetServer($"{_redisSettings.Address}:{_redisSettings.Port},allowAdmin=true"); server.ScriptExists("scripts here");
目前支持的方法以下異步