Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- namespace StackExchange.Redis
- {
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- public static class StackExchangeRedisExtensions
- {
- public static IEnumerable<IServer> GetMasterServers(this IConnectionMultiplexer connection)
- {
- var endpoints = GetFilteredEndpoints(connection);
- var allServers = endpoints.Select(ep => connection.GetServer(ep));
- var masters = allServers.Where(s => !s.IsSlave).OrderBy(s => s.EndPoint.GetPort().Value);
- return masters;
- }
- public static IEnumerable<EndPoint> GetFilteredEndpoints(this IConnectionMultiplexer connection)
- {
- var endpoints = connection.GetEndPoints();
- if (endpoints.Count() > 1)
- {
- var instanceEndpoints = endpoints.Where(ep =>
- {
- var port = ep.GetPort();
- return port.HasValue && port != 6379 && port != 6380;
- });
- if (instanceEndpoints.Any())
- return instanceEndpoints;
- }
- return endpoints;
- }
- public static int? GetPort(this EndPoint ep)
- {
- int? port = null;
- if (ep is DnsEndPoint)
- port = ((DnsEndPoint)ep).Port;
- else if (ep is IPEndPoint)
- port = ((IPEndPoint)ep).Port;
- return port;
- }
- //AZURE REDIS SPECIFIC IMPLEMENTATION
- public static int GetShardIdForKey(this IConnectionMultiplexer connection, string key)
- {
- var slot = connection.HashSlot(key);
- var masters = connection.GetMasterServers();
- var x = masters.First().ClusterNodes().GetBySlot(slot);
- return GetShardIdFromPort(x.EndPoint.GetPort().Value);
- }
- //AZURE REDIS SPECIFIC IMPLEMENTATION
- public static int GetShardIdFromPort(int port)
- {
- return (port % 100) / 2;
- }
- public static async void FlushAllNodes(this ConnectionMultiplexer connection)
- {
- foreach (var server in connection.GetMasterServers())
- {
- await server.FlushAllDatabasesAsync();
- }
- }
- public static string Info(this IServer server, string sectionName, string item)
- {
- return server.Info().SubSection(sectionName).SubItem(item);
- }
- public static IGrouping<string, KeyValuePair<string, string>> SubSection(this IGrouping<string, KeyValuePair<string, string>>[] info, string sectionName)
- {
- var section = info.Where(g => g.Key == sectionName).FirstOrDefault();
- return section;
- }
- public static string SubItem(this IGrouping<string, KeyValuePair<string, string>> section, string item)
- {
- if (section == null)
- return null;
- var listEntry = section.Where(g => g.Key == item).FirstOrDefault();
- return listEntry.Value;
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement