public ConvertModelsService()
        {
            var redis = RedisSettings.GetConnectionMultiplexer();

            _redisUsersDatabase  = redis.GetDatabase(0);
            _redisEventsDatabase = redis.GetDatabase(1);
        }
Example #2
0
        /// <summary>
        ///     Shows the redis server.
        /// </summary>
        private void ShowRedisServer( )
        {
            var properties = new RedisProperties( );

            properties.ShowDialog( );

            var vm = properties.DataContext as RedisPropertiesViewModel;

            if (vm != null && vm.OkClicked)
            {
                RedisSettings redisSettings = vm.RedisInfo;

                if (redisSettings.ServerName != Settings.Default.RedisServer ||
                    redisSettings.Port != Settings.Default.RedisPort)
                {
                    RedisSettings = redisSettings;

                    PluginSettings.RedisSettings = RedisSettings;

                    Settings.Default.RedisServer = redisSettings.ServerName;
                    Settings.Default.RedisPort   = redisSettings.Port;
                    Settings.Default.Save( );

                    OnPropertyChanged("RedisStatusText");

                    foreach (PluginWrapper plugin in PluginManager.Plugins)
                    {
                        plugin.Plugin.OnUpdateSettings(PluginSettings);
                    }
                }
            }
        }
        public MetricsCollectionService(IConnectionMultiplexer connectionMultiplexer, IOptions <RedisSettings> options)
        {
            this.connectionMultiplexer = connectionMultiplexer;
            redisSettings = options.Value;

            Init();
        }
Example #4
0
        /// <summary>
        ///     Initializes a new instance of the <see cref="MainWindow" /> class.
        /// </summary>
        public MainWindow( )
        {
            InitializeComponent( );

            UpgradeExistingInstallation( );

            var viewModel = new MainWindowViewModel(this, RefreshAccordion);

            viewModel.RestoreUi         += viewModel_RestoreUi;
            viewModel.ShowWhenMinimized += viewModel_ShowWhenMinimized;
            viewModel.HideWhenMinimized += viewModel_HideWhenMinimized;

            DataContext = viewModel;

            Activated += MainWindow_Activated;

            DatabaseSettings databaseSettings = GetDatabaseSettings( );

            if (databaseSettings == null)
            {
                MessageBox.Show("A valid database server is required.", "ReadiMon");
                System.Windows.Application.Current.Shutdown(0);
                return;
            }

            RedisSettings redisSettings = GetRedisSettings( );

            viewModel.DatabaseSettings = databaseSettings;
            viewModel.RedisSettings    = redisSettings;

            viewModel.Start( );

            Loaded += MainWindow_Loaded;
        }
Example #5
0
 public RedisConnectionWrapper(RedisSettings redisSettings)
 {
     this.redisSettings    = redisSettings;
     this.connectionString = new Lazy <string>(() =>
     {
         return(this.redisSettings.Server);
     });
 }
Example #6
0
 public void Init(List <Tuple <string, int> > addressList)
 {
     foreach (var address in addressList)
     {
         var setting = new RedisSettings(address.Item1, port: address.Item2, ioTimeout: 3);
         redisList.Add(setting);
     }
 }
Example #7
0
        static void Main(string[] args)
        {
            Serilog.ILogger logger = new LoggerConfiguration()
                                     .WriteTo.Console()
                                     .CreateLogger();

            IFeatureToggle featureToggle = new FeatureToggles();

            //string specificationId = "a1fe8998-406b-44b8-92c7-502a560e7b6e";
            ////string providerId = "10027545";
            //string providerId = "10004758";

            string specificationId = "b1952bc1-4ed9-4ae1-b29d-c72d8d22e830";
            //string providerId = "10027545";
            string providerId = "10063088";

            IConfigurationRoot config = ConfigHelper.AddConfig();

            EngineSettings engineSettings = new EngineSettings();

            CosmosDbSettings dbSettings = new CosmosDbSettings();

            config.Bind("CosmosDbSettings", dbSettings);
            dbSettings.CollectionName = "providerdatasets";
            CosmosRepository calcsCosmosRepostory = new CosmosRepository(dbSettings);
            IProviderSourceDatasetsRepository providerSourceDatasetsRepository = new ProviderSourceDatasetsRepository(calcsCosmosRepostory, engineSettings);


            RedisSettings redisSettings = new RedisSettings();

            config.Bind("redisSettings", redisSettings);
            ICacheProvider cacheProvider = new StackExchangeRedisClientCacheProvider(redisSettings);

            ApiOptions apiOptions = new ApiOptions();

            config.Bind("resultsClient", apiOptions);

            ICorrelationIdProvider correlationIdProvider = new CorrelationIdProvider();

            IResultsApiClientProxy resultsApi = new ResultsApiProxy(apiOptions, logger, correlationIdProvider);

            IMapper mapper = new MapperConfiguration(c =>
            {
                c.AddProfile <ProviderMappingProfile>();
            }).CreateMapper();

            ProviderService providerService = new ProviderService(cacheProvider, resultsApi, mapper);

            FilesystemCacheProviderService filesystemCacheProviderService = new FilesystemCacheProviderService(providerService);

            AllocationModelDebugRunner debugger = new AllocationModelDebugRunner(logger, featureToggle, providerSourceDatasetsRepository, filesystemCacheProviderService);

            (IEnumerable <Models.Results.CalculationResult> calculationResults, long ms) = debugger.Execute(specificationId, providerId).Result;

            CalculationRunSummaryGenerator summaryGenerator = new CalculationRunSummaryGenerator();

            summaryGenerator.GenerateSummary(calculationResults, ms, specificationId, providerId);
        }
        public void CommandStart(RedisSettings usedSettings, string command, RedisKey key)
        {
            if (TimerStrategy == null) return;
            this.start = TimerStrategy.Start();

            this.usedSettings = usedSettings;
            this.command = command;
            this.key = key;
        }
        public GlobalSettings(IConfiguration config)
        {
            Cache    = new CacheSettings(config);
            Database = new DatabaseSettings(config);
            Redis    = new RedisSettings(config);
            Scraper  = new ScrapeSettings(config);

            LogRequests = config.GetValue("LogRequests", false);
        }
Example #10
0
 public static void RegisterRedis(this IServiceCollection services, RedisSettings redisSettings)
 {
     services.AddDistributedRedisCache(options =>
     {
         string server         = redisSettings.Server;
         string port           = redisSettings.Port;
         options.Configuration = $"{server}:{port}";
     });
 }
Example #11
0
        /// <summary>
        /// 获取连接
        /// </summary>
        /// <param name="sectionName">节点名称</param>
        public static IRedisClient GetClient(string sectionName = null)
        {
            if (pooledRedisClientManager == null)
            {
                redisSettings = sectionName == null?RedisSettings.GetConfig() : RedisSettings.GetConfig(sectionName);

                CreateManager();
            }
            return(pooledRedisClientManager?.GetClient());
        }
Example #12
0
        public ContextBuilder(Configuration config)
        {
            _config      = config;
            _redisConfig = _config.GetRedisSettings();

            _clientsPool  = new ObjectClientsPool(_redisConfig);
            _keys         = new KeyManager(_config);
            _proxyGen     = new ProxyGenerator();
            _implSelector = new ImplBuilder(_config);
        }
Example #13
0
        public SerializationInfo(T serializer)
        {
            Serializer = serializer;
            Object     = new TestObj("Hello", 2, "World", 3);

            TempStream = new MemoryStream();
            TempBuffer = new byte[4096];

            Settings = RedisSettings.Default;
        }
 public RedisTimelineMessage(RedisSettings usedSettings, string command, RedisKey key, object sentObject, long sentSize, object receivedObject, long receivedSize, bool isError)
 {
     UsedSettings = usedSettings;
     Command = command;
     Key = key;
     SentObject = sentObject;
     SentSize = sentSize;
     ReceivedObject = receivedObject;
     ReceivedSize = receivedSize;
     IsError = isError;
 }
Example #15
0
        public RoundRobinPool(RedisSettings settings, int count)
        {
            _pool = new IRedisClient <T> [count];

            for (var i = 0; i < count; i++)
            {
                _pool[i] = new RedisClient <T>(settings);
            }

            _poolIdx = 0;
        }
 public RedisTimelineMessage(RedisSettings usedSettings, string command, RedisKey key, object sentObject, long sentSize, object receivedObject, long receivedSize, bool isError)
 {
     UsedSettings   = usedSettings;
     Command        = command;
     Key            = key;
     SentObject     = sentObject;
     SentSize       = sentSize;
     ReceivedObject = receivedObject;
     ReceivedSize   = receivedSize;
     IsError        = isError;
 }
Example #17
0
        public static IServiceCollection AddRedis(this IServiceCollection services, IConfiguration configuration)
        {
            services.AddStackExchangeRedisCache(options =>
            {
                RedisSettings redisSettings = new RedisSettings();
                configuration.GetSection("RedisSettings").Bind(redisSettings);
                var configurationOptions     = ConfigurationOptions.Parse(redisSettings.ConnectionString, true);
                options.ConfigurationOptions = configurationOptions;
            });

            return(services);
        }
Example #18
0
        public RedisStore(IOptions <RedisSettings> redisSettings)
        {
            _redisSettings = redisSettings.Value;
            var configurationOptions = new ConfigurationOptions
            {
                AbortOnConnectFail = false,
                Password           = _redisSettings.Password,
                EndPoints          = { { _redisSettings.Host, _redisSettings.Port } }
            };

            _lazyConnection = new Lazy <ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(configurationOptions));
        }
        public RedisCacheManager(IRedisConnectionWrapper connectionWrapper, RedisSettings config)
        {
            _config = config;
            if (string.IsNullOrEmpty(_config.RedisConnectionString))
            {
                throw new Exception("Redis connection string is empty");
            }

            _connectionWrapper = connectionWrapper;

            _db = _connectionWrapper.GetDatabase(_config.RedisDatabaseId ?? (int)RedisDatabaseNumber.Cache);
        }
        public void CommandStart(RedisSettings usedSettings, string command, RedisKey key)
        {
            if (TimerStrategy == null)
            {
                return;
            }
            this.start = TimerStrategy.Start();

            this.usedSettings = usedSettings;
            this.command      = command;
            this.key          = key;
        }
Example #21
0
 public RemarkStorage(IStorageClient storageClient,
                      IPagedFilter <Remark, BrowseRemarks> browseRemarksFilter,
                      IPagedFilter <Remark, BrowseSimilarRemarks> browseSimilarRemarksFilter,
                      ICache cache,
                      RedisSettings redisSettings)
 {
     _storageClient              = storageClient;
     _cache                      = cache;
     _browseRemarksFilter        = browseRemarksFilter;
     _browseSimilarRemarksFilter = browseSimilarRemarksFilter;
     _useCache                   = redisSettings.Enabled;
 }
Example #22
0
        private static void AssertSettings(RedisSettings settings)
        {
            var duplicateConnNames = settings.Connections
                                     .WhereDuplicated(s => s.Name)
                                     .ToArray();

            if (duplicateConnNames.Any())
            {
                throw new ContainerException("Configured database names must be unique.",
                                             "duplicate-connection-names",
                                             duplicateConnNames);
            }
        }
        public static IServiceCollection AddCaching(this IServiceCollection builder, IConfiguration config)
        {
            RedisSettings redisSettings = new RedisSettings();

            config.Bind("redisSettings", redisSettings);

            builder.AddSingleton <RedisSettings>(redisSettings);

            builder
            .AddSingleton <ICacheProvider, StackExchangeRedisClientCacheProvider>();

            return(builder);
        }
Example #24
0
        public void Ctor_IncompatibleSerializer_ExceptionThrown()
        {
            // use a string serializer for int clients
            var settings = RedisSettings.Build()
                           .OverrideSerializer(new Mock <ISerializer <string> >().Object);

            // prevent Reset() from actually trying to connect to redis
            var clientMock = new Mock <RedisClient <int> >();

            clientMock.Setup(c => c.Reset()).Callback(() => { });

            Assert.Throws <ArgumentException>(() => clientMock.Object.ToString());
        }
Example #25
0
        private static RedisSettings GetRedisSettings()
        {
            var redisSettings = new RedisSettings();

            var config = new ConfigurationBuilder()
                         //.AddJsonFile("appsettings.Release.json", optional: false, reloadOnChange: true)
                         .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)

                         .Build();

            config.GetSection(nameof(RedisSettings)).Bind(redisSettings);
            return(redisSettings);
        }
Example #26
0
        //------------------------------------------------------
        //--Plugin Initialization
        //------------------------------------------------------

        public override void Configure()
        {
            try
            {
                _redisSettings = Context.Configuration.GetSettings(new RedisSettings());
            }
            catch (SettingsValidationException ex)
            {
                Context.BootstrapLogger.Add(LogLevel.Error, ex.Message);
            }

            AssertSettings(_redisSettings);
        }
Example #27
0
        public static IOmnibusServicesBuilder AddRedis(
            this IOmnibusServicesBuilder builder, IConfiguration configuration)
        {
            var section  = configuration.GetRequiredSection(RedisSectionName);
            var settings = new RedisSettings();

            section.Bind(settings);
            builder.Services
            .Configure <RedisSettings>(section)
            .AddSingleton <IConnectionMultiplexer>(ConnectionMultiplexer.Connect(settings.ConnectionString));

            return(builder);
        }
Example #28
0
        public void GetsSetting()
        {
            var redis = A.Fake <IDatabase>();

            A.CallTo(redis).Where(r => r.Method.Name == "HashGet" && (RedisKey)r.Arguments[0] == "AppSettings" && (RedisValue)r.Arguments[1] == "TestSetting1")
            .WithReturnType <RedisValue>()
            .Returns("TestSetting1Value");
            var redisSettings = new RedisSettings(redis);

            var result = redisSettings.Get("TestSetting1");

            Assert.AreEqual("TestSetting1Value", result);
        }
Example #29
0
        public static ICacheStore GetCacheStore()
        {
            RedisSettings redisSettings = GetRedisSettings();

            var serviceProvider = new ServiceCollection()
                                  // Application Dependency Injection
                                  .AddSingleton <IRedisConnectionWrapper, RedisConnectionWrapper>(resolver => new RedisConnectionWrapper(redisSettings))
                                  .AddSingleton <ICacheStore>(sp => new RedisCacheStore(sp.GetRequiredService <IRedisConnectionWrapper>(), redisSettings))
                                  .BuildServiceProvider();

            // is redis alive?
            return(serviceProvider.GetRequiredService <ICacheStore>());
        }
        public ApiModule(IReloadingManager <AppSettings> settings)
        {
            _marketType = settings.CurrentValue.CandlesHistory != null
                ? MarketType.Spot
                : MarketType.Mt;

            _settings = settings.CurrentValue.CandlesHistory ?? settings.CurrentValue.MtCandlesHistory;

            _assetSettings = settings.CurrentValue.Assets;
            _redisSettings = settings.CurrentValue.RedisSettings;
            _candleHistoryAssetConnections = settings.CurrentValue.CandleHistoryAssetConnections != null
                ? settings.Nested(x => x.CandleHistoryAssetConnections)
                : settings.Nested(x => x.MtCandleHistoryAssetConnections);
        }
Example #31
0
        public static void AddRedisConfigToServices(this IServiceCollection services, Microsoft.Extensions.Configuration.IConfiguration configuration)
        {
            var redisSettings = new RedisSettings();

            configuration.GetSection(nameof(RedisSettings)).Bind(redisSettings);

            if (!redisSettings.Enabled)
            {
                return;
            }

            services.AddStackExchangeRedisCache(options => options.Configuration = redisSettings.ConnectionString);
            services.AddSingleton <ICacheService, CacheService>();
        }
Example #32
0
        public Server()
        {
            string redisAddr = API.GetConvar("trackm_redis_addr", "127.0.0.1:6379");

            SplitHostPort(redisAddr, out string redisHost, out int redisPort);

            int redisDb = API.GetConvarInt("trackm_redis_db", 0);

            var settings = RedisSettings.Build()
                           .Host(redisHost)
                           .Port(redisPort)
                           .ReconnectOnIdle(true)
                           .ReissueCommandsOnReconnect(false);

            pool = new ThreadwisePool(settings, redisDb);

            IRedisClient <string> client = pool.GetClient();

            client.FlushDb();

            updateInterval = API.GetConvarInt("trackm_update_interval", 1000);
            if (updateInterval < MinimumUpdateInterval)
            {
                Debug.WriteLine("trackm_update_interval set too low ({0}ms) using minimum {1}ms.", updateInterval, MinimumUpdateInterval);
                updateInterval = MinimumUpdateInterval;
            }

            movementThreshold = API.GetConvarInt("trackm_movement_threshold", 1);
            if (movementThreshold < MinimumMovementThreshold)
            {
                Debug.WriteLine("trackm_movement_threshold set too low ({0}m) using minimum {1}m.", movementThreshold, MinimumMovementThreshold);
                movementThreshold = MinimumMovementThreshold;
            }
            // clients deal with squared distances
            movementThreshold *= movementThreshold;

            // fivem events
            EventHandlers["playerDropped"] += new Action <Player, string>(PlayerDropped);

            // internal events
            EventHandlers[Prefix + "register"]   += new Action <Player, int, string, string>(Register);
            EventHandlers[Prefix + "unregister"] += new Action <Player, int>(Unregister);

            // public events
            EventHandlers[Prefix + "Track"]          += new Action <int, int>(Track);
            EventHandlers[Prefix + "Untrack"]        += new Action <int, int>(Untrack);
            EventHandlers[Prefix + "MetadataGet"]    += new Action <int, int, string, CallbackDelegate>(MetadataGet);
            EventHandlers[Prefix + "MetadataSet"]    += new Action <int, int, string, string>(MetadataSet);
            EventHandlers[Prefix + "MetadataDelete"] += new Action <int, int, string>(MetadataDelete);
        }
        public RedisSettings Select(RedisSettings[] settings, RedisKey key)
        {
            if (settings.Length == 0) throw new ArgumentException("settings length is 0");
            if (settings.Length == 1) return settings[0];

            using (var md5 = new System.Security.Cryptography.MD5CryptoServiceProvider())
            {
                var hashBytes = md5.ComputeHash((byte[])key);
                var preSeed = BitConverter.ToInt32(hashBytes, 0);
                if (preSeed == int.MinValue) preSeed++; // int.MinValue can't do Abs

                var seed = System.Math.Abs(preSeed);
                var index = seed % settings.Length;
                return settings[index];
            }
        }
Example #34
0
 internal RedisConnectionInfo(string host, RedisSettings.Instance settings)
 {
     Settings = settings;
     Host = host;
 }
Example #35
0
        protected SettingsWrapper(RedisSettings settings)
        {
            SAssert.ArgumentNotNull(() => settings);

              Settings = settings;
        }
Example #36
0
 public void CommandStart(RedisSettings usedSettings, string command, RedisKey key)
 {
     Debug.WriteLine(command + " " + (string)key);
 }
Example #37
0
        public void Run()
        {
            // configure benchmark parameters here:
              const int Instances = 7;
              const int Iterations = 10000;
              const bool QuietMode = false; // turn to false to make it wait for key inputs

              Func<Job> getJob = () => new PingJob();

              _settings = RedisSettings.Build()
            .ReconnectOnIdle(false);

              _pool = new RoundRobinPool<string>(_settings, Instances);

              do {

            // setup
            var options = TaskCreationOptions.LongRunning;

            var tasks = Enumerable
              .Range(0, Instances)
              .Select(n => getJob())
              .Select(job => new Task<BenchmarkResult>(
            () => benchMark(job, Iterations), options))
              .ToArray();

            if (!QuietMode) {
              Console.WriteLine("{0} instances of `{1}` each doing {2} iterations.",
            tasks.Count(),
            getJob().Description,
            Iterations);

              Console.WriteLine("Hit any key to start.");
              Console.ReadKey();
            }

            // starting
            if (Instances == 1)
              tasks.First().RunSynchronously();
            else
              Array.ForEach(tasks, t => t.Start());

            Task.WaitAll(tasks);

            // report time taken
            if (!QuietMode) {
              Console.WriteLine("All done.");

              var results = tasks.Select(t => t.Result);

              foreach (var result in results) {
            Console.WriteLine("{0} : {1}ms",
              result.Job.Description,
              result.MillisecondsTaken);
              }

              var avg = results.Average(r => r.MillisecondsTaken);
              var max = results.Max(r => r.MillisecondsTaken);
              var min = results.Min(r => r.MillisecondsTaken);

              Console.WriteLine("Maximum : {0}ms", max);
              Console.WriteLine("Minimum : {0}ms", min);
              Console.WriteLine("Average : {0}ms", avg);

              Console.ReadKey();
            }

              } while (!QuietMode); // don't repeat in quietmode
        }
 internal RedisStructure(RedisSettings settings, RedisKey key)
 {
     this.Settings = settings;
     this.Key = key;
 }