public RedisConnectionFactory(IOptions <ConfigurationOptions> redis) { this._connection = new Lazy <ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect("portal282-7.bmix-lon-yp-6194d336-1971-40ed-9ef6-4b7774867f58.ohadbaruch1-gmail-com.composedb.com:22743,password=HIOQEQQBKQOQRLXB,Ssl=true")); }
public RedisCache(ConfigRedis configProvider) { _configProvider = configProvider; _connection = ConnectionMultiplexer.Connect(_configProvider.ConnectString); _dbCache = _connection.GetDatabase(0); }
public RedisSession() { var redisMultiplexer = ConnectionMultiplexer.Connect(QT.Entities.Server.RedisDB_Host + ":" + QT.Entities.Server.RedisDB_Port); this.redisDb = redisMultiplexer.GetDatabase(2); }
public override void ConfigureServices(ServiceConfigurationContext context) { var hostingEnvironment = context.Services.GetHostingEnvironment(); var configuration = context.Services.GetConfiguration(); Configure <AbpDbContextOptions>(options => { options.UseSqlServer(); }); context.Services.AddSwaggerGen( options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "MyProjectName API", Version = "v1" }); options.DocInclusionPredicate((docName, description) => true); options.CustomSchemaIds(type => type.FullName); }); Configure <AbpLocalizationOptions>(options => { options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština")); options.Languages.Add(new LanguageInfo("en", "en", "English")); options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português")); options.Languages.Add(new LanguageInfo("ru", "ru", "Русский")); options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe")); options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文")); options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文")); }); Configure <AbpAuditingOptions>(options => { //options.IsEnabledForGetRequests = true; options.ApplicationName = "AuthServer"; }); Configure <AppUrlOptions>(options => { options.Applications["MVC"].RootUrl = configuration["App:SelfUrl"]; }); context.Services.AddAuthentication() .AddIdentityServerAuthentication(options => { options.Authority = configuration["AuthServer:Authority"]; options.RequireHttpsMetadata = false; options.ApiName = configuration["AuthServer:ApiName"]; }); Configure <AbpDistributedCacheOptions>(options => { options.KeyPrefix = "MyProjectName:"; }); Configure <AbpMultiTenancyOptions>(options => { options.IsEnabled = MultiTenancyConsts.IsEnabled; }); if (!hostingEnvironment.IsDevelopment()) { var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]); context.Services .AddDataProtection() .PersistKeysToStackExchangeRedis(redis, "MyProjectName-Protection-Keys"); } context.Services.AddCors(options => { options.AddPolicy(DefaultCorsPolicyName, builder => { builder .WithOrigins( configuration["App:CorsOrigins"] .Split(",", StringSplitOptions.RemoveEmptyEntries) .Select(o => o.RemovePostFix("/")) .ToArray() ) .WithAbpExposedHeaders() .SetIsOriginAllowedToAllowWildcardSubdomains() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); }
public RedisCartRepository() { var connectionString = "localhost,abortConnect=false"; this.redisConnections = ConnectionMultiplexer.Connect(connectionString); }
public IServiceProvider ConfigureServices(IServiceCollection services) { bool.TryParse(Configuration["IPB_OAUTH_DEV_MODE"] ?? "", out var devMode); services .AddAuthentication(options => { options.DefaultAuthenticateScheme = "token"; options.DefaultChallengeScheme = "token"; }) .AddScheme <TokenAuthOptions, TokenAuthenticationHandler>("token", options => { options.ClientId = Configuration["IPB_OAUTH_CLIENT_ID"]; options.UserInformationEndpointUrl = Configuration["Data:OAuth:UserInformationEndpoint"]; options.DevMode = devMode; }); services.AddDistributedMemoryCache(); services.Configure <AppSettings>(Configuration.GetSection("Application")); services.AddSingleton <IActionContextAccessor, ActionContextAccessor>(); services.AddBioEngineRouting(); services.AddScoped <IContentHelperInterface, ContentHelper>(); services.AddScoped <IPBApiHelper>(); services.Configure <IPBApiConfig>(o => { o.ApiKey = Configuration["BE_IPB_API_KEY"]; o.ApiUrl = Configuration["BE_IPB_API_URL"]; o.NewsForumId = Configuration["BE_IPB_NEWS_FORUM_ID"]; o.DevMode = devMode; }); services.Configure <APISettings>(o => o.FileBrowserUrl = Configuration["API_FILE_BROWSER_URL"]); services.AddBioEngineSocial(Configuration); if (_env.IsProduction()) { var resolved = TryResolveDns(Configuration["BE_REDIS_HOST"]); var redisConfiguration = new ConfigurationOptions { EndPoints = { new IPEndPoint(resolved.AddressList.First(), int.Parse(Configuration["BE_REDIS_PORT"])) }, AbortOnConnectFail = false, DefaultDatabase = int.Parse(Configuration["BE_REDIS_DATABASE"]) }; var redis = ConnectionMultiplexer.Connect(redisConfiguration); services.AddDataProtection().PersistKeysToRedis(redis, "DataProtection-Keys"); services.AddAntiforgery(opts => opts.Cookie.Name = "beAntiforgeryCookie"); } services.AddCors(options => { // Define one or more CORS policies options.AddPolicy("allorigins", corsBuilder => { corsBuilder.AllowAnyHeader().AllowAnyOrigin().AllowAnyMethod().AllowCredentials(); }); }); services.AddMvc(options => { options.AddMetricsResourceFilter(); }); var builder = services.AddBioEngineData(Configuration); builder.RegisterAssemblyTypes(typeof(Startup).GetTypeInfo().Assembly) .Where(t => t.Name.EndsWith("MapperProfile")).As <Profile>(); builder.RegisterGeneric(typeof(RestContext <>)).InstancePerDependency(); ApplicationContainer = builder.Build(); return(new AutofacServiceProvider(ApplicationContainer)); }
/// <summary> /// 删除用户订单数据 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void button14_Click(object sender, EventArgs e) { var userIdStr = textUserIdList.Text; var UserIdList = userIdStr.Split(',').ToList(); //查询数据,然后删除对应的缓存数据 using (SqlConnection con = new SqlConnection()) { con.ConnectionString = ConnectionString; con.Open(); SqlCommand com = new SqlCommand(); com.Connection = con; com.CommandType = CommandType.Text; com.CommandText = $"SELECT * FROM [{DbName}].[dbo].[NationalDayOrders] WHERE UserId in ({userIdStr});"; SqlDataReader dr = com.ExecuteReader();//执行SQL语句 ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(Host); var database = redis.GetDatabase(db); if (dr.HasRows) { while (dr.Read()) { var imei = dr["IMEI"]; var userId = dr["UserId"]; //遍历每一种礼包,这里随便写了个15 for (int i = 1; i < 15; i++) { var key = $"TcySys_NationalAct_ChargeAct_UserBuyIEMIList_{i}"; var key2 = $"TcySys_NationalAct_ChargeAct_UserBuyList_{i}"; database.HashDelete(key2, userId.ToString()); database.HashDelete(key, imei.ToString()); } } } database.KeyDelete("TcySys_NationalAct_ChargeAct_RefreshTimer"); dr.Close(); //关闭执行 con.Close(); //关闭数据库 } //删除缓存内用户的数据 using (SqlConnection con = new SqlConnection()) { con.ConnectionString = ConnectionString; con.Open(); SqlCommand com = new SqlCommand(); com.Connection = con; com.CommandType = CommandType.Text; com.CommandText = $"DELETE FROM [{DbName}].[dbo].[NationalDayOrders] WHERE UserId in ({userIdStr})"; SqlDataReader dr = com.ExecuteReader(); //执行SQL语句 dr.Close(); //关闭执行 con.Close(); //关闭数据库 } }
public static ConnectionMultiplexer GetConnection(string configuration) { Func <ConnectionMultiplexer> function = () => ConnectionMultiplexer.Connect(configuration); return(function.RetryOnException(3, TimeSpan.FromMilliseconds(10))); }
// This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { RegisterAppInsights(services); services.AddMvc(); services.AddSession(); if (Configuration.GetValue <string>("IsClusterEnv") == bool.TrueString) { services.AddDataProtection(opts => { opts.ApplicationDiscriminator = "eshop.webmvc"; }) .PersistKeysToRedis(ConnectionMultiplexer.Connect(Configuration["DPConnectionString"]), "DataProtection-Keys"); } services.Configure <AppSettings>(Configuration); services.AddHealthChecks(checks => { var minutes = 1; if (int.TryParse(Configuration["HealthCheck:Timeout"], out var minutesParsed)) { minutes = minutesParsed; } checks.AddUrlCheck(Configuration["CatalogUrlHC"], TimeSpan.FromMinutes(minutes)); checks.AddUrlCheck(Configuration["OrderingUrlHC"], TimeSpan.FromMinutes(minutes)); checks.AddUrlCheck(Configuration["BasketUrlHC"], TimeSpan.Zero); //No cache for this HealthCheck, better just for demos checks.AddUrlCheck(Configuration["IdentityUrlHC"], TimeSpan.FromMinutes(minutes)); checks.AddUrlCheck(Configuration["MarketingUrlHC"], TimeSpan.FromMinutes(minutes)); }); // Add application services. services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>(); services.AddTransient <ICatalogService, CatalogService>(); services.AddTransient <IOrderingService, OrderingService>(); services.AddTransient <IBasketService, BasketService>(); services.AddTransient <ICampaignService, CampaignService>(); services.AddTransient <ILocationService, LocationService>(); services.AddTransient <IIdentityParser <ApplicationUser>, IdentityParser>(); if (Configuration.GetValue <string>("UseResilientHttp") == bool.TrueString) { services.AddSingleton <IResilientHttpClientFactory, ResilientHttpClientFactory>(sp => { var logger = sp.GetRequiredService <ILogger <ResilientHttpClient> >(); var httpContextAccessor = sp.GetRequiredService <IHttpContextAccessor>(); var retryCount = 6; if (!string.IsNullOrEmpty(Configuration["HttpClientRetryCount"])) { retryCount = int.Parse(Configuration["HttpClientRetryCount"]); } var exceptionsAllowedBeforeBreaking = 5; if (!string.IsNullOrEmpty(Configuration["HttpClientExceptionsAllowedBeforeBreaking"])) { exceptionsAllowedBeforeBreaking = int.Parse(Configuration["HttpClientExceptionsAllowedBeforeBreaking"]); } return(new ResilientHttpClientFactory(logger, httpContextAccessor, exceptionsAllowedBeforeBreaking, retryCount)); }); services.AddSingleton <IHttpClient, ResilientHttpClient>(sp => sp.GetService <IResilientHttpClientFactory>().CreateResilientHttpClient()); } else { services.AddSingleton <IHttpClient, StandardHttpClient>(); } var useLoadTest = Configuration.GetValue <bool>("UseLoadTest"); var identityUrl = Configuration.GetValue <string>("IdentityUrl"); var callBackUrl = Configuration.GetValue <string>("CallBackUrl"); // Add Authentication services services.AddAuthentication(options => { options.DefaultScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.DefaultChallengeScheme = OpenIdConnectDefaults.AuthenticationScheme; }) .AddCookie() .AddOpenIdConnect(options => { options.SignInScheme = CookieAuthenticationDefaults.AuthenticationScheme; options.Authority = identityUrl.ToString(); options.SignedOutRedirectUri = callBackUrl.ToString(); options.ClientId = useLoadTest ? "mvctest" : "mvc"; options.ClientSecret = "secret"; options.ResponseType = useLoadTest ? "code id_token token" : "code id_token"; options.SaveTokens = true; options.GetClaimsFromUserInfoEndpoint = true; options.RequireHttpsMetadata = false; options.Scope.Add("openid"); options.Scope.Add("profile"); options.Scope.Add("orders"); options.Scope.Add("basket"); options.Scope.Add("marketing"); options.Scope.Add("locations"); options.Scope.Add("webshoppingagg"); }); }
public Redis() { ConnectionMultiplexer connection = ConnectionMultiplexer.Connect("localhost"); _database = connection.GetDatabase(); }
public static void Init(IRedisConfig redisConfig) { RedisConnection.Redis = ConnectionMultiplexer.Connect(redisConfig.RedisHost + ":" + redisConfig.RedisPort); }
public RedisGroupChatsRepository(string connectionString) { ConnectionMultiplexer connection = ConnectionMultiplexer.Connect(connectionString); _cache = connection.GetDatabase(); }
static DoubleCacheController() { _doubleCache = new DoubleCache.DoubleCache( new DoubleCache.LocalCache.MemCache(), new RedisCache(ConnectionMultiplexer.Connect("localhost").GetDatabase(), new MsgPackItemSerializer())); }
public override void ConfigureServices(ServiceConfigurationContext context) { var hostingEnvironment = context.Services.GetHostingEnvironment(); var configuration = context.Services.GetConfiguration(); Configure <AbpDbContextOptions>(options => { options.UseSqlite(); }); Configure <AbpMultiTenancyOptions>(options => { options.IsEnabled = MultiTenancyConsts.IsEnabled; }); Configure <AbpAspNetCoreMvcOptions>(options => { options.ConventionalControllers.Create(typeof(SettingModelApplicationModule).Assembly); }); if (hostingEnvironment.IsDevelopment()) { Configure <AbpVirtualFileSystemOptions>(options => { options.FileSets.ReplaceEmbeddedByPhysical <SettingModelDomainSharedModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}Tolo.Abp.SettingModel.Domain.Shared", Path.DirectorySeparatorChar))); options.FileSets.ReplaceEmbeddedByPhysical <SettingModelDomainModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}Tolo.Abp.SettingModel.Domain", Path.DirectorySeparatorChar))); options.FileSets.ReplaceEmbeddedByPhysical <SettingModelApplicationContractsModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}Tolo.Abp.SettingModel.Application.Contracts", Path.DirectorySeparatorChar))); options.FileSets.ReplaceEmbeddedByPhysical <SettingModelApplicationModule>(Path.Combine(hostingEnvironment.ContentRootPath, string.Format("..{0}..{0}src{0}Tolo.Abp.SettingModel.Application", Path.DirectorySeparatorChar))); }); } context.Services.AddAbpSwaggerGenWithOAuth( configuration["AuthServer:Authority"], new Dictionary <string, string> { { "SettingModel", "SettingModel API" } }, options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "SettingModel API", Version = "v1" }); options.DocInclusionPredicate((docName, description) => true); options.CustomSchemaIds(type => type.FullName); }); Configure <AbpVirtualFileSystemOptions>(options => { options.FileSets.AddEmbedded <SettingModelHttpApiHostModule>("Tolo.Abp.SettingModel"); }); Configure <AbpLocalizationOptions>(options => { options.Resources .Add <SettingModelWebResource>("en") .AddVirtualJson("/Localization/SettingModelWeb"); options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština")); options.Languages.Add(new LanguageInfo("en", "en", "English")); options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)")); options.Languages.Add(new LanguageInfo("fr", "fr", "Français")); options.Languages.Add(new LanguageInfo("hu", "hu", "Magyar")); options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português")); options.Languages.Add(new LanguageInfo("ru", "ru", "Русский")); options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe")); options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文")); options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文")); }); context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = configuration["AuthServer:Authority"]; options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]); options.Audience = "SettingModel"; }); //Configure<AbpDistributedCacheOptions>(options => //{ // options.KeyPrefix = "SettingModel:"; //}); if (!hostingEnvironment.IsDevelopment()) { var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]); context.Services .AddDataProtection() .PersistKeysToStackExchangeRedis(redis, "SettingModel-Protection-Keys"); } context.Services.AddCors(options => { options.AddPolicy(DefaultCorsPolicyName, builder => { builder .WithOrigins( configuration["App:CorsOrigins"] .Split(",", StringSplitOptions.RemoveEmptyEntries) .Select(o => o.RemovePostFix("/")) .ToArray() ) .WithAbpExposedHeaders() .SetIsOriginAllowedToAllowWildcardSubdomains() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); }
public void Initialize(RedisClusteringOptions options) { DatabaseOptions = options; Multiplexer = ConnectionMultiplexer.Connect(options.ConnectionString); }
public RedisHelper(IConfiguration configuration) { this.multiplexer = ConnectionMultiplexer.Connect(configuration.GetSection("RedisCaching:ConnectionString").Value); }
public RedisConnectionFactory(IOptions <RedisConfiguration> options) { _connection = new Lazy <ConnectionMultiplexer>(() => ConnectionMultiplexer.Connect(options.Value.Host)); }
public static void RegisterServices(Container container, ILoggerFactory loggerFactory) { loggerFactory.AddNLog(); var logger = loggerFactory.CreateLogger <Bootstrapper>(); if (!String.IsNullOrEmpty(Settings.Current.GoogleGeocodingApiKey)) { container.RegisterSingleton <IGeocodeService>(() => new GoogleGeocodeService(Settings.Current.GoogleGeocodingApiKey)); } if (Settings.Current.EnableMetricsReporting) { container.RegisterSingleton <IMetricsClient>(() => new StatsDMetricsClient(Settings.Current.MetricsServerName, Settings.Current.MetricsServerPort, "ex")); } else { logger.Warn("StatsD Metrics is NOT enabled."); } if (Settings.Current.EnableRedis) { container.RegisterSingleton <ConnectionMultiplexer>(() => { var multiplexer = ConnectionMultiplexer.Connect(Settings.Current.RedisConnectionString); multiplexer.PreserveAsyncOrder = false; return(multiplexer); }); if (Settings.Current.HasAppScope) { container.RegisterSingleton <ICacheClient>(() => new ScopedCacheClient(new RedisHybridCacheClient(container.GetInstance <ConnectionMultiplexer>()), Settings.Current.AppScope)); } else { container.RegisterSingleton <ICacheClient, RedisHybridCacheClient>(); } container.RegisterSingleton <IQueue <EventPost> >(() => new RedisQueue <EventPost>(container.GetInstance <ConnectionMultiplexer>(), container.GetInstance <ISerializer>(), GetQueueName <EventPost>(), behaviors: container.GetAllInstances <IQueueBehavior <EventPost> >())); container.RegisterSingleton <IQueue <EventUserDescription> >(() => new RedisQueue <EventUserDescription>(container.GetInstance <ConnectionMultiplexer>(), container.GetInstance <ISerializer>(), GetQueueName <EventUserDescription>(), behaviors: container.GetAllInstances <IQueueBehavior <EventUserDescription> >())); container.RegisterSingleton <IQueue <EventNotificationWorkItem> >(() => new RedisQueue <EventNotificationWorkItem>(container.GetInstance <ConnectionMultiplexer>(), container.GetInstance <ISerializer>(), GetQueueName <EventNotificationWorkItem>(), behaviors: container.GetAllInstances <IQueueBehavior <EventNotificationWorkItem> >())); container.RegisterSingleton <IQueue <WebHookNotification> >(() => new RedisQueue <WebHookNotification>(container.GetInstance <ConnectionMultiplexer>(), container.GetInstance <ISerializer>(), GetQueueName <WebHookNotification>(), behaviors: container.GetAllInstances <IQueueBehavior <WebHookNotification> >())); container.RegisterSingleton <IQueue <MailMessage> >(() => new RedisQueue <MailMessage>(container.GetInstance <ConnectionMultiplexer>(), container.GetInstance <ISerializer>(), GetQueueName <MailMessage>(), behaviors: container.GetAllInstances <IQueueBehavior <MailMessage> >())); container.RegisterSingleton <IQueue <WorkItemData> >(() => new RedisQueue <WorkItemData>(container.GetInstance <ConnectionMultiplexer>(), container.GetInstance <ISerializer>(), GetQueueName <WorkItemData>(), workItemTimeout: TimeSpan.FromHours(1), behaviors: container.GetAllInstances <IQueueBehavior <WorkItemData> >())); container.RegisterSingleton <IMessageBus>(() => new RedisMessageBus(container.GetInstance <ConnectionMultiplexer>().GetSubscriber(), $"{Settings.Current.AppScopePrefix}messages", container.GetInstance <ISerializer>())); } else { logger.Warn("Redis is NOT enabled."); } if (Settings.Current.EnableAzureStorage) { container.RegisterSingleton <IFileStorage>(new AzureFileStorage(Settings.Current.AzureStorageConnectionString, $"{Settings.Current.AppScopePrefix}ex-events")); } else { logger.Warn("Azure Storage is NOT enabled."); } var client = ExceptionlessClient.Default; container.RegisterSingleton <ICoreLastReferenceIdManager, ExceptionlessClientCoreLastReferenceIdManager>(); container.RegisterSingleton <ExceptionlessClient>(() => client); client.Configuration.SetVersion(Settings.Current.Version); if (String.IsNullOrEmpty(Settings.Current.InternalProjectId)) { client.Configuration.Enabled = false; } client.Register(); container.AddBootstrapper <HttpConfiguration>(config => client.RegisterWebApi(config)); client.Configuration.UseInMemoryStorage(); client.Configuration.UseReferenceIds(); }
private void button12_Click(object sender, EventArgs e) { button12.Enabled = false; progressBar1.Value = 0; lCount.Text = 0.ToString(); CheckForIllegalCrossThreadCalls = false; var countDic = new Dictionary <int, int>(); countDic[1] = 0; countDic[2] = 0; countDic[3] = 0; countDic[4] = 0; countDic[5] = 0; countDic[6] = 0; countDic[7] = 0; countDic[8] = 0; countDic[9] = 0; countDic[10] = 0; countDic[11] = 0; countDic[12] = 0; lbl1.Text = string.Empty; lbl2.Text = string.Empty; lbl3.Text = string.Empty; lbl4.Text = string.Empty; lbl5.Text = string.Empty; lbl6.Text = string.Empty; lbl7.Text = string.Empty; lbl8.Text = string.Empty; lbl9.Text = string.Empty; lbl10.Text = string.Empty; lbl11.Text = string.Empty; lbl12.Text = string.Empty; try { Task.Run(() => { var key1 = "TcySys_SpecialActConfig_Master_90004_Sub_3"; ConnectionMultiplexer redis = ConnectionMultiplexer.Connect(Host); var database = redis.GetDatabase(db); var configDetial = database.StringGet(key1); var config = JsonConvert.DeserializeObject <NationalDayMonopolyActConfig>(configDetial); var lotteryCount = Convert.ToDouble(textBox8.Text); var type = 0; try { type = Convert.ToInt16(comboBox1.Text.Split('.')[0]); } catch { MessageBox.Show("请选择类型"); } var j = 1; switch (type) { case 1: GetPrecent(countDic, lotteryCount, config.FreeAwardConfig); break; case 2: GetPrecent(countDic, lotteryCount, config.DoubleAwardConfig); break; case 3: GetPrecent(countDic, lotteryCount, config.PayAwardConfig); break; case 4: GetPrecent(countDic, lotteryCount, config.DoublePayAwardConfig); break; default: break; } lbl1.Text = (countDic[1] / lotteryCount * 100.00).ToString(); lbl2.Text = (countDic[2] / lotteryCount * 100.00).ToString(); lbl3.Text = (countDic[3] / lotteryCount * 100.00).ToString(); lbl4.Text = (countDic[4] / lotteryCount * 100.00).ToString(); lbl5.Text = (countDic[5] / lotteryCount * 100.00).ToString(); lbl6.Text = (countDic[6] / lotteryCount * 100.00).ToString(); lbl7.Text = (countDic[7] / lotteryCount * 100.00).ToString(); lbl8.Text = (countDic[8] / lotteryCount * 100.00).ToString(); lbl9.Text = (countDic[9] / lotteryCount * 100.00).ToString(); lbl10.Text = (countDic[10] / lotteryCount * 100.00).ToString(); lbl11.Text = (countDic[11] / lotteryCount * 100.00).ToString(); lbl12.Text = (countDic[12] / lotteryCount * 100.00).ToString(); progressBar1.Value = 100; }); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } finally { button12.Enabled = true; } }
private static ConnectionMultiplexer CreateMultiplexer() { return(ConnectionMultiplexer.Connect(connectionString)); }
public Startup(IConfiguration configuration) { Configuration = configuration; Redis = ConnectionMultiplexer.Connect("127.0.0.1:6379,allowAdmin=true,SyncTimeout=10000"); }
protected override void Load(ContainerBuilder builder) { builder.Register(c => ConnectionMultiplexer.Connect(_redisConfiguration)) .As <IConnectionMultiplexer>() .SingleInstance(); }
public override void ConfigureServices(ServiceConfigurationContext context) { var hostingEnvironment = context.Services.GetHostingEnvironment(); var configuration = context.Services.GetConfiguration(); Configure <AbpDbContextOptions>(options => { options.UseSqlServer(); }); Configure <AbpMultiTenancyOptions>(options => { options.IsEnabled = MultiTenancyConsts.IsEnabled; }); context.Services.AddAbpSwaggerGenWithOAuth( configuration["AuthServer:Authority"], new Dictionary <string, string> { { "Module", "Module API" } }, options => { options.SwaggerDoc("v1", new OpenApiInfo { Title = "Module API", Version = "v1" }); options.DocInclusionPredicate((docName, description) => true); options.CustomSchemaIds(type => type.FullName); }); Configure <AbpLocalizationOptions>(options => { options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština")); options.Languages.Add(new LanguageInfo("en", "en", "English")); options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)")); options.Languages.Add(new LanguageInfo("fr", "fr", "Français")); options.Languages.Add(new LanguageInfo("hu", "hu", "Magyar")); options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português")); options.Languages.Add(new LanguageInfo("ru", "ru", "Русский")); options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe")); options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文")); options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文")); }); context.Services.AddAuthentication(JwtBearerDefaults.AuthenticationScheme) .AddJwtBearer(options => { options.Authority = configuration["AuthServer:Authority"]; options.RequireHttpsMetadata = Convert.ToBoolean(configuration["AuthServer:RequireHttpsMetadata"]); options.Audience = "Module"; }); Configure <AbpDistributedCacheOptions>(options => { options.KeyPrefix = "Module:"; }); if (!hostingEnvironment.IsDevelopment()) { var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]); context.Services .AddDataProtection() .PersistKeysToStackExchangeRedis(redis, "Module-Protection-Keys"); } context.Services.AddCors(options => { options.AddPolicy(DefaultCorsPolicyName, builder => { builder .WithOrigins( configuration["App:CorsOrigins"] .Split(",", StringSplitOptions.RemoveEmptyEntries) .Select(o => o.RemovePostFix("/")) .ToArray() ) .WithAbpExposedHeaders() .SetIsOriginAllowedToAllowWildcardSubdomains() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); }
public RedisCache() { Redis = ConnectionMultiplexer.Connect("localhost"); }
static void Main(string[] args) { // Creating connection with Redis server var conn = ConnectionMultiplexer.Connect("localhost"); //Connects to db IDatabase redis = conn.GetDatabase(); //Clearing old data //Creates an array of (new) users string[] userArray = { "Jonas", "Petras", "Antanas", "Lukas" }; //Adds user to db foreach (var user in userArray) { redis.ListRemove("user_name", user); redis.ListRightPush("users_name", user); } //Gets lenght of the new list var listLength = redis.ListLength("users_name"); //Adds accounts for users Random rnd = new Random(); Console.WriteLine("Before Transactions"); for (int i = 0; i < listLength; i++) { var hashKey = userArray[i]; //Generating credit card numbers and balances long cc_numb = rnd.Next(100000000, 1000000000); int balance = rnd.Next(10, 1000); //Adding credit card numbers and balances to db HashEntry[] userInfo = { new HashEntry("CC_number", "LT" + cc_numb.ToString()), new HashEntry("CC_Balance", balance.ToString()), }; redis.HashSet(hashKey, userInfo); Console.WriteLine(hashKey); foreach (var item in userInfo) { Console.WriteLine(String.Format("{0}: {1}", item.Name, item.Value)); } } //Transakcijos //1) Jonas Perveda 20Euru Petrui redis.HashIncrement("Petras", "CC_Balance", 20); redis.HashDecrement("Jonas", "CC_Balance", 20); //2)Antanas gauna 500 Euru alga redis.HashIncrement("Antanas", "CC_Balance", 500); //3)Lukas sumokėjo 15 Euru parduotuvėje redis.HashDecrement("Jonas", "CC_Balance", 15); HashEntry[] result; Console.WriteLine("After Transactions"); foreach (var user in userArray) { Console.WriteLine(user); result = redis.HashGetAll(user); foreach (var item in result) { Console.WriteLine(String.Format("{0}: {1}", item.Name, item.Value)); } } Console.ReadLine(); }
public RedisClient(IOptionsSnapshot <RedisOptions> optionsAccessor) { _options = optionsAccessor.Value; _redis = ConnectionMultiplexer.Connect(_options.ConnectionString).GetDatabase(_options.DatabaseId); }
public RedisCache(AmetistaConfiguration configuration, ILogger <RedisCache> logger) { redis = ConnectionMultiplexer.Connect(configuration.ConnectionStrings.RedisCache); db = redis.GetDatabase(); _logger = logger; }
public static void Main(string[] args) { SqlConnectionStringBuilder stringBuilder = new SqlConnectionStringBuilder(); stringBuilder["Server"] = "127.0.0.1,1433"; stringBuilder["Database"] = "vnexpres"; stringBuilder["User Id"] = "sa"; stringBuilder["Password"] = "******"; SqlConnection sqlConnection = new SqlConnection(stringBuilder.ToString()); sqlConnection.StatisticsEnabled = true; // cho phép thu thập thông tin // Bắt đầu sự kiện thay dổi trạng thái kết nối sqlConnection.StateChange += (object sender, StateChangeEventArgs e) => { Console.WriteLine($"Trạng thái hiện tại: {e.CurrentState}, trạng thái trước:" + $"{e.OriginalState}"); }; sqlConnection.Open(); // mở kết nối // dùng SqlCommand thực hiện SQL using (SqlCommand command = sqlConnection.CreateCommand()) { command.CommandText = "SELECT title, content FROM dbo.News"; using (SqlDataReader reader = command.ExecuteReader()) //sử dụng phương thức ExecuteReader { Console.WriteLine("CÁC TIN TỨC:"); Console.WriteLine($"{"Title"}{"Content"}"); while (reader.Read()) { Console.WriteLine(String.Format("{Title}, {Content}", reader["Title"], reader["Content"])); } } } sqlConnection.Close(); // đóng kết nối // tao ket noi voi redis ConnectionMultiplexer redis = ConnectionMultiplexer.Connect("192.168.1.5:6379,password=NguyenManhHa"); // lay database IDatabase db = redis.GetDatabase(-1); // đọc nguồn cấp dữ liệu rss từ vnexpress Rss20FeedFormatter rssFormatter; using (var xmlReader = XmlReader.Create ("http://vnexpress.net/rss/")) { rssFormatter = new Rss20FeedFormatter(); rssFormatter.ReadFrom(xmlReader); } var title = rssFormatter.Feed.Title.Text; foreach (var syndicationItem in rssFormatter.Feed.Items) { Console.WriteLine("Article: {0}", syndicationItem.Title.Text); Console.WriteLine("URL: {0}", syndicationItem.Links[0].Uri); Console.WriteLine("Summary: {0}", syndicationItem.Summary.Text); Console.WriteLine(); } CreateHostBuilder(args).Build().Run(); }
public override void ConfigureServices(ServiceConfigurationContext context) { var hostingEnvironment = context.Services.GetHostingEnvironment(); var configuration = context.Services.GetConfiguration(); Configure <AbpLocalizationOptions>(options => { options.Resources .Get <BookStoreResource>() .AddBaseTypes( typeof(AbpUiResource) ); options.Languages.Add(new LanguageInfo("ar", "ar", "العربية")); options.Languages.Add(new LanguageInfo("cs", "cs", "Čeština")); options.Languages.Add(new LanguageInfo("en", "en", "English")); options.Languages.Add(new LanguageInfo("en-GB", "en-GB", "English (UK)")); options.Languages.Add(new LanguageInfo("fr", "fr", "Français")); options.Languages.Add(new LanguageInfo("hu", "hu", "Magyar")); options.Languages.Add(new LanguageInfo("pt-BR", "pt-BR", "Português")); options.Languages.Add(new LanguageInfo("ru", "ru", "Русский")); options.Languages.Add(new LanguageInfo("tr", "tr", "Türkçe")); options.Languages.Add(new LanguageInfo("zh-Hans", "zh-Hans", "简体中文")); options.Languages.Add(new LanguageInfo("zh-Hant", "zh-Hant", "繁體中文")); options.Languages.Add(new LanguageInfo("de-DE", "de-DE", "Deutsch", "de")); options.Languages.Add(new LanguageInfo("es", "es", "Español", "es")); }); Configure <AbpBundlingOptions>(options => { options.StyleBundles.Configure( BasicThemeBundles.Styles.Global, bundle => { bundle.AddFiles("/global-styles.css"); } ); }); Configure <AbpAuditingOptions>(options => { //options.IsEnabledForGetRequests = true; options.ApplicationName = "AuthServer"; }); if (hostingEnvironment.IsDevelopment()) { Configure <AbpVirtualFileSystemOptions>(options => { options.FileSets.ReplaceEmbeddedByPhysical <BookStoreDomainSharedModule>(Path.Combine(hostingEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Acme.BookStore.Domain.Shared")); options.FileSets.ReplaceEmbeddedByPhysical <BookStoreDomainModule>(Path.Combine(hostingEnvironment.ContentRootPath, $"..{Path.DirectorySeparatorChar}Acme.BookStore.Domain")); }); } Configure <AppUrlOptions>(options => { options.Applications["MVC"].RootUrl = configuration["App:SelfUrl"]; options.RedirectAllowedUrls.AddRange(configuration["App:RedirectAllowedUrls"].Split(',')); }); Configure <AbpBackgroundJobOptions>(options => { options.IsJobExecutionEnabled = false; }); Configure <AbpDistributedCacheOptions>(options => { options.KeyPrefix = "BookStore:"; }); if (!hostingEnvironment.IsDevelopment()) { var redis = ConnectionMultiplexer.Connect(configuration["Redis:Configuration"]); context.Services .AddDataProtection() .PersistKeysToStackExchangeRedis(redis, "BookStore-Protection-Keys"); } context.Services.AddCors(options => { options.AddPolicy(DefaultCorsPolicyName, builder => { builder .WithOrigins( configuration["App:CorsOrigins"] .Split(",", StringSplitOptions.RemoveEmptyEntries) .Select(o => o.RemovePostFix("/")) .ToArray() ) .WithAbpExposedHeaders() .SetIsOriginAllowedToAllowWildcardSubdomains() .AllowAnyHeader() .AllowAnyMethod() .AllowCredentials(); }); }); }
public RedisCacheProvider() { RedisConfig = Config.Get("Database:Cache:RedisConfig", defaultValue: "localhost:6379"); Redis = ConnectionMultiplexer.Connect(RedisConfig + ",allowAdmin=true"); Server = Redis.GetServer(RedisConfig); }