using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Globalization;
using System.Text;
using CYQ.Data.Tool;
namespace CYQ.Data.Cache
{
///
/// Redis client main class.
/// Use the static methods Setup and GetInstance to setup and get an instance of the client for use.
///
internal class RedisClient : ClientBase
{
#region Static fields and methods.
private static LogAdapter logger = LogAdapter.GetLogger(typeof(RedisClient));
public static RedisClient Create(string configValue)
{
return new RedisClient(configValue);
}
private RedisClient(string configValue)
{
hostServer = new HostServer(CacheType.Redis, configValue);
hostServer.OnAuthEvent += new HostServer.AuthDelegate(hostServer_OnAuthEvent);
}
bool hostServer_OnAuthEvent(MSocket socket)
{
if (!Auth(socket.HostNode.Password, socket))
{
string err = "Auth password fail : " + socket.HostNode.Password;
socket.HostNode.Error = err;
Error.Throw(err);
}
return true;
}
#endregion
#region Set、Append
public bool Append(string key, object value, int seconds) { return Set("append", key, true, value, hash(key), seconds); }
public bool Set(string key, object value, int seconds) { return Set("set", key, true, value, hash(key), seconds); }
private bool Set(string command, string key, bool keyIsChecked, object value, uint hash, int expirySeconds)
{
if (!keyIsChecked)
{
checkKey(key);
}
string result = hostServer.Execute(hash, "", delegate(MSocket socket)
{
SerializedType type;
byte[] bytes;
byte[] typeBit = new byte[1];
try
{
bytes = Serializer.Serialize(value, out type, compressionThreshold);
typeBit[0] = (byte)type;
}
catch (Exception e)
{
logger.Error("Error serializing object for key '" + key + "'.", e);
return "";
}
// CheckDB(socket, hash);
int db = GetDBIndex(socket, hash);
// Console.WriteLine("Set :" + key + ":" + hash + " db." + db);
int skipCmd = 0;
using (RedisCommand cmd = new RedisCommand(socket))
{
if (db > -1)
{
cmd.Reset(2, "Select");
cmd.AddKey(db.ToString());
skipCmd++;
}
cmd.Reset(3, command);
cmd.AddKey(key);
cmd.AddValue(typeBit, bytes);
skipCmd++;
//cmd.Send();
//if (db != -1)
//{
// string aaa = socket.ReadLine();
//}
//result = socket.ReadResponse();
//if (result[0] != '-')
//{
if (expirySeconds > 0)
{
cmd.Reset(3, "EXPIRE");
cmd.AddKey(key);
cmd.AddKey(expirySeconds.ToString());
skipCmd++;
// cmd.Send();
//result = socket.ReadResponse();
}
// }
}
socket.SkipToEndOfLine(skipCmd - 1);
return socket.ReadResponse();
});
return result == "+OK" || result == ":1";
}
#endregion
#region Get
public object Get(string key) { return Get("get", key, true, hash(key)); }
private object Get(string command, string key, bool keyIsChecked, uint hash)
{
if (!keyIsChecked)
{
checkKey(key);
}
object value = hostServer.Execute