Example #1
0
        static void Main(string[] args)
        {
            string connectionString = "localhost:6379";

            IConnector  connector  = new RedisConnector(connectionString);
            ISerializer serializer = new MySerializer();

            ICache rediCache = new RedisCache(connector, serializer);

            var cacheWrapper = new CacheWrapper(rediCache);

            var cache = new CacheTimeWrapper(cacheWrapper);

            Api api = new Api(cache);

            for (int i = 0; i < 10; i++)
            {
                var result = api.GetInformation();

                Thread.Sleep(5000);

                string value = serializer.Serializer(result);
                Console.WriteLine(value);
            }

            Console.ReadKey();
        }
Example #2
0
        //[Authorize]
        public async Task <IActionResult> Index()
        {
            List <Product> lstproducts;

            lstproducts = RedisConnector.Get <List <Product> >(User.Identity.Name + "lstProduct");
            if (lstproducts == null)
            {
                lstproducts = await apiProxy.GetListAsync <Product>("product/GetAll");

                //Saving a list to redis using object
                RedisConnector.Set(User.Identity.Name + "lstProduct", lstproducts);
            }

            if (User.Identity.IsAuthenticated)
            {
                ViewBag.Username = User.Identity.Name;
                List <string> lstClaims = new List <string>();
                foreach (var claims in User.Claims)
                {
                    lstClaims.Add(claims.Value);
                }
            }


            return(View(lstproducts));
        }
Example #3
0
        public async Task <IActionResult> Logout()
        {
            RedisConnector.DeleteKeys(User.Identity.Name + "lstProduct");

            await HttpContext.SignOutAsync(CookieAuthenticationDefaults.AuthenticationScheme);

            return(Redirect("/"));
        }
        internal RedisSentinelClient(IRedisSocket socket, EndPoint endpoint, int concurrency, int bufferSize)
        {
            _connector    = new RedisConnector(endpoint, socket, concurrency, bufferSize);
            _subscription = new SubscriptionListener(_connector);

            _subscription.MessageReceived += OnSubscriptionReceived;
            _subscription.Changed         += OnSubscriptionChanged;
            _connector.Connected          += OnConnectionReconnected;
        }
Example #5
0
        public async Task Init()
        {
            var ds = GetValidStream();

            if (_redisConnector == null)
            {
                _redisConnector = new RedisConnector(_logger);
                await _redisConnector.InitAsync(ds);
            }
        }
Example #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PubSubRedisLogProvider" /> class.
        /// </summary>
        /// <param name="redis">The redis.</param>
        /// <param name="propagationStrategy">The propagation strategy.</param>
        /// <param name="cancellationToken">The cancellation token.</param>
        public PubSubRedisLogProvider(RedisConnector redis, IPropagationStrategy propagationStrategy, CancellationToken cancellationToken)
        {
            _redis = redis;
            _propagationStrategy = propagationStrategy;
            _cancellationToken   = cancellationToken;
            _queue = new ConcurrentQueue <string>();
            var thread = new Thread(Worker);

            thread.Start();
        }
Example #7
0
        public static void Initialize(string redisConnector, Guid sender)
        {
            _redisConnector = redisConnector;
            _sender         = sender;

            //创建连接
            _redis = RedisConnector.Open(redisConnector);

            _subscriber = _redis.GetSubscriber();
        }
Example #8
0
 private void btnConnect_Click(object sender, EventArgs e)
 {
     try
     {
         this.connector = new RedisConnector(ConfigurationManager.AppSettings["redisserver"]);
         MessageBox.Show("Connect successfully");
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.ToString());
     }
 }
        public RedisClient(IRedisSocket socket, EndPoint endpoint, int asyncConcurrency, int asyncBufferSize)
        {
            _connector    = new RedisConnector(endpoint, socket, asyncConcurrency, asyncBufferSize);
            _transaction  = new RedisTransaction(_connector);
            _subscription = new SubscriptionListener(_connector);
            _monitor      = new MonitorListener(_connector);

            _subscription.MessageReceived  += OnSubscriptionReceived;
            _subscription.Changed          += OnSubscriptionChanged;
            _monitor.MonitorReceived       += OnMonitorReceived;
            _connector.Connected           += OnConnectionConnected;
            _transaction.TransactionQueued += OnTransactionQueued;
        }
Example #10
0
        public static SubterfugeClient.SubterfugeClient GetClient()
        {
            String Hostname = "server"; // For docker
            // String Hostname = "localhost"; // For local
            int Port = 5000;

            String dbHost = "db"; // For docker
            // String dbHost = "localhost"; // For local
            int dbPort = 6379;

            RedisConnector db = new RedisConnector(dbHost, dbPort.ToString(), true);

            return(new SubterfugeClient.SubterfugeClient(Hostname, Port.ToString()));
        }
Example #11
0
        static void Main(string[] args)
        {
            DateTime start, end;
            var      rnd = new Random();

            try
            {
                RedisConnector connector = new RedisConnector(ConfigurationManager.AppSettings["redisserver"]);

                #region delete
                Console.WriteLine("DELETE all \"Product*\"-pattern keys in Redis...");
                start = DateTime.Now;
                int countDeleted = connector.KeyDelete("Product*");
                end = DateTime.Now;
                Console.WriteLine($"There are {countDeleted} \"Product*\"-pattern keys. Deleted them in {(end - start).TotalMilliseconds} millisecs");
                #endregion

                #region add
                Console.Write("How many Products do you want to prepare in Redis? ");
                int NumberOfProducts = int.Parse(Console.ReadLine());
                Console.WriteLine($"Preparing {NumberOfProducts} products...");
                start = DateTime.Now;
                for (int i = 1; i <= NumberOfProducts; i++)
                {
                    connector.StringSet($"Product{i}", DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
                }
                end = DateTime.Now;
                Console.WriteLine($"Prepared {NumberOfProducts} products in {(end - start).TotalMilliseconds} millisecs");
                #endregion

                Console.Write($"How many heartbeats do you want to play on {NumberOfProducts} products? ");
                int NumberOfHeartbeats = int.Parse(Console.ReadLine());
                Console.WriteLine($"Preparing to spam {NumberOfHeartbeats} heatbeats on {NumberOfProducts} products...");
                start = DateTime.Now;
                for (int i = 0; i < NumberOfHeartbeats; i++)
                {
                    string key   = $"Product{rnd.Next(1, NumberOfProducts + 1)}";
                    string value = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");
                    connector.StringSet(key, value);
                }
                end = DateTime.Now;
                Console.WriteLine($"Updating {NumberOfHeartbeats} heatbeats in {(end - start).TotalMilliseconds} millisecs");
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            Console.Write("Press Enter to exit.");
            Console.ReadLine();
        }
Example #12
0
        public async Task <IActionResult> Index()
        {
            PatientViewModel             objModel  = new PatientViewModel();
            List <AppointmentListDoctor> lstdoctor = RedisConnector.Get <List <AppointmentListDoctor> >(User.Identity.Name + "Appointmentlstdoctor");

            if (lstdoctor == null)
            {
                lstdoctor = await apiProxy.GetListAsync <AppointmentListDoctor>("patient/GetDoctors");

                //Saving a list to redis using object
                RedisConnector.Set(User.Identity.Name + "Appointmentlstdoctor", lstdoctor);
            }
            objModel.AvailableDoctors = lstdoctor;
            return(View(objModel));
        }
Example #13
0
        public new void TestCleanup()
        {
            var container = GetConfiguredContainer();

            if (Redis)
            {
                RedisConnector redisConnector = container.Resolve <RedisConnector>();
                var            redis          = redisConnector.GetMultiplexer();
                foreach (var endpoint in redis.GetEndPoints())
                {
                    var server = redis.GetServer(endpoint);
                    server.FlushDatabase(DB_ID);
                }
            }
        }
Example #14
0
        static void Main(string[] args)
        {
            RedisConnector   redis       = new RedisConnector(dbHost, dbPort.ToString(), false);
            SubterfugeServer grpcService = new SubterfugeServer();

            Server server = new Server
            {
                Services = { subterfugeService.BindService(grpcService).Intercept(new JwtInterceptor()) },
                Ports    = { new ServerPort(Hostname, Port, ServerCredentials.Insecure) }
            };

            Console.WriteLine($"Listening on {Port}...");
            RedisUserModel.CreateSuperUser(); // Creates a super user with admin powers.
            server.Start();
            Shutdown.WaitOne();
            server.ShutdownAsync().Wait();
        }
Example #15
0
        internal RedisClient(IRedisSocket socket, EndPoint endpoint, int asyncConcurrency, int asyncBufferSize)
        {
            // use invariant culture - we have to set it explicitly for every thread we create to
            // prevent any floating-point problems (mostly because of number formats in non en-US cultures).
            //CultureInfo.DefaultThreadCurrentCulture = CultureInfo.InvariantCulture; 这行会影响 string.Compare 结果

            _connector    = new RedisConnector(endpoint, socket, asyncConcurrency, asyncBufferSize);
            _transaction  = new RedisTransaction(_connector);
            _subscription = new SubscriptionListener(_connector);
            _monitor      = new MonitorListener(_connector);

            _subscription.MessageReceived  += OnSubscriptionReceived;
            _subscription.Changed          += OnSubscriptionChanged;
            _monitor.MonitorReceived       += OnMonitorReceived;
            _connector.Connected           += OnConnectionConnected;
            _transaction.TransactionQueued += OnTransactionQueued;
        }
Example #16
0
        public DistributedMemoryCache(CacheOption option)
        {
            string redisConnector = option?.Params?[_redisConnectorKey]?.ToString();

            if (string.IsNullOrEmpty(redisConnector))
            {
                throw new ArgumentNullException(_redisConnectorKey);
            }

            //创建连接
            _redis = RedisConnector.Open(redisConnector);

            _subscriber = _redis.GetSubscriber();

            //订阅CacheRunner的通道
            _subscriber.Subscribe(_channel, Broker_MsgRecevied);

            CacheSyncMsgDispatcher.Initialize(redisConnector, _self);
        }
Example #17
0
 public UserRepository(RedisConnector redisConnector) : base(redisConnector)
 {
 }
Example #18
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RedisTelemetryClient" /> class.
 /// </summary>
 public RedisTelemetryClient()
 {
     _redis      = ServiceLocator.Resolve <RedisConnector>();
     _defaultTTL = new TimeSpan(30, 0, 0, 0);
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            ThreadPool.SetMinThreads(500, 50);
            //Add Dependency Injection
            var redisConfig   = Configuration.GetSection(GlobalConstants.REDIS_CONFIG_KEY).Get <RedisConfig>();
            var redisInstance = new RedisConnector(
                new RedisConfig()
            {
                HostName = redisConfig.HostName,
                Key      = redisConfig.Key,
                Port     = redisConfig.Port,
                SSL      = "true"
            });

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder
                                  .WithOrigins(Configuration["AllowedOrigins"].Split(','))
                                  .AllowAnyOrigin()
                                  .AllowAnyHeader()
                                  );
            });

            services.AddSingleton(x => redisInstance);
            services.AddScoped <IArticleBiz, ArticleBiz>();
            services.AddScoped <IArticleDataService, ArticleDataService>();
            services.AddScoped <IRedisCacheRepository, RedisCacheRepository>();
            services.AddScoped(typeof(IGenericRepository <>), typeof(GenericRepository <>));
            services.AddTransient <IDbConnection>(x =>
            {
                return(new NpgsqlConnection(Configuration[GlobalConstants.DATABASE_CONFIG_KEY]));
            });
            services.AddMvc(o => o.EnableEndpointRouting = false);

            services.AddHttpsRedirection(option =>
            {
                option.RedirectStatusCode = StatusCodes.Status307TemporaryRedirect;
                option.HttpsPort          = 5001;
            });

            services.AddSwaggerGen(
                c =>
            {
                c.SwaggerDoc("v1", new OpenApiInfo {
                    Title = GlobalConstants.SWAGGER_TITLE, Version = "v1", Description = GlobalConstants.SWAGGER_DESCRIPTION
                });
                c.AddSecurityDefinition("Bearer", new OpenApiSecurityScheme
                {
                    In     = ParameterLocation.Header,
                    Type   = SecuritySchemeType.ApiKey,
                    Scheme = "Bearer"
                });
                c.AddSecurityRequirement(new OpenApiSecurityRequirement
                {
                    {
                        new OpenApiSecurityScheme
                        {
                            Reference = new OpenApiReference {
                                Type = ReferenceType.SecurityScheme, Id = "Bearer"
                            },
                            Scheme = "oauth2",
                            Name   = "Bearer",
                            In     = ParameterLocation.Header
                        },
                        new List <string>()
                    }
                });
            });
        }
Example #20
0
        internal RedisSentinelClient(IRedisSocket socket, EndPoint endpoint, int concurrency, int bufferSize)
        {
            _connector = new RedisConnector(endpoint, socket, concurrency, bufferSize);
            _subscription = new SubscriptionListener(_connector);

            _subscription.MessageReceived += OnSubscriptionReceived;
            _subscription.Changed += OnSubscriptionChanged;
            _connector.Connected += OnConnectionReconnected;
        }
Example #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RedisTelemetryClient" /> class.
 /// </summary>
 /// <param name="redis">The redis.</param>
 /// <param name="suffix">The key suffix</param>
 public RedisTelemetryClient(RedisConnector redis, string suffix)
 {
     _redis  = redis;
     _suffix = suffix;
 }
Example #22
0
        public RedisClient(IRedisSocket socket, EndPoint endpoint, int asyncConcurrency, int asyncBufferSize)
        {
            _connector = new RedisConnector(endpoint, socket, asyncConcurrency, asyncBufferSize);

            _connector.Connected += OnConnectionConnected;
        }
Example #23
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RedisCacheRepository" /> class.
 /// </summary>
 /// <param name="connector">The connector.</param>
 public RedisCacheRepository(RedisConnector connector)
 {
     _connector   = connector;
     _cacheClient = connector.Cache;
 }
Example #24
0
 /// <summary>
 /// Constructor.
 /// </summary>
 public RedisNotificationPlugin(RedisConnector redisConnector)
 {
     this.redisConnector = redisConnector;
 }
 public static void ResetAllRedisKey(string key, bool isRealServer)
 {
     RedisConnector.KeyDelete(key, isRealServer);
 }
 public static void ResetLongTermBuyFlagOff(string key, bool isRealServer)
 {
     RedisConnector.FlagOff(key, isRealServer);
     LogUtil.Instance.WriteLog($"{key} 가 리셋되었습니다.");
 }