我正在尝试使用 Enyim 客户端库从 Memcache 服务器获取键值。
连接到 memcache 服务器后,我可以写入/替换键值,但是在使用 get 操作时会抛出以下异常:
NotSupportedException was unhandled 服务器不支持操作或请求格式错误。如果是后者,请将错误报告给开发人员。
请注意,我可以使用 telnet/其他 memcache 库读取此值。
我不确定我是否遗漏了什么或者 Enyim 包中是否有错误?
这是代码。
using System;
using System.Net;
using Enyim.Caching;
using Enyim.Caching.Configuration;
using Enyim.Caching.Memcached;
namespace Memcached
{
public class MemcacheClient
{
private MemcachedClient _mc;
private static readonly TimeSpan MinExpirationTimeSpan = new TimeSpan(0, 0, 30);
public MemcacheClient()
{
Startup();
}
private void Startup()
{
var config = new MemcachedClientConfiguration();
config.Servers.Add(new IPEndPoint(IPAddress.Loopback, 11212));
// config.Servers.Add(new IPEndPoint(IPAddress.Loopback, 11213));
config.Protocol = MemcachedProtocol.Text;
_mc = new MemcachedClient(config);
}
public bool SetItem(string key, object value)
{
if (_mc != null)
return _mc.Store(StoreMode.Set, key, value);
return false;
}
public bool SetItem(string key, object value, TimeSpan duration)
{
_ValidateExpirationDuration(duration);
if (_mc != null)
{
var restult = _mc.Store(StoreMode.Set, key, value, DateTime.Now + duration);
_mc.FlushAll();
return restult;
}
return false;
}
private static void _ValidateExpirationDuration(TimeSpan duration)
{
if (duration <= MinExpirationTimeSpan)
throw new ArgumentException("Cache expiration times of less than 30 seconds are ignored", "duration");
}
public object GetItem(string key)
{
if (_mc != null)
return _mc.Get(key); //<----------getting exception here
return null;
}
public T GetItem<T>(string key) where T : class
{
var result = GetItem(key);
if (result != null)
{
var targetObject = result as T;
if (targetObject != null)
return targetObject;
}
return null;
}
public bool Replace(string key, object value, TimeSpan duration)
{
_ValidateExpirationDuration(duration);
if (_mc != null)
return _mc.Store(StoreMode.Replace, key, value, DateTime.Now + duration);
return false;
}
public bool Replace(string key, object value)
{
if (_mc != null)
return _mc.Store(StoreMode.Replace, key, value);
return false;
}
}
}
调用函数
using System;
using System.Globalization;
namespace TryEnyim
{
class Program
{
static void Main(string[] args)
{
var cache = new Memcached.MemcacheClient();
Console.Write("Writing to cache: " + cache.SetItem("myString", "This is enyim @" + System.DateTime.Now.ToString(CultureInfo.InvariantCulture)));
cache.Replace("myString", "This is enyim again @" + System.DateTime.Now.AddSeconds(10).ToString(CultureInfo.InvariantCulture));
Console.WriteLine("Read key now: " + cache.GetItem<string>("myString"));// <----------getting exception here
Console.ReadLine();
}
}
}
我正在使用 NuGet 的 Enyim 包(版本 2.12.0.0)。
任何帮助都会很有用。
谢谢