Beispiel #1
0
 public override bool GetUrlElement()
 {
     try
     {
         byte[] data = (byte[])actionGetter.GetMessage();
         if (data.Length > 0)
         {
             requestPack = ProtoBufUtils.Deserialize <RequestLog80000Pack>(data);
             return(true);
         }
         return(false);
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("GetUrlElement:{0} error:{1}", actionId, ex);
         return(false);
     }
 }
Beispiel #2
0
        private static byte[] GenPackage(int type, Player sender, string message)
        {
            LCGetChat chatPackage = new LCGetChat();

            chatPackage.Type    = type;
            chatPackage.Massage = message;
            chatPackage.Sender  = new PBPlayerInfo()
            {
                Id       = sender.Id,
                Name     = sender.Name,
                VipLevel = sender.VIPLevel,
                Level    = sender.Level
            };
            chatPackage.Time = DateTime.UtcNow.Ticks;
            byte[] data   = ProtoBufUtils.Serialize(chatPackage);
            byte[] buffer = CustomActionDispatcher.GeneratePackageStream(3002, data);
            return(buffer);
        }
Beispiel #3
0
        /// <summary>
        /// The game service start.
        /// </summary>
        /// <param name="setting">Environment setting.</param>
        /// <param name="cacheSetting">Cache setting.</param>
        public static void Start(EnvironmentSetting setting, CacheSetting cacheSetting)
        {
            if (_isRunning == 1)
            {
                return;
            }

            _setting = setting;
            if (!RedisConnectionPool.CheckConnect())
            {
                string error = string.Format("Error: the redis server is not started.");
                Console.WriteLine(error);
                TraceLog.WriteError(error);
                return;
            }
            DbConnectionProvider.Initialize();
            EntitySchemaSet.CacheGlobalPeriod = _setting.CacheGlobalPeriod;
            EntitySchemaSet.CacheUserPeriod   = _setting.CacheUserPeriod;
            if (_setting.EntityAssembly != null)
            {
                ProtoBufUtils.LoadProtobufType(_setting.EntityAssembly);
                EntitySchemaSet.LoadAssembly(_setting.EntityAssembly);
            }
            EntitySchemaSet.StartCheckTableTimer();
            LoadGameEntitySchema();
            ZyGameBaseConfigManager.Intialize();
            //init script.
            if (_setting.ScriptSysAsmReferences.Length > 0)
            {
                ScriptEngines.AddSysReferencedAssembly(_setting.ScriptSysAsmReferences);
            }
            ScriptEngines.AddReferencedAssembly("ZyGames.Framework.Game.dll");
            if (_setting.ScriptAsmReferences.Length > 0)
            {
                ScriptEngines.AddReferencedAssembly(_setting.ScriptAsmReferences);
            }
            ScriptEngines.RegisterModelChangedBefore(OnModelChangeBefore);
            ScriptEngines.RegisterModelChangedAfter(OnModelChangeAtfer);
            ScriptEngines.Initialize();
            Language.SetLang();
            CacheFactory.Initialize(cacheSetting);
            Global = new ContextCacheSet <CacheItem>("__gameenvironment_global");
            Interlocked.Exchange(ref _isRunning, 1);
        }
Beispiel #4
0
        protected override bool DecodePacket(MessageStructure reader, MessageHead head)
        {
            responsePack = ProtoBufUtils.Deserialize <Response1005Pack>(netReader.Buffer);
            string responseDataInfo = "";

            responseDataInfo  = "request :" + Game.Utils.JsonHelper.prettyJson <Request1005Pack>(req) + "\n";
            responseDataInfo += "response:" + Game.Utils.JsonHelper.prettyJson <Response1005Pack>(responsePack) + "\n";
            DecodePacketInfo  = responseDataInfo;
            int childStepId = getChild(1005);

            if (childStepId > 0)
            {
                Dictionary <string, string> dic = new Dictionary <string, string>();
                dic.Add("the3rdUserID", responsePack.the3rdUserId.ToString());
                dic.Add("strThe3rdUserID", dic["the3rdUserID"]);
                SetChildStep(childStepId.ToString(), _setting, dic);
            }
            return(true);
        }
Beispiel #5
0
    static void OnTargetChg(byte[] data)
    {
        Scene scn = SceneSystem.Instance.mCurrentScene;

        if (scn == null)
        {
            return;
        }
        ReqTargetChg targetChg = ProtoBufUtils.Deserialize <ReqTargetChg>(data);
        Character    cha       = scn.GetCharacter(targetChg.uid);

        if (cha == null)
        {
            return;
        }
        Character target = scn.GetCharacter(targetChg.targetID);

        cha.SetTarget(target, false);
    }
Beispiel #6
0
    void NotifyMatchReady(byte[] data)
    {
        ReqMatch msg = ProtoBufUtils.Deserialize <ReqMatch>(data);

        if (msg.UserID == GameController.mUserInfo.uid)
        {
            readyBtn.interactable = false;
        }

        for (int i = 0; i < playerIDs.Length; ++i)
        {
            int uid = playerIDs[i];
            if (msg.UserID != uid)
            {
                continue;
            }
            playerLocks[i].SetActive(true);
        }
    }
Beispiel #7
0
        public static string LoadAssembly()
        {
            string error = "";

            if (_setting.Entity.IsScript)
            {
                ScriptCompiler.ClearTemp("smstemp");
                var refAsm = new string[] {
                    "NLog.dll",
                    "Newtonsoft.Json.dll",
                    "protobuf-net.dll",
                    "ZyGames.Framework.dll",
                    "ZyGames.Framework.Common.dll",
                    "ZyGames.Framework.Game.dll"
                };

                AppDomain.CurrentDomain.AppendPrivatePath(Path.Combine(MathUtils.RuntimePath, "smstemp"));
                var files = Directory.GetFiles(_setting.Entity.ScriptPath, "*.cs", SearchOption.AllDirectories);
                var cr    = ScriptCompiler.Compile(files, refAsm, "Entity.Model", false, false, "smstemp");
                if (cr != null)
                {
                    var assembly = cr.CompiledAssembly;
                    _setting.Entity.DymincEntity = assembly;
                }
                else
                {
                    error = "Compile fail";
                }
            }
            else
            {
                AppDomain.CurrentDomain.AppendPrivatePath(Path.GetFullPath(_setting.Entity.AssemblyPath));
                _setting.Entity.DymincEntity = AssemblyBuilder.ReadAssembly(_setting.Entity.AssemblyPath, null);
            }
            try
            {
                ProtoBufUtils.LoadProtobufType(_setting.Entity.DymincEntity);
            }
            catch (Exception)
            {
            }
            return(error);
        }
Beispiel #8
0
        static void RequestSkill(byte[] data, Action5001 action)
        {
            ReqSkill  req = ProtoBufUtils.Deserialize <ReqSkill>(data);
            Character cha = SceneManager.Instance.FindCharacter(req.casterID);

            if (cha == null)
            {
                return;
            }
            SkillHandle handle = new SkillHandle();

            handle.skillID        = req.skillID;
            handle.caster         = cha;
            handle.skillTargetID  = req.targetID;
            handle.autoTargetPos  = req.autoTargetPos;
            handle.targetPos      = req.targetPos.ToVector3();
            handle.skillEndMethod = null;
            SkillHandle.UseSkill(handle);
        }
Beispiel #9
0
    static void OnChgHp(byte[] data)
    {
        Scene scn = SceneSystem.Instance.mCurrentScene;

        if (scn == null)
        {
            return;
        }
        NotifyHPChg msg = ProtoBufUtils.Deserialize <NotifyHPChg>(data);
        Character   cha = scn.GetCharacter(msg.uid);

        if (cha == null)
        {
            return;
        }
        HPChgType hurtType = (HPChgType)msg.chgType;

        cha.headBar.CreateHeadText(hurtType, msg.hp);
    }
    public byte[] BuildHearbeatPackage()
    {
        var         writer   = NetWriter.Instance;
        MessagePack headPack = new MessagePack()
        {
            MsgId     = NetWriter.MsgId,
            ActionId  = 1,
            SessionId = NetWriter.SessionID,
            UserId    = (int)NetWriter.UserID
        };

        byte[] headBytes = ProtoBufUtils.Serialize(headPack);
        writer.SetHeadBuffer(headBytes);
        writer.SetBodyData(new byte[0]);
        var data = writer.PostData();

        NetWriter.resetData();
        return(data);
    }
Beispiel #11
0
        private static ScriptRuntimeScope InitScriptRuntimeScope()
        {
            string runtimePath = MathUtils.RuntimePath ?? MathUtils.RuntimeBinPath;

            AppDomain.CurrentDomain.AppendPrivatePath(ScriptCompiler.ScriptPath);
            bool isFirstRun = _runtimeDomain == null;

            if (!isFirstRun && _settupInfo.ModelChangedBefore != null)
            {
                _settupInfo.ModelChangedBefore(_runtimeDomain.Scope.ModelAssembly);
            }

            _runtimeDomain = new ScriptRuntimeDomain(typeof(ScriptRuntimeDomain).Name, new[] { _settupInfo.RuntimePath, ScriptCompiler.ScriptPath });

            ScriptDomainContext domainContext = _runtimeDomain.InitDomainContext();

            foreach (var assemblyName in _settupInfo.ReferencedAssemblyNames)
            {
                //排除System的dll
                if (string.IsNullOrEmpty(assemblyName) ||
                    assemblyName.IndexOf(":") == -1)
                {
                    continue;
                }
                string key = Path.GetFileNameWithoutExtension(assemblyName);
                domainContext.LoadAssembly(key, assemblyName);
            }

            var scope = _runtimeDomain.CreateScope(_settupInfo);

            PrintCompiledMessage();
            if (!isFirstRun && _settupInfo.ModelChangedAfter != null)
            {
                _settupInfo.ModelChangedAfter(scope.ModelAssembly);
            }
            else
            {
                ProtoBufUtils.LoadProtobufType(scope.ModelAssembly);
                EntitySchemaSet.LoadAssembly(scope.ModelAssembly);
            }
            return(scope);
        }
Beispiel #12
0
 protected override void SendParameter(NetWriter writer, object userData)
 {
     if (isCustom)
     {
         //自定对象参数格式
         Request1001Pack requestPack = new Request1001Pack()
         {
             PageIndex = 1,
             PageSize  = 10
         };
         byte[] data = ProtoBufUtils.Serialize(requestPack);
         writer.SetBodyData(data);
     }
     else
     {
         //默认url参数格式
         writer.writeInt32("PageIndex", 1);
         writer.writeInt32("PageSize", 10);
     }
 }
Beispiel #13
0
 private static void SaveTo()
 {
     try
     {
         var client = RedisConnectionPool.Pop();
         try
         {
             byte[] data = ProtoBufUtils.Serialize(_globalSession);
             client.Set(sessionRedisKey, data);
         }
         finally
         {
             RedisConnectionPool.Put(client);
         }
     }
     catch (Exception er)
     {
         TraceLog.WriteError("Save session to redis faild,{0}", er);
     }
 }
Beispiel #14
0
 private static bool SetDict <T>(RedisConnection client, string redisKey, Dictionary <string, T> dataSet)
 {
     byte[] buffer = new byte[0];
     try
     {
         buffer = ProtoBufUtils.Serialize(dataSet);
         if (buffer.Length > 0)
         {
             //先设置为空
             client.Set(redisKey, new byte[0]);
             return(client.Set(redisKey, buffer));
         }
         return(true);
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("Set to key:\"{0}\" protobuf serialize \"{1}\" error:{2}", redisKey, typeof(T).FullName, ex);
         return(false);
     }
 }
Beispiel #15
0
        /// <summary>
        /// 放到Redsi中
        /// </summary>
        /// <param name="statement"></param>
        public static bool Put(SqlStatement statement)
        {
            bool result = false;

            RedisManager.Process(client =>
            {
                try
                {
                    string key   = GetStatementKey(statement.IdentityID);
                    byte[] value = ProtoBufUtils.Serialize(statement);
                    client.ZAdd(key, value);
                    result = true;
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("Sql statement put to redis error:{0}\r\n{1}", ex, JsonUtils.SerializeCustom(statement));
                }
            });
            return(result);
        }
Beispiel #16
0
        /// <summary>
        /// UserAchievementCache
        /// </summary>
        public static void DoUserAchievementCache()
        {
            var achieveSet = new PersonalCacheStruct <UserAchievementCache>();

            TraceLog.WriteInfo("Do UserAchievementCache table start...");
            int count = 0;

            try
            {
                var    dbProvider = DbConnectionProvider.CreateDbProvider(DbConfig.MERGE);
                string sql        = "SELECT UserID,AchievementList FROM UserAchievementCache";
                using (IDataReader reader = dbProvider.ExecuteReader(CommandType.Text, sql))
                {
                    while (reader.Read())
                    {
                        UserAchievementCache achievecache = new UserAchievementCache()
                        {
                            UserID = reader["UserID"].ToInt()
                        };

                        var bytes = reader.GetValue(1) as byte[];
                        achievecache.AchievementList = (CacheList <AchievementData>)ProtoBufUtils.Deserialize(bytes, typeof(CacheList <AchievementData>));

                        if (achieveSet.FindKey(achievecache.UserID.ToString()) == null)
                        {
                            //achieveSet.Add(achievecache);
                            count++;
                        }
                    }
                    //achieveSet.Update();
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Do UserAchievementCache table error Exception: {0} .", ex);
                return;
            }


            TraceLog.WriteInfo("Do UserAchievementCache table successful : {0} .", count);
        }
Beispiel #17
0
        /// <summary>
        /// 定义byte[]格式:headLength + headBytes + contentBytes
        /// </summary>
        /// <returns></returns>
        private MessagePack ReadMessageHead(byte[] data, out byte[] content)
        {
            Console.WriteLine("CustomActionDispatcher::ReadMessageHead");
            MessagePack headPack = null;

            content = new byte[0];
            try
            {
                //解头部(解之前当然还需要对byte[]解密,这里跳过这步)
                int    pos          = 0;
                byte[] headLenBytes = new byte[4];
                Buffer.BlockCopy(data, pos, headLenBytes, 0, headLenBytes.Length);
                pos += headLenBytes.Length;
                int headSize = BitConverter.ToInt32(headLenBytes, 0);
                if (headSize < data.Length)
                {
                    byte[] headBytes = new byte[headSize];
                    Buffer.BlockCopy(data, pos, headBytes, 0, headBytes.Length);
                    pos     += headBytes.Length;
                    headPack = ProtoBufUtils.Deserialize <MessagePack>(headBytes);

                    //解消息的内容
                    if (data.Length > pos)
                    {
                        int len = data.Length - pos;
                        content = new byte[len];
                        Buffer.BlockCopy(data, pos, content, 0, content.Length);
                        //内容数据放到具体Action业务上处理
                    }
                }
                else
                {
                    //不支持的数据格式
                }
            }
            catch (Exception ex)
            {
                //不支持的数据格式
            }
            return(headPack);
        }
        public override void WriteResponse(BaseGameResponse response)
        {
            SetResponseHead();
            byte[] headBytes    = ProtoBufUtils.Serialize(_responseHead);
            byte[] contentBytes = BuildResponsePack();
            byte[] buffer       = null;
            if (contentBytes == null || contentBytes.Length == 0)
            {
                buffer = BufferUtils.AppendHeadBytes(headBytes);
            }
            else
            {
                buffer = BufferUtils.MergeBytes(
                    BufferUtils.AppendHeadBytes(headBytes),
                    contentBytes
                    );
            }
            //需要对字节数据加密处理,这里跳过

            response.BinaryWrite(buffer);
        }
Beispiel #19
0
        public static byte[] PackCastPackage <T>(int actionId, T obj)
        {
            //Console.WriteLine("Cast to UserId: {0}", session.UserId);
            byte[] head = ProtoBufUtils.Serialize(new PacageCastHead()
            {
                ActionId = actionId
            });
            byte[] body = ProtoBufUtils.Serialize(obj);

            byte[] headLen = BitConverter.GetBytes(head.Length);
            byte[] bodyLen = BitConverter.GetBytes(body.Length);

            byte[] buffer = new byte[headLen.Length + head.Length + bodyLen.Length + body.Length];

            Buffer.BlockCopy(headLen, 0, buffer, 0, headLen.Length);
            Buffer.BlockCopy(head, 0, buffer, headLen.Length, head.Length);
            Buffer.BlockCopy(bodyLen, 0, buffer, headLen.Length + head.Length, bodyLen.Length);
            Buffer.BlockCopy(body, 0, buffer, headLen.Length + head.Length + bodyLen.Length, body.Length);

            return(buffer);
        }
Beispiel #20
0
        public byte[] Serialize <T>(T msgbody)
        {
            if (msgbody == null)
            {
                AppModules.Instance.LogManager.Log.Error("Null: msgbody");
                return(null);
            }
            ResetStrem();
            MsgBody = msgbody;

            if (!MsgHead.SerializeByStream(m_ms))
            {
                AppModules.Instance.LogManager.Log.Error("MsgBase: Serialize");
                return(null);
            }

            ProtoBufUtils.ProtobufSerializeByStream(msgbody, m_ms);
            MsgHead.m_lengh = (uint)m_ms.Length - (uint)MsgHead.Length;
            MsgHead.SerializeByStreamPos(m_ms, 0);
            return(m_ms.ToArray());
        }
Beispiel #21
0
    void NotifyRoomInfo(byte[] data)
    {
        NotifyRoomInfo roomInfo = ProtoBufUtils.Deserialize <NotifyRoomInfo>(data);

        for (int i = 0; i < roomInfo.Players.Count; ++i)
        {
            RoomPlayerInfo roomPlayerInfo = roomInfo.Players[i];
            if (roomPlayerInfo == null)
            {
                continue;
            }
            texPlayerNames[i].text = roomPlayerInfo.Name;
            playerIDs[i]           = roomPlayerInfo.UserID;
            ++playerCount;
        }
        restTime = roomInfo.RestTime;
        endTime  = Time.realtimeSinceStartup + roomInfo.RestTime;

        mainMenuRoot.SetActive(false);
        matchRoot.SetActive(true);
    }
Beispiel #22
0
    private void OnLoginResponse(byte[] res)
    {
        LoginRes response = ProtoBufUtils.Deserialize <LoginRes>(res);

        PlayerData.AccountId = response.accountId;
        int stat = response.code.status;

        if (stat == 0)
        {
            MUIMgr.Instance.OpenUI("Systems/CharacterSelectSystem");
            if (rem)
            {
                PlayerPrefs.SetString("username", username.text); //本地持久化储存 基于string类型 储存到硬盘 键值对
                PlayerPrefs.SetString("password", password.text); //本地持久化储存 基于string类型 储存到硬盘 键值对
            }
        }
        else if (stat == 1)
        {
            Debug.LogError("登录失败了呢");
        }
    }
Beispiel #23
0
 protected override void SendParameter(NetWriter writer, ActionParam actionParam)
 {
     if (actionParam.HasValue)
     {
         //自定对象参数格式
         isCustom = true;
         Request1001Pack requestPack = actionParam.GetValue <Request1001Pack>();
         byte[]          data        = ProtoBufUtils.Serialize(requestPack);
         writer.SetBodyData(data);
     }
     else
     {
         isCustom = false;
         //默认url参数格式
         actionParam.Foreach((k, v) =>
         {
             writer.writeString(k, v.ToString());
             return(true);
         });
     }
 }
Beispiel #24
0
 private static void OnModelChangeAtfer(Assembly assembly)
 {
     if (assembly == null)
     {
         return;
     }
     try
     {
         ProtoBufUtils.Initialize();
         ProtoBufUtils.LoadProtobufType(assembly);
         EntitySchemaSet.LoadAssembly(assembly);
         Language.Reset();
         CacheFactory.ResetCache();
         TraceLog.ReleaseWrite("Update Model script success.");
         Interlocked.Exchange(ref _isRunning, 1);
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("OnModelChangeAtfer error:{0}", ex);
     }
 }
Beispiel #25
0
 /// <summary>
 /// 生成CSharp脚本程序集
 /// </summary>
 private static Assembly GenerateCsharpScriptAssembly(string name, string[] fileNames, string assemblyName, FileWatcherInfo watcherInfo)
 {
     if (fileNames.Length > 0)
     {
         var refAssemblies = _referencedAssemblies.ToList();
         foreach (var refKey in watcherInfo.ReferenceKeys)
         {
             string assmPath = _watcherDict[refKey].AssemblyOutPath;
             if (!string.IsNullOrEmpty(assmPath))
             {
                 refAssemblies.Add(assmPath);
             }
         }
         bool inMemory = watcherInfo.IsInMemory;
         if (name == ModelDirName)
         {
             string pathToAssembly;
             var    assm = ScriptCompiler.InjectionCompile(fileNames, refAssemblies.ToArray(), assemblyName, _scriptIsDebug, inMemory, out pathToAssembly);
             watcherInfo.AssemblyOutPath = pathToAssembly;
             //load parent class propertys.
             if (assm != null)
             {
                 ProtoBufUtils.LoadProtobufType(assm);
                 if (watcherInfo.Assembly == null)
                 {
                     //first
                     EntitySchemaSet.LoadAssembly(assm);
                 }
             }
             return(assm);
         }
         var result = ScriptCompiler.Compile(fileNames, refAssemblies.ToArray(), assemblyName, _scriptIsDebug, inMemory, ScriptCompiler.ScriptAssemblyTemp);
         if (result != null)
         {
             watcherInfo.AssemblyOutPath = result.PathToAssembly;
             return(result.CompiledAssembly);
         }
     }
     return(null);
 }
    public bool TryParse(byte[] data, out PackageHead head, out byte[] bodyBytes)
    {
        bodyBytes = null;
        head      = null;
        int pos = 0;

        if (data == null || data.Length == 0)
        {
            return(false);
        }
        int headSize = GetInt(data, ref pos);

        byte[] headBytes = new byte[headSize];
        Buffer.BlockCopy(data, pos, headBytes, 0, headBytes.Length);
        pos += headSize;
        ResponsePack resPack = ProtoBufUtils.Deserialize <ResponsePack>(headBytes);

        head             = new PackageHead();
        head.StatusCode  = resPack.ErrorCode;
        head.MsgId       = resPack.MsgId;
        head.Description = resPack.ErrorInfo;
        head.ActionId    = resPack.ActionId;
        head.StrTime     = resPack.St;

        int bodyLen = data.Length - pos;

        if (bodyLen > 0)
        {
            bodyBytes = new byte[bodyLen];
            Buffer.BlockCopy(data, pos, bodyBytes, 0, bodyLen);
        }
        else
        {
            bodyBytes = new byte[0];
        }

        //UnityEngine.Debug.Log(string.Format("ActionId:{0}, ErrorCode:{1}, len:{2}", resPack.ActionId, resPack.ErrorCode, bodyBytes.Length));

        return(true);
    }
Beispiel #27
0
        /// <summary>
        /// Send to queue pool
        /// </summary>
        /// <param name="entityList"></param>
        public static void Send(AbstractEntity[] entityList)
        {
            string key = "";

            try
            {
                if (entityList == null || entityList.Length == 0)
                {
                    return;
                }
                var groupList = entityList.GroupBy(t => t.GetIdentityId());
                foreach (var g in groupList)
                {
                    var      valueList  = g.ToList();
                    byte[][] keyBytes   = new byte[valueList.Count][];
                    byte[][] valueBytes = new byte[valueList.Count][];
                    string   queueKey   = GetRedisSyncQueueKey(g.Key);
                    byte[]   idBytes    = BufferUtils.GetBytes(g.Key);

                    int index = 0;
                    foreach (var entity in valueList)
                    {
                        key             = string.Format("{0}_{1}", entity.GetType().FullName, entity.GetKeyCode());
                        keyBytes[index] = RedisConnectionPool.ToByteKey(key);
                        byte[] stateBytes = BufferUtils.GetBytes(entity.IsDelete ? 1 : 0);
                        valueBytes[index] = BufferUtils.MergeBytes(
                            BufferUtils.GetBytes(idBytes.Length + stateBytes.Length),
                            idBytes,
                            stateBytes,
                            ProtoBufUtils.Serialize(entity));
                        index++;
                    }
                    RedisConnectionPool.Process(client => client.HMSet(queueKey, keyBytes, valueBytes));
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Post changed key:{0} error:{1}", key, ex);
            }
        }
Beispiel #28
0
 private object DeserializeBinaryObject(SchemaTable schemaTable, AbstractEntity entity, object value, SchemaColumn fieldAttr, string columnName)
 {
     try
     {
         if (value is byte[])
         {
             byte[] buffer = value as byte[];
             return(ProtoBufUtils.Deserialize(buffer, fieldAttr.ColumnType));
         }
         throw new Exception("value is not byte[] type.");
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("Table:{0} key:{1} column:{2} deserialize binary error:byte[] to {3}\r\nException:{4}",
                             schemaTable.EntityName,
                             entity.GetKeyCode(),
                             columnName,
                             fieldAttr.ColumnType.FullName,
                             ex);
     }
     return(null);
 }
Beispiel #29
0
        /// <summary>
        /// get entity keys
        /// </summary>
        /// <param name="min"></param>
        /// <param name="max"></param>
        /// <returns></returns>
        public List <KeyValuePair <string, byte[]> > GetKeys(int min = 0, int max = 0)
        {
            if (max == 0)
            {
                max = int.MaxValue;
            }
            var    list = new List <KeyValuePair <string, byte[]> >();
            string key  = GlobalChangeKey;

            RedisManager.Process(client =>
            {
                string setId = key + "_temp";
                try
                {
                    if (!client.ContainsKey(setId) && client.ContainsKey(key))
                    {
                        client.Rename(key, setId);
                    }
                    byte[][] buffers = client.ZRange(setId, min, max);
                    if (buffers == null || buffers.Length == 0)
                    {
                        client.Remove(setId);
                        return;
                    }

                    foreach (var buffer in buffers)
                    {
                        list.Add(ProtoBufUtils.Deserialize <KeyValuePair <string, byte[]> >(buffer));
                        client.ZRemove(setId, buffer);
                    }
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("Entity change key Pop setId:{0} error:{1}", setId, ex);
                }
            });

            return(list);
        }
Beispiel #30
0
        /// <summary>
        /// 从Redis队列中取出Sql命令
        /// </summary>
        /// <param name="keyIndex">Redis队列的Index,默认从0开始</param>
        /// <param name="min"></param>
        /// <param name="max">从队列取的最大值,0为不限制</param>
        /// <returns></returns>
        public static List <SqlStatement> Pop(int keyIndex = 0, int min = 0, int max = 0)
        {
            if (max == 0)
            {
                max = int.MaxValue;
            }
            List <SqlStatement> list = new List <SqlStatement>();
            string key = GetKey(keyIndex);

            RedisManager.Process(client =>
            {
                string setId = key + "_temp";
                try
                {
                    if (!client.ContainsKey(setId) && client.ContainsKey(key))
                    {
                        client.Rename(key, setId);
                    }
                    byte[][] buffers = client.ZRange(setId, min, max);
                    if (buffers == null || buffers.Length == 0)
                    {
                        client.Remove(setId);
                        return;
                    }

                    foreach (var buffer in buffers)
                    {
                        list.Add(ProtoBufUtils.Deserialize <SqlStatement>(buffer));
                        client.ZRemove(setId, buffer);
                    }
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("SqlStatement Pop setId:{0} error:{1}", setId, ex);
                }
            });

            return(list);
        }