private MemcachedClientApiConfiguration(
			IEnumerable<IPEndPoint> servers,
			ISocketPoolConfiguration socketPoolConfiguration,
			IMemcachedKeyTransformer keyTransformer, 
			IMemcachedNodeLocator nodeLocator, 
			Func<IMemcachedNodeLocator> nodeLocatorFactory, 
			ITranscoder transcoder, 
			IAuthenticationConfiguration authentication, 
			MemcachedProtocol protocol, 
			IPerformanceMonitor performanceMonitor)
        {
            Condition.Requires(socketPoolConfiguration, "socket pool configuration").IsNotNull();
            Condition.Requires(keyTransformer, "key transformer").IsNotNull();
            Condition.Requires(transcoder, "transcoder").IsNotNull();
            Condition.Requires(authentication, "authentication").IsNotNull();
            Condition.Requires(nodeLocator, "node locator")
                .Evaluate(!(nodeLocator == null && nodeLocatorFactory == null),
                "Both node locator and node locator factory are not set. Requires only one to be set.");
            Condition.Requires(nodeLocator, "node locator")
                .Evaluate(!(nodeLocator == null && nodeLocatorFactory == null),
                "Both node locator and node locator are set. Requires only one to be set.");
            Condition.Requires(servers, "servers").IsNotNull();

            _socketPoolConfiguration = socketPoolConfiguration;
            _keyTransformer = keyTransformer;
            _nodeLocator = nodeLocator;
            _nodeLocatorFactory = nodeLocatorFactory;
            _transcoder = transcoder;
            _authentication = authentication;
            PerformanceMonitor = performanceMonitor;
            Protocol = protocol;
            _servers = servers.ToList();
        }
Ejemplo n.º 2
0
        private static async Task MemcachedProtocol(IServiceProvider serviceProvider)
        {
            var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder.SetMinimumLevel(LogLevel.Error);
                builder.AddConsole();
            });

            var client = new ClientBuilder(serviceProvider)
                         .UseSockets()
                         .UseConnectionLogging(loggerFactory: loggerFactory)
                         .Build();

            var ipAddress  = IPAddress.Parse("127.0.0.1");
            var connection = await client.ConnectAsync(new IPEndPoint(ipAddress, 11211));

            MemcachedProtocol memcachedProtocol = new MemcachedProtocol(connection);

            await memcachedProtocol.Set("Hello", Encoding.UTF8.GetBytes("World"), TimeSpan.FromMinutes(30));

            var checkSet = await memcachedProtocol.Get("Hello");

            Console.WriteLine($"checkSet result :{Encoding.UTF8.GetString(checkSet)}");

            await memcachedProtocol.Replace("Hello", Encoding.UTF8.GetBytes("World replaced"), TimeSpan.FromMinutes(30));

            var checkReplace = await memcachedProtocol.Get("Hello");

            Console.WriteLine($"checkReplace result :{Encoding.UTF8.GetString(checkReplace)}");
        }
Ejemplo n.º 3
0
        protected virtual MemcachedClient GetClient(MemcachedProtocol protocol = MemcachedProtocol.Binary, bool useBinaryFormatterTranscoder = false)
        {
            IServiceCollection services = new ServiceCollection();

            services.AddEnyimMemcached(options =>
            {
                options.AddServer("memcached", 11211);
                options.Protocol = protocol;
                //if (useBinaryFormatterTranscoder)
                //{
                //    options.Transcoder = "BinaryFormatterTranscoder";
                //}
            });
            if (useBinaryFormatterTranscoder)
            {
                services.AddSingleton <ITranscoder, BinaryFormatterTranscoder>();
            }

            services.AddLogging(builder => builder.SetMinimumLevel(LogLevel.Information).AddConsole());

            IServiceProvider serviceProvider = services.BuildServiceProvider();
            var client = serviceProvider.GetService <IMemcachedClient>() as MemcachedClient;

            client.Remove("VALUE");
            return(client);
        }
        private MemcachedClientApiConfiguration(
            IEnumerable <IPEndPoint> servers,
            ISocketPoolConfiguration socketPoolConfiguration,
            IMemcachedKeyTransformer keyTransformer,
            IMemcachedNodeLocator nodeLocator,
            Func <IMemcachedNodeLocator> nodeLocatorFactory,
            ITranscoder transcoder,
            IAuthenticationConfiguration authentication,
            MemcachedProtocol protocol,
            IPerformanceMonitor performanceMonitor)
        {
            Condition.Requires(socketPoolConfiguration, "socket pool configuration").IsNotNull();
            Condition.Requires(keyTransformer, "key transformer").IsNotNull();
            Condition.Requires(transcoder, "transcoder").IsNotNull();
            Condition.Requires(authentication, "authentication").IsNotNull();
            Condition.Requires(nodeLocator, "node locator")
            .Evaluate(!(nodeLocator == null && nodeLocatorFactory == null),
                      "Both node locator and node locator factory are not set. Requires only one to be set.");
            Condition.Requires(nodeLocator, "node locator")
            .Evaluate(!(nodeLocator == null && nodeLocatorFactory == null),
                      "Both node locator and node locator are set. Requires only one to be set.");
            Condition.Requires(servers, "servers").IsNotNull();

            _socketPoolConfiguration = socketPoolConfiguration;
            _keyTransformer          = keyTransformer;
            _nodeLocator             = nodeLocator;
            _nodeLocatorFactory      = nodeLocatorFactory;
            _transcoder        = transcoder;
            _authentication    = authentication;
            PerformanceMonitor = performanceMonitor;
            Protocol           = protocol;
            _servers           = servers.ToList();
        }
Ejemplo n.º 5
0
        static Task LaneCaching()
        {
            return(Task.WhenAll(Enumerable.Range(0, Sockets).Select(async x =>
            {
                var builder = new ClientBuilder().UseSockets().Build();
                var connection = builder.ConnectAsync(new IPEndPoint(IPAddress.Parse(Destination), 11211)).GetAwaiter().GetResult();
                await using (var client = new MemcachedProtocol(new LowLatencyMessageProtocol <MemcachedRequest, IMemcachedResponse>(connection, new MemcachedMessageWriter(), new MemcachedMessageReader())))
                {
                    client.Start();

                    var list = new List <Task>();
                    for (var i = 0; i < Threads; i++)
                    {
                        list.Add(Task.Run(async() => {
                            await client.Set(Key, Value, null);
                            foreach (var batch in Enumerable.Range(0, Iterations).Batch(200))
                            {
                                await Task.WhenAll(batch.Select(x =>
                                                                client.Get <string, StringResponseDeserializer>(Key,
                                                                                                                new StringResponseDeserializer())));
                            }
                        }));
                    }
                    await Task.WhenAll(list);
                }
            })));
        }
        private static IMemcachedClient GetConfiguredClient(string host, int port, MemcachedProtocol protocol)
        {
            Guard.NotEmpty(host, nameof(host));

            var config = new MemcachedClientConfiguration();

            config.AddServer(host, port);
            config.Protocol = protocol;

            return(new MemcachedClient(config));
        }
Ejemplo n.º 7
0
        public async Task SetAndGetValue()
        {
            var builder = new ClientBuilder().UseSockets().Build();

            await using var connection = await builder.ConnectAsync(TestConstants.MemcachedServer);

            await using var client = new MemcachedProtocol(new LowLatencyMessageProtocol <MemcachedRequest, IMemcachedResponse>(connection, new MemcachedMessageWriter(), new MemcachedMessageReader()));
            client.Start();
            await client.Set("key", "value", null);

            var value = await client.Get <string, StringResponseDeserializer>("key", new StringResponseDeserializer());

            Assert.Equal("value", value);
        }
Ejemplo n.º 8
0
        public static void AddMemcached(
            string ip,
            string port,
            MemcachedProtocol protocol = MemcachedProtocol.Binary,
            bool openAuth = false,
            Dictionary <string, object> authPara = null)
        {
            CacheConfiguration.DefaultCacheType = CacheEnum.Memcached;

            MemcachedAssembleConfig.Ip       = ip;
            MemcachedAssembleConfig.Port     = port;
            MemcachedAssembleConfig.Protocol = protocol;
            MemcachedAssembleConfig.AuthPara = authPara;
            MemcachedAssembleConfig.OpenAuth = openAuth;
        }
        protected virtual MemcachedClient GetClient(MemcachedProtocol protocol = MemcachedProtocol.Binary)
        {
            IServiceCollection services = new ServiceCollection();

            services.AddEnyimMemcached(options =>
            {
                options.AddServer("memcached", 11211);
                options.Protocol = protocol;
            });
            services.AddLogging();
            IServiceProvider serviceProvider = services.BuildServiceProvider();
            var client = serviceProvider.GetService <IMemcachedClient>() as MemcachedClient;

            client.Remove("VALUE");
            return(client);
        }
Ejemplo n.º 10
0
        public MemCachedProvider(MemcachedProtocol protocol = MemcachedProtocol.Binary)
        {
            MemcachedClientConfiguration config = new MemcachedClientConfiguration()
            {
                Protocol = protocol
            };

            foreach (string s in readHosts)
            {
                config.AddServer(s);
            }
            foreach (string s in writeHosts)
            {
                config.AddServer(s);
            }
            client = new MemcachedClient(config);
        }
Ejemplo n.º 11
0
        public MemcachedClientConfiguration CreateConfig(List <IPEndPoint> ips, MemcachedProtocol pol)
        {
            MemcachedClientConfiguration memConfig = new MemcachedClientConfiguration();

            foreach (var ip in ips)
            {
                memConfig.Servers.Add(ip);                 //服务器
            }
            memConfig.Protocol = MemcachedProtocol.Binary; //协议
            //文件权限
            memConfig.Authentication.Type = typeof(PlainTextAuthenticator);
            memConfig.Authentication.Parameters["zone"] = "";
            //memConfig.Authentication.Parameters["userName"] = "******";
            //memConfig.Authentication.Parameters["password"] = "******";
            memConfig.SocketPool.MinPoolSize = 5;
            memConfig.SocketPool.MaxPoolSize = 200;
            return(memConfig);
        }
Ejemplo n.º 12
0
        private static async Task MemcachedProtocol(IServiceProvider serviceProvider)
        {
            var loggerFactory = LoggerFactory.Create(builder =>
            {
                builder.SetMinimumLevel(LogLevel.Debug);
                builder.AddConsole();
            });

            var client = new ClientBuilder(serviceProvider)
                         .UseSockets()
                         /* .UseConnectionLogging(loggerFactory: loggerFactory)*/
                         .Build();
            var ipAddress  = IPAddress.Parse("127.0.0.1");
            var connection = await client.ConnectAsync(new IPEndPoint(ipAddress, 11211));

            MemcachedProtocol memcachedProtocol = new MemcachedProtocol(connection);
            var largeString = String.Empty;
            var tasks       = new List <Task <byte[]> >();

            for (int i = 0; i < 10; i++)
            {
                largeString += i + "_";
            }
            //await memcachedProtocol.Set("Hello", Encoding.UTF8.GetBytes(largeString), TimeSpan.FromMinutes(30));

            /*for (int i = 0; i < 10; i++)
             * {
             *  tasks.Add(memcachedProtocol.Get("Hello"));
             * }
             *
             * await memcachedProtocol.Set("Hello", Encoding.UTF8.GetBytes("World!!"), TimeSpan.FromMinutes(30));
             * await Task.WhenAll(tasks);
             *
             * foreach (var item in tasks)
             * {
             *  Console.WriteLine(Encoding.UTF8.GetString(item.Result));
             *  Console.WriteLine("-------------------------------");
             * } */

            Console.WriteLine("Complete");

            //var byteResult = await memcachedProtocol.Get("Hello");
            //var result = Encoding.UTF8.GetString(byteResult);
        }
Ejemplo n.º 13
0
        public async Task DeleteAKey()
        {
            var builder = new ClientBuilder().UseSockets().Build();

            await using var connection = await builder.ConnectAsync(TestConstants.MemcachedServer);

            await using var client = new MemcachedProtocol(new LowLatencyMessageProtocol <MemcachedRequest, IMemcachedResponse>(connection, new MemcachedMessageWriter(), new MemcachedMessageReader()));
            client.Start();

            var key = "ToDelete";

            await client.Set(key, "value", null);

            var value = await client.Get <string, StringResponseDeserializer>(key, new StringResponseDeserializer());

            Assert.Equal("value", value);

            await client.Delete(key);

            await Assert.ThrowsAsync <KeyNotFoundException>(() => client.Get <string, StringResponseDeserializer>(key, new StringResponseDeserializer()));
        }
        protected virtual MemcachedClient GetClient(IServiceCollection services, MemcachedProtocol protocol = MemcachedProtocol.Binary, bool useBinaryFormatterTranscoder = false)
        {
            services.AddEnyimMemcached(options =>
            {
                options.AddServer("memcached", 11211);
                options.Protocol = protocol;
                //if (useBinaryFormatterTranscoder)
                //{
                //    options.Transcoder = "BinaryFormatterTranscoder";
                //}
            });
            if (useBinaryFormatterTranscoder)
            {
                services.AddSingleton <ITranscoder, BinaryFormatterTranscoder>();
            }

            IServiceProvider serviceProvider = services.BuildServiceProvider();
            var client = serviceProvider.GetService <IMemcachedClient>() as MemcachedClient;

            client.Remove("VALUE");
            return(client);
        }
Ejemplo n.º 15
0
        private async Task RunLaneCache(Func <ConnectionContext, IMessageProtocol <MemcachedRequest, IMemcachedResponse> > protocol)
        {
            var builder    = new ClientBuilder().UseSockets().Build();
            var connection = await builder.ConnectAsync(new IPEndPoint(IPAddress.Parse("10.0.0.21"), 11211));

            await using var client = new MemcachedProtocol(protocol(connection));
            client.Start();
            var list = new List <Task>();

            for (var i = 0; i < Threads; i++)
            {
                list.Add(Task.Run(async() => {
                    await client.Set(Key, Value, null);
                    foreach (var batch in Enumerable.Range(0, Iterations).Batch(200))
                    {
                        await Task.WhenAll(batch.Select(x =>
                                                        client.Get <string, StringResponseDeserializer>(Key,
                                                                                                        new StringResponseDeserializer())));
                    }
                }));
            }
            await Task.WhenAll(list);
        }
Ejemplo n.º 16
0
        public async Task ReplaceValue()
        {
            var builder = new ClientBuilder().UseSockets().Build();

            await using var connection = await builder.ConnectAsync(TestConstants.MemcachedServer);

            await using var client = new MemcachedProtocol(new LowLatencyMessageProtocol <MemcachedRequest, IMemcachedResponse>(connection, new MemcachedMessageWriter(), new MemcachedMessageReader()));
            client.Start();

            var key = "ToReplace";

            await client.Set(key, "firstValue", null);

            var value = await client.Get <string, StringResponseDeserializer>(key, new StringResponseDeserializer());

            Assert.Equal("firstValue", value);

            await client.Replace(new StringWritable(key), new StringWritable("newValue"), null);

            var replaced = await client.Get <string, StringResponseDeserializer>(key, new StringResponseDeserializer());

            Assert.Equal("newValue", replaced);
        }
Ejemplo n.º 17
0
        public async Task ExpireQuickly()
        {
            var builder = new ClientBuilder().UseSockets().Build();

            await using var connection = await builder.ConnectAsync(TestConstants.MemcachedServer);

            await using var client = new MemcachedProtocol(new LowLatencyMessageProtocol <MemcachedRequest, IMemcachedResponse>(connection, new MemcachedMessageWriter(), new MemcachedMessageReader()));
            client.Start();

            var key = "ToExpire";

            var expirationTime = TimeSpan.FromSeconds(2);

            await client.Set(key, "firstValue", expirationTime);

            var value = await client.Get <string, StringResponseDeserializer>(key, new StringResponseDeserializer());

            Assert.Equal("firstValue", value);

            // memcached expires entries on 1-second boundaries, so setting this to n+1 seconds expiration may cause the test to fail some of the time
            await Task.Delay(expirationTime.Add(TimeSpan.FromSeconds(2)));

            await Assert.ThrowsAsync <KeyNotFoundException>(() => client.Get <string, StringResponseDeserializer>(key, new StringResponseDeserializer()));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MemcachedCacheProvider" /> class.
 /// </summary>
 /// <param name="host">The host name.</param>
 /// <param name="port">The port.</param>
 /// <param name="username">The username to use to authenticate with the server.</param>
 /// <param name="password">The password to use to authenticate with the server.</param>
 /// <param name="protocol">The type of the communication between client and server.</param>
 public MemcachedCacheProvider([NotNull] string host, int port, [NotNull] string username, [NotNull] string password, MemcachedProtocol protocol) : this(host, port, username, password, protocol, (TimeSpan?)null)
 {
 }
Ejemplo n.º 19
0
        private static IMemcachedClientConfiguration GetClientConfiguration(string host, string username, string password, MemcachedProtocol protocol, Type authType = null)
        {
            var config = new MemcachedClientConfiguration();

            if (!string.IsNullOrEmpty(host))
            {
                config.AddServer(host);
            }

            config.Protocol            = protocol;
            config.Authentication.Type = authType;

            if (!string.IsNullOrEmpty(username))
            {
                config.Authentication.Parameters["userName"] = username;
            }

            if (!string.IsNullOrEmpty(password))
            {
                config.Authentication.Parameters["password"] = password;
            }

            return(config);
        }
Ejemplo n.º 20
0
 public MemcachedCacheProvider(string host, string username, string password, MemcachedProtocol protocol, Type authType, TimeSpan?expiry, JsonSerializerSettings serializerSettings)
     : this(GetClientConfiguration(host, username, password, protocol, authType), expiry, serializerSettings)
 {
 }
        private static IMemcachedClient GetConfiguredClient(string host, int port, string username, string password, MemcachedProtocol protocol)
        {
            Guard.NotEmpty(host, nameof(host));
            Guard.NotEmpty(username, nameof(username));
            Guard.NotEmpty(password, nameof(password));

            var config = new MemcachedClientConfiguration();

            config.AddServer(host, port);
            config.Protocol            = protocol;
            config.Authentication.Type = typeof(PlainTextAuthenticator);
            config.Authentication.Parameters["userName"] = username;
            config.Authentication.Parameters["password"] = password;

            return(new MemcachedClient(config));
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MemcachedCacheProvider" /> class.
 /// </summary>
 /// <param name="host">The host name.</param>
 /// <param name="port">The port.</param>
 /// <param name="protocol">The type of the communication between client and server.</param>
 public MemcachedCacheProvider([NotNull] string host, int port, MemcachedProtocol protocol) : this(host, port, protocol, (TimeSpan?)null)
 {
 }
Ejemplo n.º 23
0
        /// <summary>
        /// Adds the giving protocal to the options.
        /// </summary>
        /// <param name="protocal">The protocal to be added.</param>
        public MemcachedCacheOptions WithProtocal([NotNull] MemcachedProtocol protocal)
        {
            _protocal = Guard.NotNull(protocal, nameof(protocal));

            return(this);
        }
 /// <summary>
 /// Initializes a new instance of the <see cref="MemcachedCacheProvider" /> class.
 /// </summary>
 /// <param name="host">The host name.</param>
 /// <param name="port">The port.</param>
 /// <param name="protocol">The type of the communication between client and server.</param>
 /// <param name="expiry">The caching expiration time.</param>
 public MemcachedCacheProvider([NotNull] string host, int port, MemcachedProtocol protocol, [CanBeNull] TimeSpan?expiry) : this(GetConfiguredClient(host, port, protocol), expiry)
 {
 }