Пример #1
0
        public void Execute()
        {
            var data         = CacheSet.PvpTitleTable.GetAllData();
            var highestTitle = data[data.Count - 1];
            int maxScore     = highestTitle.TitleMinScore;
            var players      = CacheSet.PlayerSinglePvpCache.FindAll();

            foreach (var player in players)
            {
                if (player.SinglePvpScore > maxScore)
                {
                    player.DeductedScore += player.SinglePvpScore - maxScore;
                    player.SinglePvpScore = maxScore;
                }
            }
            if (PVPLogic.Year == 0 || PVPLogic.Year != DateTime.UtcNow.Year)
            {
                PVPLogic.SeasonId = 1;
                PVPLogic.Year     = DateTime.UtcNow.Year;
                RedisConnectionPool.GetClient().Set(GameConsts.Pvp.PvpSeasonOfYearKey, PVPLogic.Year);
            }
            else
            {
                PVPLogic.SeasonId += 1;
            }
            RedisConnectionPool.GetClient().Set(GameConsts.Pvp.PvpSeasonCountKey, PVPLogic.SeasonId);
        }
Пример #2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="token"></param>
        /// <returns></returns>
        public static UserToken GetUserToken(string token)
        {
            UserToken userToken = null;
            string    redisKey  = string.Format("{0}@{1}", AccountServerToken, token);

            if (!string.IsNullOrEmpty(RedisHost) && RedisConnected)
            {
                //use redis cache.
                RedisConnectionPool.Process(client =>
                {
                    var val   = client.Get(redisKey);
                    userToken = val == null || val.Length == 0 ? new UserToken() : MathUtils.ParseJson <UserToken>(Encoding.UTF8.GetString(val));
                });
                return(userToken);
            }
            if (HttpContext.Current != null && HttpContext.Current.Cache != null)
            {
                userToken = (UserToken)HttpContext.Current.Cache[redisKey];
            }
            if (Equals(userToken, null) && userTokenCache.ContainsKey(redisKey))
            {
                userToken = (UserToken)userTokenCache[redisKey];
            }
            return(userToken);
        }
Пример #3
0
        /// <summary>
        /// 放到消息队列池中
        /// </summary>
        /// <param name="statement"></param>
        public static bool Put(SqlStatement statement)
        {
            bool result = false;

            try
            {
                if (!IsUseSyncQueue)
                {
                    return(false);
                }
                string tableName = statement.Table;
                string key       = GetSqlQueueKey(statement.IdentityID);
                byte[] value     = ProtoBufUtils.Serialize(statement);
                RedisConnectionPool.Process(client =>
                {
                    client.ZAdd(key, DateTime.Now.Ticks, value);
                    ProfileManager.PostSqlOfMessageQueueTimes(tableName, 1);
                });
                result = true;
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Sql update queue write error:{0}\r\n{1}", ex, JsonUtils.SerializeCustom(statement));
            }

            return(result);
        }
Пример #4
0
        /// <summary>
        /// 创建链接池管理对象
        /// IP地址中可以加入auth验证   password@ip:port
        /// </summary>
        private static void CreateManager()
        {
            {
                //IPEndPoint result = null;
                var host = ConfigHelper.RedisEndPoint.Trim();
                if (host.IndexOf("@") > -1)
                {
                    var hostParts = host.Split('@');
                    _pwd = hostParts[0];
                    var ip = hostParts[1].Split(':');

                    _host = ip[0];
                    _port = int.Parse(ip[1]);

                    //result = new IPEndPoint(IPAddress.Parse(ip[0]), int.Parse(ip[1]));
                }
                else
                {
                    var hostParts = host.Split(':');
                    _host = hostParts[0];
                    _port = int.Parse(hostParts[1]);
                    //result = new IPEndPoint(IPAddress.Parse(hostParts[0]), int.Parse(hostParts[1]));
                }
                //_IP = result;
                _PoolMaxSize = ConfigHelper.PoolMaxSize;
            }

            //_prcm = new RedisConnectionPool(_IP, _PoolMaxSize);
            _prcm = new RedisConnectionPool(_host, _port, _PoolMaxSize);
        }
 private static void OnModelChangeAtfer(Assembly assembly)
 {
     if (assembly == null)
     {
         return;
     }
     try
     {
         TypeAccessor.Init();
         RedisConnectionPool.Initialize(_setting.Serializer);
         DbConnectionProvider.Initialize();
         ProtoBufUtils.Initialize();
         ProtoBufUtils.LoadProtobufType(assembly);
         EntitySchemaSet.Init();
         EntitySchemaSet.LoadAssembly(assembly);
         EntitySchemaSet.InitSchema(typeof(SensitiveWord));
         Language.Reset();
         CacheFactory.ResetCache();
         TraceLog.ReleaseWrite("Update Model script success.");
         IsRunning = true;
     }
     catch (Exception ex)
     {
         TraceLog.WriteError("OnModelChangeAtfer error:{0}", ex);
     }
 }
Пример #6
0
        /// <summary>
        /// 以同步的方式更新Entity
        /// </summary>
        /// <param name="entityList"></param>
        public static bool SendSync(IEnumerable <AbstractEntity> entityList)
        {
            var keyList   = new List <byte[]>();
            var valueList = new List <byte[]>();

            foreach (var entity in entityList)
            {
                if (entity == null)
                {
                    continue;
                }
                entity.TempTimeModify = MathUtils.Now;
                string key       = GetQueueFormatKey(entity);
                var    keyValues = key.Split('_', '|');
                int    id        = AbstractEntity.DecodeKeyCode(keyValues[1]).ToInt();
                string keyCode   = keyValues[2];
                string redisKey  = string.Format("{0}_{1}", keyValues[0], keyCode);
                byte[] idBytes   = BufferUtils.GetBytes(id);
                var    keyBytes  = RedisConnectionPool.ToByteKey(redisKey);
                byte[] entityBytes;
                bool   isDelete = entity.IsDelete;
                entityBytes = _serializer.Serialize(entity);
                //modify resean: set unchange status.
                entity.Reset();

                byte[] stateBytes = BufferUtils.GetBytes(isDelete ? 1 : 0);
                byte[] values     = BufferUtils.MergeBytes(BufferUtils.GetBytes(idBytes.Length + stateBytes.Length), idBytes, stateBytes, entityBytes);
                keyList.Add(keyBytes);
                valueList.Add(values);
            }
            return(ProcessRedisSyncQueue(string.Empty, keyList.ToArray(), valueList.ToArray()));
        }
Пример #7
0
        public void RedisListTest()
        {
            var watch = Stopwatch.StartNew();
            var keys  = new List <string> {
                "__List:1000:1", "__List:1000:2"
            };
            var           script    = @"
local result={}
local index = 0
local len = table.getn(KEYS)
for i=1, len do
    local key = KEYS[i]
    local values = redis.call('lrange',key,0,-1)
    local l = table.getn(values)
    result[i] = table.concat(values,',')
end
return result
";
            List <string> valueList = null;

            RedisConnectionPool.Process(c =>
            {
                valueList = c.ExecLuaAsList(script, keys.ToArray(), new string[0]);
            });
            Trace.WriteLine("value count:" + valueList.Count + "\r\n" + string.Join("\r\n", valueList));

            WaitEnd(watch);
        }
Пример #8
0
        public void CheckCompletedTest()
        {
            var keys = new[] { "testkey1", "testkey2" };
            var vals = new[] { "1", "2" };

            RedisConnectionPool.SetExpire(keys, vals, 300);
            RedisConnectionPool.Process(c =>
            {
                var values = new List <string>();
                using (var p = c.CreatePipeline())
                {
                    foreach (var key in keys)
                    {
                        string k = key;
                        p.QueueCommand(cli => cli.Get <string>(k), v =>
                        {
                            values.Add(v);
                        });
                    }
                    p.Flush();
                }
                Trace.WriteLine(string.Join(",", values));
            });
            var watch = Stopwatch.StartNew();
            var data  = ShareCacheStruct.Get <ChildData>(1);

            data.Age++;
            bool result = CacheFactory.CheckCompleted();

            Trace.WriteLine("Queue result:" + result);
            WaitEnd(watch);
        }
Пример #9
0
        public void ReUsePoolConnection_test()
        {
            var host = "127.0.0.1";
            var port = 6379;

            var connections = new List <RedisConnection>()
            {
                RedisConnectionPool.GetConnection(host, port)
                , RedisConnectionPool.GetConnection(host, port)
                , RedisConnectionPool.GetConnection(host, port)
                , RedisConnectionPool.GetConnection(host, port)
                , RedisConnectionPool.GetConnection(host, port)
                , RedisConnectionPool.GetConnection(host, port)
            };

            foreach (var conn in connections)
            {
                conn.OnConnectionReleased();
            }

            Assert.True(RedisConnectionPool.GetPoolSizeForHost(host, port).Equals(6));

            var newConn = RedisConnectionPool.GetConnection(host, port);

            Assert.True(connections.Any(c => c.Id.Equals(newConn.Id)));
        }
Пример #10
0
 public void FindRedis()
 {
     RedisConnectionPool.Process(cli =>
     {
         /*
          * var watch = Stopwatch.StartNew();
          * key = "$FrameworkUnitTest.Cache.Model.UserKeyData";//"$FrameworkUnitTest.Cache.Model.QuestProcess";//
          * //var keys = cli.HKeys(key);
          * //Trace.WriteLine("load time:" + watch.ElapsedMilliseconds + "ms." + "keys:" + keys.Length);
          * //var valueBytes = cli.HGet(key, keys);
          * //Trace.WriteLine("load time:" + watch.ElapsedMilliseconds + "ms." + "vals:" + valueBytes.Length);
          * byte[] suBytes = Encoding.Default.GetBytes("1380000");
          * var script = @"
          *  local userId = KEYS[2]
          *  local key = KEYS[1]
          *  local keyBytes = redis.call('HKeys',key)
          *  print('keys:'.. table.getn(keyBytes))
          *  local valueBytes = {}
          *  for i,k in pairs(keyBytes) do
          *      if string.find(k, userId) then
          *          local val = redis.call('HGet',key, k)
          *          table.insert(valueBytes, val)
          *      end
          *  end
          *  return valueBytes
          * ";
          * var keybytes = Encoding.Default.GetBytes(key);
          * var valueBytes = cli.Eval(script, 2, keybytes, suBytes);
          * Trace.WriteLine("load time:" + watch.ElapsedMilliseconds + "ms." + "vals:" + (valueBytes.Length > 0 && valueBytes[0] != null ? Encoding.Default.GetString(valueBytes[0]) + "count:" + valueBytes.Length : "count:" + valueBytes.Length));
          *
          */
     });
 }
Пример #11
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="assembly"></param>
        public static void Init(Assembly assembly)
        {
            var htype = Type.GetType("ZyGames.Framework.Game.Sns.Service.IHandler`1", false, true);
            var types = assembly.GetTypes();

            foreach (var type in types)
            {
                if (type.GetInterfaces().Select(t => t.Name).Contains(htype.Name))
                {
                    handlerTypes[type.Name] = type;
                }
            }
            if (!string.IsNullOrEmpty(RedisHost))
            {
                try
                {
                    //use redis cache.
                    RedisConnectionPool.Initialize(new RedisPoolSetting()
                    {
                        Host = RedisHost, DbIndex = RedisDb
                    }, new JsonCacheSerializer(Encoding.UTF8));
                    RedisConnected = true;
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("Redis Initialize error:{0}", ex);
                }
            }
        }
Пример #12
0
        /// <summary>
        /// Get entity from redis, but not surported mutil key of entity.
        /// </summary>
        /// <param name="personalId"></param>
        /// <param name="types"></param>
        /// <returns></returns>
        public static object[] Load(string personalId, params Type[] types)
        {
            personalId = AbstractEntity.EncodeKeyCode(personalId);
            var param = types.Where(t => !CacheFactory.ContainEntityKey(t, personalId)).ToArray();

            if (param.Length == 0)
            {
                return(null);
            }

            var result = RedisConnectionPool.GetAllEntity(personalId, param);

            foreach (var t in result)
            {
                var entity = t as AbstractEntity;
                if (entity == null)
                {
                    continue;
                }
                CacheItemSet itemSet;
                if (CacheFactory.AddOrUpdateEntity(entity, out itemSet))
                {
                    itemSet.OnLoadSuccess();
                }
            }
            return(result);
        }
Пример #13
0
 private static void LoadUnLineData()
 {
     try
     {
         RedisConnectionPool.ProcessReadOnly(client =>
         {
             byte[] data = client.Get(sessionRedisKey) ?? new byte[0];
             if (data.Length == 0)
             {
                 return;
             }
             var temp = ProtoBufUtils.Deserialize <ConcurrentDictionary <Guid, GameSession> >(data);
             if (temp != null)
             {
                 var paris = temp.Where(p =>
                 {
                     p.Value.UserId = 0;//reset userid
                     return(!p.Value.CheckExpired());
                 }).ToArray();
                 _globalSession = new ConcurrentDictionary <Guid, GameSession>(paris);
             }
         });
     }
     catch (Exception er)
     {
         TraceLog.WriteError("Load GameSession from redis faild,{0}", er);
     }
 }
        /// <summary>
        ///
        /// </summary>
        /// <param name="personalId"></param>
        /// <param name="dataList"></param>
        /// <returns></returns>
        protected bool TryLoadFromRedis(out List <T> dataList, string personalId = null)
        {
            string      redisKey = string.IsNullOrEmpty(personalId) ? containerKey : string.Format("{0}_{1}", containerKey, personalId);
            SchemaTable schema   = EntitySchemaSet.Get <T>();

            return(RedisConnectionPool.TryGetEntity(redisKey, schema, out dataList));
        }
Пример #15
0
        /// <summary>
        /// Check queue is completed.
        /// </summary>
        /// <param name="keyIndex"></param>
        /// <returns></returns>
        public static bool CheckCompleted(int keyIndex = 0)
        {
            var keys = new string[DataSyncQueueManager.SyncQueueCount];

            if (keys.Length == 1)
            {
                keys[0] = (DataSyncQueueManager.RedisSyncQueueKey);
            }
            else
            {
                for (int i = 0; i < keys.Length; i++)
                {
                    keys[i] = string.Format("{0}:{1}", DataSyncQueueManager.RedisSyncQueueKey, i);
                }
            }

            bool result = false;

            RedisConnectionPool.ProcessReadOnly(client =>
            {
                var values = client.MGet(keys);
                result     = values == null || values.Length == 0 || values.Any(t => t == null);
            });
            return(result);
        }
Пример #16
0
        public void ReLoadRedis()
        {
            try
            {
                RedisConfig = RedisSettingFactory.Load();

                ICacheSerializer serializer = RedisConfig.Serializer == StorageMode.Protobuf
                    ? (ICacheSerializer) new ProtobufCacheSerializer()
                    : new JsonCacheSerializer(Encoding.UTF8);

                RedisConnectionPool.Initialize(new RedisPoolSetting()
                {
                    Host             = RedisConfig.Host,
                    ReadOnlyHost     = RedisConfig.Host,
                    MaxWritePoolSize = 2,
                    MaxReadPoolSize  = 2,
                    DbIndex          = RedisConfig.Db
                }, serializer);

                var _redisSection = ConfigManager.Configger.GetFirstOrAddConfig <RedisSection>();
                if (_redisSection == null)
                {
                }
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("ReLoadRedis error:{0}", ex);
            }
        }
Пример #17
0
        public bool TrySearchRedisKeys(out List <string> keys, int top = 0)
        {
            string pattern = "*";

            if (_redisSearchPatternList.Count == 1)
            {
                pattern = _redisSearchPatternList[0];
            }
            List <string> list   = null;
            bool          result = false;

            RedisConnectionPool.ProcessReadOnly(client =>
            {
                if (top > 0)
                {
                    list = _redisSearchPatternList.Count > 1
                    ? SearchKeys(client, _redisSearchPatternList).OrderBy(k => k).Take(top).ToList()
                    : client.SearchKeys(pattern).OrderBy(k => k).Take(top).ToList();
                }
                else
                {
                    list = _redisSearchPatternList.Count > 1
                    ? SearchKeys(client, _redisSearchPatternList).OrderBy(k => k).ToList()
                    : client.SearchKeys(pattern).OrderBy(k => k).ToList();
                }
                result = true;
            });
            keys = list;
            return(result);
        }
Пример #18
0
        public static void TestCheckSqlSyncQueue(int identity)
        {
            if (Interlocked.Exchange(ref _isWatchWorking[identity], 1) == 0)
            {
                try
                {
                    string   queueKey   = GetSqlQueueKey(identity);
                    string   workingKey = queueKey + "_temp";
                    bool     result;
                    byte[][] bufferBytes = new byte[0][];
                    do
                    {
                        result = false;
                        RedisConnectionPool.ProcessReadOnly(client =>
                        {
                            bool hasWorkingQueue    = client.ContainsKey(workingKey);
                            bool hasNewWorkingQueue = client.ContainsKey(queueKey);

                            if (!hasWorkingQueue && !hasNewWorkingQueue)
                            {
                                return;
                            }
                            if (!hasWorkingQueue)
                            {
                                try
                                {
                                    client.Rename(queueKey, workingKey);
                                }
                                catch { }
                            }

                            bufferBytes = client.ZRange(workingKey, 0, sqlSyncPackSize);
                            if (bufferBytes.Length > 0)
                            {
                                client.ZRemRangeByRank(workingKey, 0, sqlSyncPackSize);
                                result = true;
                            }
                            else
                            {
                                client.Remove(workingKey);
                            }
                        });
                        if (!result)
                        {
                            break;
                        }
                        DoProcessSqlSyncQueue(workingKey, bufferBytes);
                    } while (true);
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("OnCheckSqlSyncQueue error:{0}", ex);
                }
                finally
                {
                    Interlocked.Exchange(ref _isWatchWorking[identity], 0);
                }
            }
        }
Пример #19
0
        /// <summary>
        /// Send entity to db saved.
        /// </summary>
        /// <param name="postColumnFunc"></param>
        /// <param name="getPropertyFunc"></param>
        /// <param name="entityList"></param>
        public static void SendToDb <T>(EntityPropertyGetFunc <T> getPropertyFunc, EnttiyPostColumnFunc <T> postColumnFunc, params T[] entityList) where T : ISqlEntity
        {
            string key = "";

            try
            {
                if (entityList == null || entityList.Length == 0)
                {
                    return;
                }
                var sender    = new SqlDataSender(false);
                var groupList = entityList.GroupBy(t => t.GetMessageQueueId());
                var sqlList   = new List <KeyValuePair <string, KeyValuePair <byte[], long> > >();

                foreach (var g in groupList)
                {
                    key = g.Key.ToString();
                    var valueList = g.ToList();

                    foreach (var entity in valueList)
                    {
                        if (entity == null)
                        {
                            continue;
                        }

                        SqlStatement statement = sender.GenerateSqlQueue <T>(entity, getPropertyFunc, postColumnFunc);
                        if (statement == null)
                        {
                            throw new Exception(string.Format("Generate sql of \"{0}\" entity error", entity.GetType().FullName));
                        }

                        var    sqlValueBytes = ProtoBufUtils.Serialize(statement);
                        string sqlQueueKey   = SqlStatementManager.GetSqlQueueKey(statement.IdentityID);
                        sqlList.Add(new KeyValuePair <string, KeyValuePair <byte[], long> >(sqlQueueKey,
                                                                                            new KeyValuePair <byte[], long>(sqlValueBytes, DateTime.Now.Ticks)));
                    }
                }
                RedisConnectionPool.ProcessPipeline(p =>
                {
                    bool hasPost     = false;
                    var groupSqlList = sqlList.GroupBy(t => t.Key);
                    foreach (var g in groupSqlList)
                    {
                        var pairs = g.Select(t => t.Value).ToList();
                        p.QueueCommand(client => ((RedisClient)client).ZAdd(g.Key, pairs));
                        hasPost = true;
                    }
                    if (hasPost)
                    {
                        p.Flush();
                    }
                });
            }
            catch (Exception ex)
            {
                TraceLog.WriteError("Send To Db key:{0} error:{1}", key, ex);
            }
        }
Пример #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="key"></param>
        /// <param name="userToken"></param>
        public static void SaveToken(string key, UserToken userToken)
        {
            string userKey  = string.Format("{0}:{1}", AccountServerToken, userToken.UserId);
            string redisKey = string.Format("{0}@{1}", AccountServerToken, key);

            if (!string.IsNullOrEmpty(RedisHost) && RedisConnected)
            {
                try
                {
                    string script = @"
local redisKey = KEYS[1]
local userKey = KEYS[2]
local key = KEYS[3]
local timeout = ARGV[1]
local val = ARGV[2]
local oldToken = redis.call('Get', userKey)
if oldToken and oldToken ~= nil then
    local k =  '__AccountToken@'..oldToken
    redis.call('del', k)
end
redis.call('Set', redisKey, val, 'EX', timeout)
redis.call('Set', userKey, key, 'EX', timeout)
return 0
";
                    //use redis cache.
                    RedisConnectionPool.Process(client =>
                    {
                        int timeout = (int)(userToken.ExpireTime - DateTime.Now).TotalSeconds;
                        client.ExecLuaAsInt(script, new[] { redisKey, userKey, key }, new[] { timeout.ToString(), MathUtils.ToJson(userToken) });
                    });
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("Save token errror:{0}", ex);
                }
                return;
            }
            if (HttpContext.Current != null && HttpContext.Current.Cache != null)
            {
                var cache    = HttpContext.Current.Cache;
                var oldToken = cache[userKey] as string;
                if (!string.IsNullOrEmpty(oldToken))
                {
                    cache.Remove(string.Format("{0}@{1}", AccountServerToken, oldToken));
                }
                cache[redisKey] = userToken;
                cache[userKey]  = key;
            }
            else
            {
                string oldToken;
                if (userHashCache.TryGetValue(userToken.UserId, out oldToken))
                {
                    UserToken temp;
                    userTokenCache.TryRemove(oldToken, out temp);
                }
                userTokenCache[key] = userToken;
            }
        }
Пример #21
0
 /// <summary>
 /// 生成存储在Redis的Key
 /// </summary>
 /// <param name="type"></param>
 /// <param name="personalKey"></param>
 /// <returns></returns>
 public static string GenerateRedisKey(Type type, string personalKey)
 {
     if (string.IsNullOrEmpty(personalKey))
     {
         return(string.Format("{0}", RedisConnectionPool.EncodeTypeName(type.FullName)));
     }
     return(string.Format("{0}_{1}", RedisConnectionPool.EncodeTypeName(type.FullName), personalKey));
 }
Пример #22
0
 public bool Send <T>(params T[] dataList) where T : AbstractEntity
 {
     if (_sendParam.Schema.CacheType == CacheType.Rank)
     {
         return(RedisConnectionPool.TryUpdateRankEntity(_sendParam.Key, dataList));
     }
     return(RedisConnectionPool.TryUpdateEntity(dataList));
 }
Пример #23
0
        private static string GetEntityTypeFromKey(string key, out string typeName, ref Type type, out string asmName, out bool isEntityType, out string redisKey)
        {
            int index = key.IndexOf(',');
            var arr   = (index > -1 ? key.Substring(0, index) : key).Split('_');

            typeName = arr[0];
            asmName  = index == -1 ? "" : key.Substring(index + 1, key.Length - index - 1);
            string persionKey = string.Empty;
            string entityKey  = string.Empty;

            if (arr.Length > 1)
            {
                entityKey = arr[1];
                var tempArr = entityKey.Split('|');
                if (tempArr.Length > 1)
                {
                    persionKey = tempArr[0];
                    entityKey  = tempArr[1];
                }
            }
            isEntityType = false;
            if (string.IsNullOrEmpty(persionKey))
            {
                isEntityType = true;
                redisKey     = string.Format("{0}_{1}", RedisConnectionPool.EncodeTypeName(typeName), entityKey);
            }
            else
            {
                //私有类型
                redisKey = string.Format("{0}_{1}", RedisConnectionPool.EncodeTypeName(typeName), persionKey);
            }
            string formatString = entityTypeNameFormat;

            if (isEntityType)
            {
                formatString = "{0},{1}";
            }
            if (type == null)
            {
                string entityTypeName = RedisConnectionPool.DecodeTypeName(typeName);
                type = Type.GetType(string.Format(formatString, entityTypeName, asmName), false, true);
                if (Equals(type, null))
                {
                    var enitityAsm = ScriptEngines.GetEntityAssembly();
                    if (enitityAsm != null)
                    {
                        asmName = enitityAsm.GetName().Name;
                        type    = Type.GetType(string.Format(formatString, entityTypeName, asmName), false, true);
                        if (Equals(type, null))
                        {
                            //调试模式下type为空处理
                            type = enitityAsm.GetType(entityTypeName, false, true);
                        }
                    }
                }
            }
            return(entityKey);
        }
Пример #24
0
        private static void OnCheckSqlSyncQueue(object state)
        {
            int identity = (int)state;

            if (Interlocked.CompareExchange(ref _isWatchWorking[identity], 1, 0) == 0)
            {
                try
                {
                    string   queueKey   = GetSqlQueueKey(identity);
                    string   workingKey = queueKey + "_temp";
                    bool     result;
                    byte[][] bufferBytes = new byte[0][];
                    byte[][] valueBytes  = new byte[0][];
                    byte[][] scoreBytes  = new byte[0][];
                    do
                    {
                        result = false;
                        RedisConnectionPool.ProcessReadOnly(client =>
                        {
                            bool hasWorkingQueue    = client.ContainsKey(workingKey);
                            bool hasNewWorkingQueue = client.ContainsKey(queueKey);

                            if (!hasWorkingQueue && !hasNewWorkingQueue)
                            {
                                return;
                            }
                            if (!hasWorkingQueue)
                            {
                                try
                                {
                                    client.Rename(queueKey, workingKey);
                                }
                                catch { }
                            }
                            bufferBytes = GetPackFromQueue(client, workingKey, sqlSyncPackSize);

                            if (bufferBytes.Length > 0)
                            {
                                result = true;
                            }
                        });
                        if (!result)
                        {
                            break;
                        }
                        DoProcessSqlSyncQueue(workingKey, queueKey, bufferBytes);
                    } while (true);
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("OnCheckSqlSyncQueue error:{0}", ex);
                }
                finally
                {
                    Interlocked.Exchange(ref _isWatchWorking[identity], 0);
                }
            }
        }
Пример #25
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)
            {
                return;
            }

            TraceLog.WriteLine("{0} Server is starting...", DateTime.Now.ToString("HH:mm:ss"));
            _setting = setting;
            if (!RedisConnectionPool.Ping("127.0.0.1"))
            {
                string error = string.Format("Error: NIC is not connected or no network.");
                TraceLog.WriteLine(error);
                TraceLog.WriteError(error);
                return;
            }
            RedisConnectionPool.Initialize(_setting.Serializer);
            if (!RedisConnectionPool.CheckConnect())
            {
                string error = string.Format("Error: the redis server is not started.");
                TraceLog.WriteLine(error);
                TraceLog.WriteError(error);
                return;
            }
            TraceLog.WriteLine("{0} Redis server connect successfully.", DateTime.Now.ToString("HH:mm:ss"));

            DbConnectionProvider.Initialize();
            TraceLog.WriteLine("{0} DB server connect successfully.", DateTime.Now.ToString("HH:mm:ss"));

            EntitySchemaSet.CacheGlobalPeriod = _setting.CacheGlobalPeriod;
            EntitySchemaSet.CacheUserPeriod   = _setting.CacheUserPeriod;
            if (_setting.EntityAssembly != null)
            {
                ProtoBufUtils.LoadProtobufType(_setting.EntityAssembly);
                EntitySchemaSet.LoadAssembly(_setting.EntityAssembly);
            }

            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.OnLoaded += OnScriptLoaded;
            ScriptEngines.Initialize();
            Language.SetLang();
            CacheFactory.Initialize(cacheSetting, _setting.Serializer);
            EntitySchemaSet.StartCheckTableTimer();
            Global = new ContextCacheSet <CacheItem>("__gameenvironment_global");
        }
Пример #26
0
        /// <summary>
        /// 获取Container中存在的Cache,不重新创建
        /// </summary>
        /// <param name="redisKey"></param>
        /// <param name="itemPair"></param>
        /// <param name="periodTime"></param>
        /// <returns></returns>
        public static bool TryGetContainerCacheItem(string redisKey, out KeyValuePair <string, CacheItemSet> itemPair, int periodTime = 0)
        {
            itemPair = default(KeyValuePair <string, CacheItemSet>);
            CacheItemSet cacheItem;

            string[] keys = (redisKey ?? "").Split('_');
            if (keys.Length == 2 && !string.IsNullOrEmpty(keys[0]))
            {
                CacheContainer container = null;
                string         typeName  = RedisConnectionPool.DecodeTypeName(keys[0]);
                var            schema    = EntitySchemaSet.Get(typeName);
                periodTime = periodTime > 0 ? periodTime : schema.PeriodTime;
                if (_writePools != null && !_writePools.TryGetValue(typeName, out container))
                {
                    _writePools.InitContainer(typeName);
                    _writePools.TryGetValue(typeName, out container);
                }
                if (container == null)
                {
                    return(false);
                }

                string[] childKeys   = keys[1].Split('|');
                string   personalKey = childKeys[0];
                string   entityKey   = childKeys.Length > 1 ? childKeys[1] : "";
                if (schema.CacheType == CacheType.Dictionary)//|| schema.CacheType == CacheType.Entity)
                {
                    var result = container.Collection.TryGetValue(personalKey, out cacheItem);
                    itemPair = new KeyValuePair <string, CacheItemSet>(entityKey, cacheItem);
                    return(result);
                }
                if (schema.CacheType == CacheType.Entity)
                {
                    var result = container.Collection.TryGetValue(entityKey, out cacheItem);
                    itemPair = new KeyValuePair <string, CacheItemSet>(entityKey, cacheItem);
                    return(result);
                }
                if (schema.CacheType == CacheType.Queue)
                {
                    TraceLog.WriteError("Not support CacheType.Queue get cache, key:{0}.", redisKey);
                }

                ////存在分类id与实体主键相同情况, 要优先判断实体主键
                //if (!string.IsNullOrEmpty(personalKey) && container.Collection.TryGetValue(entityKey, out cacheItem))
                //{
                //    itemPair = new KeyValuePair<string, CacheItemSet>(entityKey, cacheItem);
                //    return true;
                //}
                //if (!string.IsNullOrEmpty(personalKey) && container.Collection.TryGetValue(personalKey, out cacheItem))
                //{
                //    itemPair = new KeyValuePair<string, CacheItemSet>(entityKey, cacheItem);
                //    return true;
                //}
            }
            return(false);
        }
Пример #27
0
        /// <summary>
        /// Check to be synchronized queue of redis
        /// </summary>
        /// <param name="state"></param>
        private static void OnCheckRedisSyncQueue(object state)
        {
            int identity = (int)state;

            if (Interlocked.CompareExchange(ref _isRedisSyncWorking[identity], 1, 0) == 0)
            {
                try
                {
                    string   queueKey   = GetRedisSyncQueueKey(identity);
                    string   workingKey = queueKey + "_temp";
                    byte[][] keys       = new byte[0][];
                    byte[][] values     = new byte[0][];
                    RedisConnectionPool.ProcessReadOnly(client =>
                    {
                        bool hasWorkingQueue    = client.HLen(workingKey) > 0;
                        bool hasNewWorkingQueue = client.HLen(queueKey) > 0;

                        if (!hasWorkingQueue && !hasNewWorkingQueue)
                        {
                            return;
                        }
                        if (!hasWorkingQueue)
                        {
                            try
                            {
                                client.Rename(queueKey, workingKey);
                            }
                            catch
                            {
                            }
                        }

                        var keyValuePairs = client.HGetAll(workingKey);
                        if (keyValuePairs != null && keyValuePairs.Length > 0)
                        {
                            keys   = keyValuePairs.Where((buffs, index) => index % 2 == 0).ToArray();
                            values = keyValuePairs.Where((buffs, index) => index % 2 == 1).ToArray();
                            client.Remove(workingKey);
                        }
                    });

                    if (keys != null && keys.Length > 0)
                    {
                        _threadPools.QueueWorkItem(DoProcessRedisSyncQueue, workingKey, keys, values);
                    }
                }
                catch (Exception ex)
                {
                    TraceLog.WriteError("OnCheckRedisSyncQueue error:{0}", ex);
                }
                finally
                {
                    Interlocked.Exchange(ref _isRedisSyncWorking[identity], 0);
                }
            }
        }
Пример #28
0
 public RedisClient(String host, int port = 6379, String password = null, Int32?db = null)
 {
     Host        = host;
     Port        = port;
     Password    = password;
     Db          = db;
     _connection = RedisConnectionPool.GetConnection(host, port, password);
     _connection.Connect();
     _selectDb();
 }
Пример #29
0
        /// <summary>
        /// Check queue is completed.
        /// </summary>
        /// <param name="keyIndex"></param>
        /// <returns></returns>
        public static bool CheckCompleted(int keyIndex = 0)
        {
            bool result = false;

            RedisConnectionPool.ProcessReadOnly(client =>
            {
                result = client.SearchKeys(DataSyncQueueManager.RedisSyncQueueKey + "*").Count == 0;
            });
            return(result);
        }
Пример #30
0
 public RedisClient(RedisHostInfo hostInfo)
 {
     this.Host     = hostInfo.Host;
     this.Port     = hostInfo.Port;
     this.Password = hostInfo.Password;
     this.Db       = hostInfo.Db;
     _connection   = RedisConnectionPool.GetConnection(this.Host, this.Port, this.Password);
     _connection.Connect();
     _selectDb();
 }