时间:2023-10-23 13:12:01 | 来源:网站运营
时间:2023-10-23 13:12:01 来源:网站运营
.net 有没有比较好用的redis 集群解决方案?:该原文是Ayende Rahien大佬业余自己在使用C# 和 .NET构建一个简单、高性能兼容Redis协议的数据库的经历。首先这个"Redis"是非常简单的实现,但是他在优化这个简单"Redis"路程很有趣,也能给我们在从事性能优化工作时带来一些启示。Socket.Select()
方法,但是需要我们自己在此基础上构建一切(比如我们必须写代码处理缓冲、字符串等等)。ConcurrentDictionary
。ConcurrentDictionary
的可伸缩性。即使我使用了1024个分片的锁,它仍然占用50%的时间开销。问题是,我们能做得更好吗?我们可以尝试一个更好的选择,就是我们不再使用ConcurrentDictionary
,而是直接使用单独的Dictionary
来分片,这样的话每个Dictionary
都不需要并发就可以访问。Dictionary
)来完成这项工作。因为我是16核的机器,我将创建10个这样的线程(假设它们每个都能分配到1个核心),并且我能够将I/O处理放到其余的6个核心上。SubString
函数的调用开销也很大,超过整个系统开销的6%。在研究系统其它部分时,看到了这个:using System.Collections.Concurrent;using System.Net.Sockets;using System.Threading.Channels;var listener = new TcpListener(System.Net.IPAddress.Any, 6379);listener.Start();var redisClone = new RedisClone();while (true){ var client = listener.AcceptTcpClient(); var _ = redisClone.HandleConnection(client); // run async}public class RedisClone{ ShardedDictionary _state = new(Environment.ProcessorCount / 2); public async Task HandleConnection(TcpClient tcp) { var _ = tcp; var stream = tcp.GetStream(); var client = new Client { Tcp = tcp, Dic = _state, Reader = new StreamReader(stream), Writer = new StreamWriter(stream) { NewLine = "/r/n" } }; await client.ReadAsync(); }}class Client{ public TcpClient Tcp; public StreamReader Reader; public StreamWriter Writer; public string Key; public string? Value; public ShardedDictionary Dic; List<string> Args = new(); public async Task ReadAsync() { try { Args.Clear(); var lineTask = Reader.ReadLineAsync(); if (lineTask.IsCompleted == false) { await Writer.FlushAsync(); } var line = await lineTask; if (line == null) { using (Tcp) { return; } } if (line[0] != '*') throw new InvalidDataException("Cannot understand arg batch: " + line); var argsv = int.Parse(line.Substring(1)); for (int i = 0; i < argsv; i++) { line = await Reader.ReadLineAsync(); if (line == null || line[0] != '$') throw new InvalidDataException("Cannot understand arg length: " + line); var argLen = int.Parse(line.Substring(1)); line = await Reader.ReadLineAsync(); if (line == null || line.Length != argLen) throw new InvalidDataException("Wrong arg length expected " + argLen + " got: " + line); Args.Add(line); } switch (Args[0]) { case "GET": Key = Args[1]; Value = null; break; case "SET": Key = Args[1]; Value = Args[2]; break; default: throw new ArgumentOutOfRangeException("Unknown command: " + Args[0]); } Dic.Run(this); } catch (Exception e) { await HandleError(e); } } public async Task NextAsync() { try { if (Value == null) { await Writer.WriteLineAsync("$-1"); } else { await Writer.WriteLineAsync($"${Value.Length}/r/n{Value}"); } await ReadAsync(); } catch (Exception e) { await HandleError(e); } } public async Task HandleError(Exception e) { using (Tcp) { try { string? line; var errReader = new StringReader(e.ToString()); while ((line = errReader.ReadLine()) != null) { await Writer.WriteAsync("-"); await Writer.WriteLineAsync(line); } await Writer.FlushAsync(); } catch (Exception) { // nothing we can do } } }}class ShardedDictionary{ Dictionary<string, string>[] _dics; BlockingCollection<Client>[] _workers; public ShardedDictionary(int shardingFactor) { _dics = new Dictionary<string, string>[shardingFactor]; _workers = new BlockingCollection<Client>[shardingFactor]; for (int i = 0; i < shardingFactor; i++) { var dic = new Dictionary<string, string>(); var worker = new BlockingCollection<Client>(); _dics[i] = dic; _workers[i] = worker; // readers new Thread(() => { ExecWorker(dic, worker); }) { IsBackground = true, }.Start(); } } private static void ExecWorker(Dictionary<string, string> dic, BlockingCollection<Client> worker) { while (true) { var client = worker.Take(); if (client.Value != null) { dic[client.Key] = client.Value; client.Value = null; } else { dic.TryGetValue(client.Key, out client.Value); } var _ = client.NextAsync(); } } public void Run(Client c) { var reader = _workers[c.GetHashCode() % _workers.Length]; reader.Add(c); }}
学习离不开答疑交流,跳槽高薪离不开信息分享,这里给大家推荐个学习群,里面有大佬技术答疑、有直播技术分享、有资料定期分享、还有高薪内推资源,强烈建议大家进群一起学习交流,来年拿高薪。也欢迎大家加入最活跃的编程技术交流群 (.NET/WPF )进学习群,一起学习进步!关键词:解决,方案