火冰狐 发表于 2015-7-23 03:41:01

Python/dotNET Redis服务连接客户端调用SET方法的同时获取Redis服务器返回的内容

  在用Python或dotNET redis客户端连接redis服务器的时候,当你调用客户端的SET方法后同时还想得到其返回的字符串,那么需要处理一下。
  
  1. Redis Python redis客户端:
      默认的SET方法返回的数据类型是布尔型的,即True或False,如果需要获取调用SET方法后服务器返回的原始数据,那么需要在客户端对象上调用一下set_response_callback方法即可,于是返回就是redis服务器的数据了
  from redis import Redis
      redis_client = Redis(host="192.168.0.123", port=1234)
      redis_client.set_response_callback('SET', lambda a,**b: a)
  redis_key = "test"
      redis_param = '{"id":1,"title":"test"}'
      redis_resp_string = redis_client.set(redis_key, redis_param)
  
  2. Redis dotNET ServiceStack.Redis 客户端:
      Redis dotNET版的ServiceStack.Redis客户端需要修改源码,默认的SET方法是不会返回数据的。
  2.1 在源代码的RedisClient.ICacheClient.cs文件增加一个方法:
      public string SetCustom(string key, string value)
      {
            return base.SetCustom(key, value.ToUtf8Bytes());
      }
      2.2 然后在RedisNativeClient.cs文件增加一个方法:
      public string SetCustom(string key, byte[] value)
      {
            if (key == null)
                throw new ArgumentNullException("key");
            value = value ?? new byte;
            if (value.Length > OneGb)
                throw new ArgumentException("value exceeds 1G", "value");
            return SendExpectSuccessCustom(Commands.Set, key.ToUtf8Bytes(), value);
      }
      2.3然后在RedisNativeClient_Utils.cs文件增加两个方法:
      protected string SendExpectSuccessCustom(params byte[][] cmdWithBinaryArgs)
      {
            if (!SendCommand(cmdWithBinaryArgs))
                throw CreateConnectionError();
            if (Pipeline != null)
            {
                Pipeline.CompleteStringQueuedCommand(ExpectSuccessCustom);
                return String.Empty;
            }
            return ExpectSuccessCustom();
      }
      protected string ExpectSuccessCustom()
      {
            var multiData = ReadMultiData();
            byte[] byteData = multiData;
            string stringData = byteData.FromUtf8Bytes();
            return stringData;
      }
      2.4 调用方式:
      redisClient = new RedisClient("192.168.0.123", 9570);
      string strKey = "test";
      string strValue = "123";
      string redisRespString = redisClient.SetCustom(strKey, strValue);
3. 修改RedisClient.ICacheClient.cs文件里的Get(string key)方法
public T Get(string key){
    //原代码
    /*
    return typeof(T) == typeof(byte[])
                ? (T)(object)base.Get(key)
                : JsonSerializer.DeserializeFromString(GetValue(key));
    */
    //修改成如下
    if(typeof(T) == typeof(byte[])){
      return (T)(object)base.Get(key);
    }else{
      string resultValue = GetValue(key);
      if (typeof(T) == typeof(string)){
            return (T)(object)resultValue;
      }else{
            return JsonSerializer.DeserializeFromString(resultValue);
      }
    }
}
  
  
  
  
  
      
  
  
  
页: [1]
查看完整版本: Python/dotNET Redis服务连接客户端调用SET方法的同时获取Redis服务器返回的内容