feat: initial commit - HJHA game server full source
6 major server modules (PdkFriendServer/GlobalSever/ServerCore/GameModule/GameNetModule) + game logic (GameFix/GameDAL/ServerData) + network layer (NetWorkMessage) + data layer (ObjectModel) + utilities (MrWu/Core/Config/CloudAPI/dll) + adapters (zyxAdapter/base) .NET 8.0 C# solution, 16 projects, 958 source files
This commit is contained in:
62
GameDAL/Backend/BMAdminDal.cs
Normal file
62
GameDAL/Backend/BMAdminDal.cs
Normal file
@ -0,0 +1,62 @@
|
||||
using GameData;
|
||||
using GameDAL.Game;
|
||||
using MrWu.Basic;
|
||||
using MrWu.Debug;
|
||||
using ObjectModel;
|
||||
using ObjectModel.Backend;
|
||||
using Server.DB.Redis;
|
||||
using Server.DB.Sql;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using ObjectModel.User;
|
||||
|
||||
namespace GameDAL.Backend
|
||||
{
|
||||
public static class BMAdminDal
|
||||
{
|
||||
const int DBIdx = 8;
|
||||
public static readonly TimeSpan outT = new TimeSpan(1, 0, 0);
|
||||
|
||||
/// <summary>
|
||||
/// 根据推广标识获取用户
|
||||
/// </summary>
|
||||
/// <param name="platTag"></param>
|
||||
/// <returns></returns>
|
||||
public static BMAdminModel GetBMAdminModelByPlatTag(string platTag)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
|
||||
public static Task<long> GetRedNumAsync(int userid)
|
||||
{
|
||||
return Task.Run(() => GetRedNum(userid));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取玩家红包
|
||||
/// </summary>
|
||||
/// <param name="userid"></param>
|
||||
/// <returns></returns>
|
||||
public static long GetRedNum(int userid)
|
||||
{
|
||||
return 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 给玩家加减红包
|
||||
/// </summary>
|
||||
/// <param name="userid"></param>
|
||||
/// <param name="num">正数加 负数减</param>
|
||||
public static void AddRedNum(int userid, int num)
|
||||
{
|
||||
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
32
GameDAL/Backend/DeskPlayerDal.cs
Normal file
32
GameDAL/Backend/DeskPlayerDal.cs
Normal file
@ -0,0 +1,32 @@
|
||||
using ObjectModel;
|
||||
using ObjectModel.Config;
|
||||
using Server.DB.Redis;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using GameData;
|
||||
|
||||
namespace GameDAL.Backend
|
||||
{
|
||||
public class DeskPlayerDal
|
||||
{
|
||||
/// <summary>
|
||||
/// 获取禁止同桌信息
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetNoDeskPlayer() {
|
||||
return redisManager.GetBiSaidb(ConstClass.NoDeskMatesAllowedDBIdx).StringGet(ConstClass.NoDeskMatesAllowedKey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置禁止同桌信息
|
||||
/// </summary>
|
||||
/// <param name="playerInfos"></param>
|
||||
public static void SetNoDeskPlayer(List<NoDeskPlayerInfo> playerInfos) {
|
||||
if (playerInfos == null) return;
|
||||
redisManager.GetBiSaidb(ConstClass.NoDeskMatesAllowedDBIdx).StringSet(ConstClass.NoDeskMatesAllowedKey, JsonPack.GetJson(playerInfos));
|
||||
}
|
||||
}
|
||||
}
|
||||
61
GameDAL/ChongZhiShangPingDal.cs
Normal file
61
GameDAL/ChongZhiShangPingDal.cs
Normal file
@ -0,0 +1,61 @@
|
||||
using MrWu.Debug;
|
||||
using ObjectModel.Config;
|
||||
using Server.DB.Sql;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using GameData;
|
||||
using GameMessage;
|
||||
|
||||
namespace GameDAL
|
||||
{
|
||||
public class ChongZhiShangPingDal
|
||||
{
|
||||
|
||||
private static void ConvertData(DataTable dt,List<ChongZhiShangPing> shangPings)
|
||||
{
|
||||
if (dt == null || dt.Rows.Count <= 0) return;
|
||||
int len = dt.Rows.Count;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
var id = (int)dt.Rows[i]["id"];
|
||||
if (id <= 3) continue;
|
||||
ChongZhiShangPing temp = new ChongZhiShangPing();
|
||||
temp.id = id;
|
||||
temp.jiazhi = (int)dt.Rows[i]["jiazhi"];
|
||||
temp.GetJinBi = (long)dt.Rows[i]["deJinbi"];
|
||||
temp.GetCanSaiJuan = (int)dt.Rows[i]["deCanSaiJuan"];
|
||||
temp.GetFuHuoKa = (int)dt.Rows[i]["deFuhuoKa"];
|
||||
temp.GetZuanShi = (int)dt.Rows[i]["deZuanShi"];
|
||||
temp.GetHuiYuan = (int)dt.Rows[i]["deHuiYuan"];
|
||||
temp.PayZuanShi = (int)dt.Rows[i]["fuZuanshi"];
|
||||
temp.PayLiJuan = (int)dt.Rows[i]["fuLijuan"];
|
||||
temp.PayRMB = (int)dt.Rows[i]["fuRMB"];
|
||||
temp.PayHongBao = (int)dt.Rows[i]["payHongBao"];
|
||||
temp.Title = dt.Rows[i]["title"].ToString();
|
||||
Debug.Info($"id:{temp.id} title:{temp.Title} i:{temp.PayRMB}");
|
||||
//if (temp.PayLiJuan > 0) continue;
|
||||
shangPings.Add(temp);
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<List<ChongZhiShangPing>> GetAllShangPingsAsync()
|
||||
{
|
||||
List<ChongZhiShangPing> result = new List<ChongZhiShangPing>();
|
||||
try
|
||||
{
|
||||
DataTable dt = await GameDB.Instance.selectDbAsync(dbbase.game2018, "tbChongZhiShangPing");
|
||||
ConvertData(dt,result);
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error($"获取所有充值商品出错 msg:{e.Message},code{e.StackTrace}");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
116
GameDAL/Club/ClubBankPlayerInGame.cs
Normal file
116
GameDAL/Club/ClubBankPlayerInGame.cs
Normal file
@ -0,0 +1,116 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Server.DB.Redis;
|
||||
using System.Text;
|
||||
using StackExchange.Redis;
|
||||
using MrWu.Debug;
|
||||
|
||||
namespace GameDAL {
|
||||
/// <summary>
|
||||
/// 竞技比赛的 禁止玩家游玩
|
||||
/// </summary>
|
||||
public class ClubBankPlayerInGame {
|
||||
|
||||
public const int DbIdx = 6;
|
||||
|
||||
private ClubBankPlayerInGame() { }
|
||||
|
||||
static ClubBankPlayerInGame() {
|
||||
instance = new ClubBankPlayerInGame();
|
||||
}
|
||||
|
||||
public static ClubBankPlayerInGame instance {
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 数据库单项操作
|
||||
/// </summary>
|
||||
public IDatabaseProxy dbp {
|
||||
get {
|
||||
return redisManager.Getdb(DbIdx);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 数据库操作
|
||||
/// </summary>
|
||||
public IDatabase db {
|
||||
get {
|
||||
return redisManager.GetDataBase(DbStyle.main, DbIdx);
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* 数据结构
|
||||
*
|
||||
* ClubBankPlayers:clubid [243633,243663]
|
||||
* ClubBankPlayers:clubid [243634,246338]
|
||||
*
|
||||
* */
|
||||
public const string baseKey = "ClubBankPlayers";
|
||||
|
||||
/// <summary>
|
||||
/// 获取竞技比赛的 禁止同桌 所有集合的 key
|
||||
/// </summary>
|
||||
/// <param name="clubid"></param>
|
||||
/// <returns></returns>
|
||||
public string GetClubBankKey(int clubid) {
|
||||
return $"{baseKey}:{clubid}";
|
||||
}
|
||||
|
||||
public List<int> GetAll(int clubId)
|
||||
{
|
||||
string key = GetClubBankKey(clubId);
|
||||
var values = dbp.SetMembers(key);
|
||||
var ret = values.Select(x=>int.Parse(x)).ToList();
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加一个禁止游玩的玩家 (过期时间一年)
|
||||
/// </summary>
|
||||
/// <param name="clubId">竞技比赛id</param>
|
||||
/// <param name="userId">用户id</param>
|
||||
/// <returns></returns>
|
||||
public bool Add(int clubId, int userId) {
|
||||
string key = GetClubBankKey(clubId);
|
||||
var isSuccess = dbp.SetAdd(key, userId);
|
||||
db.KeyExpire(key, TimeSpan.FromDays(365));
|
||||
return isSuccess;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除玩家限制
|
||||
/// <param name="clubId">竞技比赛id</param>
|
||||
/// <param name="userId">用户id</param>
|
||||
/// </summary>
|
||||
public bool Remove(int clubId, int userId) {
|
||||
string key = GetClubBankKey(clubId);
|
||||
var isSuccess = dbp.SetRemove(key, userId);
|
||||
db.KeyExpire(key, TimeSpan.FromDays(365));
|
||||
return isSuccess;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除
|
||||
/// </summary>
|
||||
public bool Remove(int clubId) {
|
||||
string key = GetClubBankKey(clubId);
|
||||
var isSuccess = dbp.KeyDelete(key);
|
||||
return isSuccess;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否包含玩家
|
||||
/// <param name="clubId">竞技比赛id</param>
|
||||
/// <param name="userId">用户id</param>
|
||||
/// </summary>
|
||||
public bool Contains(int clubId, int userId) {
|
||||
string key = GetClubBankKey(clubId);
|
||||
return dbp.SetContains(key, userId);
|
||||
}
|
||||
}
|
||||
}
|
||||
296
GameDAL/Club/ClubDBUtil.cs
Normal file
296
GameDAL/Club/ClubDBUtil.cs
Normal file
@ -0,0 +1,296 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Threading.Tasks;
|
||||
using Dapper;
|
||||
using GameData;
|
||||
using GameData.Club;
|
||||
using GameMessage;
|
||||
using MrWu.Debug;
|
||||
using ObjectModel.Club;
|
||||
using Server.DB.Sql;
|
||||
|
||||
namespace GameDAL.Club
|
||||
{
|
||||
public static class ClubDBUtil
|
||||
{
|
||||
/// <summary>
|
||||
/// id增量
|
||||
/// </summary>
|
||||
public const int IdIncrement = 100000;
|
||||
|
||||
#region ClubExitMatchClubList
|
||||
|
||||
/// <summary>
|
||||
/// 移除淘汰(退赛俱乐部)
|
||||
/// 直接添加解禁标记 (ReliefId),不直接删除
|
||||
/// </summary>
|
||||
public static async Task RemoveClubExitMatchAsync(int leagueClubId, int clubId)
|
||||
{
|
||||
long timeStamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds();
|
||||
string sql = "UPDATE ClubExitMatchClubList SET ReliefId=@ReliefId where ClubId=@ClubId AND LeagueClubId=@LeagueClubId AND ReliefId=0";
|
||||
await GameDB.Instance.DapperExecuteAsync(dbbase.game2018, sql,
|
||||
new {
|
||||
ClubId = clubId,
|
||||
LeagueClubId = leagueClubId,
|
||||
ReliefId = timeStamp
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加淘汰(退赛俱乐部)
|
||||
/// </summary>
|
||||
public static async Task AddClubExitMatchAsync(LeagueMatchClubExitScore data)
|
||||
{
|
||||
const string sql = @"
|
||||
INSERT INTO ClubExitMatchClubList (
|
||||
[ClubId],
|
||||
[LeagueClubId],
|
||||
[MatchId],
|
||||
[CardScore],
|
||||
[DeskScore],
|
||||
[ClubUserSumScore],
|
||||
[LeagueScore],
|
||||
[JoinRoom],
|
||||
[UpdateTime],
|
||||
[ReliefId],
|
||||
[AwardId]
|
||||
) VALUES (
|
||||
@ClubId,
|
||||
@LeagueClubId,
|
||||
@MatchId,
|
||||
@CardScore,
|
||||
@DeskScore,
|
||||
@ClubUserSumScore,
|
||||
@LeagueScore,
|
||||
@JoinRoom,
|
||||
@UpdateTime,
|
||||
@ReliefId,
|
||||
@AwardId
|
||||
)";
|
||||
await GameDB.Instance.DapperExecuteAsync(dbbase.game2018, sql, data);
|
||||
}
|
||||
|
||||
public static async Task UpdateAwardIdOnMatchClose(int matchId)
|
||||
{
|
||||
string sql =
|
||||
$"UPDATE ClubExitMatchClubList SET AwardId = {ConstData.AwardId_InHistoryCloseMatchWithResetScore} where MatchId=@MatchId AND ReliefId <> 0";
|
||||
await GameDB.Instance.DapperExecuteAsync(dbbase.game2018, sql, new { MatchId = matchId });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取联盟下退赛俱乐部的列表
|
||||
/// </summary>
|
||||
public static List<LeagueMatchClubExitScore> GetLeagueExitMathClubList(int leagueClubId)
|
||||
{
|
||||
// ReliefId = 0 表示当前没有解禁的俱乐部数据
|
||||
string sql = "SELECT * FROM ClubExitMatchClubList where LeagueClubId=@LeagueClubId AND ReliefId=0";
|
||||
var list = GameDB.Instance.DapperQuery<LeagueMatchClubExitScore>(dbbase.game2018, sql, new { LeagueClubId = leagueClubId });
|
||||
return list?.ToList() ?? new List<LeagueMatchClubExitScore>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取联盟下已经解禁但是没有产生颁奖记录的俱乐部数据
|
||||
/// </summary>
|
||||
/// <param name="leagueClubId">联盟俱乐部Id</param>
|
||||
/// <param name="startTime">比赛开始时间</param>
|
||||
/// <param name="endTime">比赛结束时间</param>
|
||||
/// <param name="isHistoryMatch">是否是历史比赛</param>
|
||||
public static async Task<List<LeagueMatchClubExitScore>> GetLeagueExitClubReliefDataAsync(int leagueClubId, int leagueMatchId,
|
||||
DateTime startTime, DateTime endTime, bool isHistoryMatch)
|
||||
{
|
||||
var parameters = new DynamicParameters();
|
||||
string sql = "SELECT * FROM ClubExitMatchClubList where LeagueClubId=@LeagueClubId";
|
||||
parameters.Add("LeagueClubId", leagueClubId);
|
||||
parameters.Add("MatchId", leagueMatchId);
|
||||
parameters.Add("StartTime", new DateTimeOffset(startTime).ToUnixTimeSeconds());
|
||||
parameters.Add("EndTime", new DateTimeOffset(endTime).ToUnixTimeSeconds());
|
||||
|
||||
sql += isHistoryMatch
|
||||
? $" AND MatchId=@MatchId AND ReliefId>=@StartTime AND ReliefId<=@EndTime AND AwardId < {ConstData.AwardId_Default} AND AwardId > 0"
|
||||
: $" AND AwardId = {ConstData.AwardId_Default}";
|
||||
|
||||
var list = await GameDB.Instance.DapperQueryAsync<LeagueMatchClubExitScore>(dbbase.game2018, sql,
|
||||
parameters);
|
||||
return list?.ToList() ?? new List<LeagueMatchClubExitScore>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取联盟下已经解禁的颁奖记录历史数据
|
||||
/// </summary>
|
||||
public static async Task<List<LeagueMatchClubExitScore>> GetLeagueAwardExitClubReliefRecord(int leagueClubId, int leagueMatchId, List<long> awardIds)
|
||||
{
|
||||
string sql = "SELECT * FROM ClubExitMatchClubList where LeagueClubId=@LeagueClubId AND AwardId In @AwardIds";
|
||||
var list = await GameDB.Instance.DapperQueryAsync<LeagueMatchClubExitScore>(dbbase.game2018, sql,
|
||||
new { LeagueClubId = leagueClubId, MatchId = leagueMatchId, AwardIds = awardIds });
|
||||
return list?.ToList() ?? new List<LeagueMatchClubExitScore>();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 直接数据库的联盟颁奖逻辑,并对解禁数据进行标记
|
||||
/// </summary>
|
||||
public static async Task<bool> DoLeagueAwardRecord(long awardId, int leagueClubId, int leagueMatchId, List<AwardRecord> list)
|
||||
{
|
||||
if (list == null || list.Count < 1) return false;
|
||||
|
||||
string awardSql = @"
|
||||
INSERT INTO LeagueAwardRecord([RecordId],[CreateTime],[ClubMatchId],[ClubName],[ClubId],
|
||||
[CardScore],[DeskScore],[ClubUserSumScore],[JoinRoom],[LeagueScore],[Index]) Values
|
||||
(@RecordId,@CreateTime,@ClubMatchId,@ClubName,@ClubId,@CardScore,@DeskScore,@ClubUserSumScore,@JoinRoom,@LeagueScore,@Index)";
|
||||
// 记录颁奖数据 (如果为1就表示已经颁奖过,但是不会在颁奖记录中汇总)
|
||||
string exitReliefSql = @$"UPDATE ClubExitMatchClubList
|
||||
SET AwardId = CASE
|
||||
WHEN (ReliefId <> 0 AND AwardId = {ConstData.AwardId_Default}) THEN @AwardId
|
||||
ELSE {ConstData.AwardId_AwardNoInHistory}
|
||||
END
|
||||
WHERE LeagueClubId = @LeagueClubId
|
||||
AND MatchId = @MatchId";
|
||||
|
||||
Debug.Log(exitReliefSql);
|
||||
|
||||
return await GameDB.Instance.DapperExecuteTransactionAsync(dbbase.game2018, async (conn, tran) =>
|
||||
{
|
||||
await conn.ExecuteAsync(awardSql, list, tran);
|
||||
await conn.ExecuteAsync(exitReliefSql, new
|
||||
{
|
||||
AwardId = awardId,
|
||||
LeagueClubId = leagueClubId,
|
||||
MatchId = leagueMatchId
|
||||
}, tran);
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region clubPayCard
|
||||
|
||||
/// <summary>
|
||||
/// 带日志的添加房卡操作 (目前只处理添加的情况)
|
||||
/// </summary>
|
||||
public static async Task<bool> AddClubPayCardAsync(List<ClubPayCardDBEntity> entities)
|
||||
{
|
||||
if(entities == null || entities.Count <= 0) return false;
|
||||
int clubId = entities[0].clubId;
|
||||
int cardCount = 0;
|
||||
foreach (var e in entities)
|
||||
{
|
||||
if (clubId != e.clubId)
|
||||
{
|
||||
Debug.Warning("[Club]批处理暂时只处理一个俱乐部的数据。");
|
||||
return false;
|
||||
}
|
||||
cardCount += e.cardCount;
|
||||
}
|
||||
|
||||
if (cardCount <= 0)
|
||||
{
|
||||
Debug.Warning("[Club]添加的房卡数量小于0!暂不处理减逻辑");
|
||||
return false;
|
||||
}
|
||||
|
||||
const string logSql = @"
|
||||
INSERT INTO clubPayCard ([clubId],[userId],[cardCount],[nickName],[datetime],[sex],[origin]
|
||||
) VALUES (@clubId,@userId,@cardCount,@nickName,@datetime,@sex,@origin)";
|
||||
const string clubUpdateSql = @"
|
||||
UPDATE top(1) clubs SET [cards] = [cards] + @cardCount
|
||||
WHERE [id] = @clubId";
|
||||
clubId = clubId - IdIncrement;
|
||||
await GameDB.Instance.DapperExecuteAsync(dbbase.game2018, clubUpdateSql, new { clubId, cardCount });
|
||||
await GameDB.Instance.DapperExecuteAsync(dbbase.gamedb, logSql, entities);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 分页获取俱乐部的房卡记录
|
||||
/// </summary>
|
||||
public static async Task<(int Count, List<ClubPayCardDBEntity> Data)> GetClubPayCardAsync(int clubId, int pageNumber, int pageSize)
|
||||
{
|
||||
int skip = pageSize * (pageNumber - 1);
|
||||
// 分页获取
|
||||
string sql = @"
|
||||
WITH Results As (SELECT *, ROW_NUMBER() OVER (ORDER BY id DESC) AS RowNum FROM clubPayCard WHERE clubId=@clubId)
|
||||
SELECT * FROM Results WHERE RowNum BETWEEN @StartIndex AND @EndIndex;
|
||||
SELECT COUNT(*) FROM clubPayCard WHERE clubId=@clubId;
|
||||
";
|
||||
return await GameDB.Instance.DapperQueryMultipleAsync(dbbase.gamedb, sql,
|
||||
new { clubId, StartIndex = skip, EndIndex = skip + pageSize },
|
||||
async reader =>
|
||||
{
|
||||
var datas = (await reader.ReadAsync<ClubPayCardDBEntity>()).ToList();
|
||||
var count = await reader.ReadSingleAsync<int>();
|
||||
return (count, datas);
|
||||
});
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region clubs_rm
|
||||
public static async Task<List<int>> GetRemoveClubIds()
|
||||
{
|
||||
string sql = "SELECT Id FROM ClubsRM";
|
||||
var list = await GameDB.Instance.DapperQueryAsync<DBEntitys.ClubRM>(dbbase.game2018, sql, null);
|
||||
return list?.Select(x => x.Id).ToList() ?? new List<int>();
|
||||
}
|
||||
|
||||
|
||||
public static async Task<bool> DeleteClubAsync(DBEntitys.ClubRM club, List<DBEntitys.ClubPlayerDBEntity> clubPlayers)
|
||||
{
|
||||
string clubsSql = "DELETE FROM clubs WHERE ID = @Id";
|
||||
string clubsRmSql = @"
|
||||
INSERT INTO ClubsRM (
|
||||
[Id],[ClubName],[Notice],[Cards],[ManCnt],[Mans],[Newways],[WayVer],[Password],[CreateTime],[DeleteTime],[LeaderUserId], [Setting]
|
||||
) VALUES (
|
||||
@Id,@ClubName,@Notice,@Cards,@ManCnt,@Mans,@Newways,@WayVer,@Password,@CreateTime,@DeleteTime,@LeaderUserId,@Setting
|
||||
)";
|
||||
string leaguePowerSql = $"DELETE FROM LeagueClubLeaguePower WHERE ClubId = @Id + {IdIncrement}";
|
||||
string playerUpdateSql = "UPDATE TOP(1) players SET myclubinfodata=@myclubinfodata, joinclubinfodata=@joinclubinfodata WHERE userid2018 = @userid2018";
|
||||
string clubmsgRmSql = "DELETE FROM clubmsg WHERE receiveid = @Id";
|
||||
|
||||
return await GameDB.Instance.DapperExecuteTransactionAsync(dbbase.game2018, async (conn, tran) =>
|
||||
{
|
||||
await conn.ExecuteAsync(clubsRmSql, club, tran);
|
||||
await conn.ExecuteAsync(clubsSql, club, tran);
|
||||
await conn.ExecuteAsync(leaguePowerSql, club, tran);
|
||||
if (clubPlayers.Count > 0)
|
||||
await conn.ExecuteAsync(playerUpdateSql, clubPlayers, tran);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新导出club
|
||||
/// </summary>
|
||||
public static async Task<bool> UpdateExportClubAsync(DBEntitys.ClubsDBEntity club, List<DBEntitys.ClubPlayerDBEntity> clubPlayers)
|
||||
{
|
||||
string playerUpdateSql = "UPDATE TOP(1) players SET myclubinfodata=@myclubinfodata, joinclubinfodata=@joinclubinfodata WHERE userid2018 = @userid2018";
|
||||
string clubUpdateSql = "UPDATE TOP(1) clubs SET mans=@mans, manCnt=@manCnt, wayVer=@wayVer, newways=@newways WHERE ID = @ID";
|
||||
return await GameDB.Instance.DapperExecuteTransactionAsync(dbbase.game2018, async (conn, tran) =>
|
||||
{
|
||||
await conn.ExecuteAsync(clubUpdateSql, club, tran);
|
||||
await conn.ExecuteAsync(playerUpdateSql, clubPlayers, tran);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region clubs
|
||||
|
||||
public static async Task<bool> UpdateClubSettingAsync(int clubId, ClubSetting setting)
|
||||
{
|
||||
if (setting == null) return false;
|
||||
|
||||
clubId = clubId - IdIncrement;
|
||||
string settingJson = JsonPack.GetJson(setting);
|
||||
string sql = "UPDATE TOP(1) clubs SET [setting] = @Setting WHERE [id] = @ClubId";
|
||||
|
||||
int result = await GameDB.Instance.DapperExecuteAsync(dbbase.game2018, sql,
|
||||
new { ClubId = clubId, Setting = settingJson });
|
||||
return result > 0;
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
1670
GameDAL/Club/ClubDataManager.cs
Normal file
1670
GameDAL/Club/ClubDataManager.cs
Normal file
@ -0,0 +1,1670 @@
|
||||
/*
|
||||
* 由SharpDevelop创建。
|
||||
* 用户: Administrator
|
||||
* 日期: 2019-03-28
|
||||
* 时间: 14:23
|
||||
*
|
||||
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
|
||||
*/
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using Server.DB.Sql;
|
||||
using System.Data;
|
||||
using MrWu.Debug;
|
||||
using System.Collections.Generic;
|
||||
using MrWu.Time;
|
||||
using MrWu.Binary;
|
||||
using MrWu.Basic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MrWu.DB;
|
||||
using GameData;
|
||||
using Server.Data.ClubDef;
|
||||
using Server.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Text;
|
||||
using Server.DB.Redis;
|
||||
using StackExchange.Redis;
|
||||
using System.Data.SqlTypes;
|
||||
using GameData.Club;
|
||||
using GameMessage;
|
||||
|
||||
namespace GameDAL
|
||||
{
|
||||
/// <summary>
|
||||
/// 竞技比赛数据管理
|
||||
/// </summary>
|
||||
public static class ClubDataManager
|
||||
{
|
||||
|
||||
/// <summary>
|
||||
/// 竞技比赛表名称
|
||||
/// </summary>
|
||||
public const string tb_clubs = "clubs";
|
||||
|
||||
/// <summary>
|
||||
/// id列名
|
||||
/// </summary>
|
||||
public const string fd_id = "id";
|
||||
|
||||
/// <summary>
|
||||
/// 竞技比赛名称列名
|
||||
/// </summary>
|
||||
public const string fd_clubname = "clubname";
|
||||
|
||||
/// <summary>
|
||||
/// 公告列名
|
||||
/// </summary>
|
||||
public const string fd_notice = "notice";
|
||||
|
||||
/// <summary>
|
||||
/// 竞技比赛会长列名
|
||||
/// </summary>
|
||||
public const string fd_leadername = "leadername";
|
||||
|
||||
/// <summary>
|
||||
/// 玩法版本
|
||||
/// </summary>
|
||||
public const string fd_wayVer = "wayVer";
|
||||
|
||||
/// <summary>
|
||||
/// 时间小时部分列名
|
||||
/// </summary>
|
||||
public const string fd_createtimeh = "createtimeh";
|
||||
|
||||
/// <summary>
|
||||
/// 时间分钟部分列名
|
||||
/// </summary>
|
||||
public const string fd_createtimem = "createtimem";
|
||||
|
||||
/// <summary>
|
||||
/// 时间秒部分列名
|
||||
/// </summary>
|
||||
public const string fd_createtimes = "createtimes";
|
||||
|
||||
/// <summary>
|
||||
/// 关闭时间小时部分列名
|
||||
/// </summary>
|
||||
public const string fd_closetimeh = "closetimeh";
|
||||
|
||||
/// <summary>
|
||||
/// 关闭时间分钟部分列名
|
||||
/// </summary>
|
||||
public const string fd_closetimem = "closetimem";
|
||||
|
||||
/// <summary>
|
||||
/// 关闭时间秒钟部分列名
|
||||
/// </summary>
|
||||
public const string fd_closetimes = "closetimes";
|
||||
|
||||
/// <summary>
|
||||
/// 房卡 列名
|
||||
/// </summary>
|
||||
public const string fd_cards = "cards";
|
||||
|
||||
/// <summary>
|
||||
/// 玩家数量 列名
|
||||
/// </summary>
|
||||
public const string fd_manCnt = "manCnt";
|
||||
|
||||
/// <summary>
|
||||
/// 所有的竞技比赛玩家数据 列名
|
||||
/// </summary>
|
||||
public const string fd_mans = "mans";
|
||||
|
||||
/// <summary>
|
||||
/// 俱乐部密码
|
||||
/// </summary>
|
||||
public const string fd_Password = "password";
|
||||
|
||||
/// <summary>
|
||||
/// 新玩法列
|
||||
/// </summary>
|
||||
public const string fd_newways = "newways";
|
||||
|
||||
/// <summary>
|
||||
/// 设置
|
||||
/// </summary>
|
||||
public const string fd_setting = "setting";
|
||||
|
||||
/// <summary>
|
||||
/// 积分 消耗一张房卡得1积分
|
||||
/// </summary>
|
||||
public const string fd_integral = "integral";
|
||||
|
||||
/// <summary>
|
||||
/// 竞技比赛所有玩家表
|
||||
/// </summary>
|
||||
public const string tb_players = "players";
|
||||
|
||||
/// <summary>
|
||||
/// userid列
|
||||
/// </summary>
|
||||
public const string fd_userid2018 = "userid2018";
|
||||
|
||||
/// <summary>
|
||||
/// 用户名
|
||||
/// </summary>
|
||||
public const string fd_nickname2018 = "nickname2018";
|
||||
|
||||
/// <summary>
|
||||
/// 联系方式-没用上
|
||||
/// </summary>
|
||||
//public const string fd_contact = "contact";
|
||||
|
||||
/// <summary>
|
||||
/// 我的竞技比赛信息_老的
|
||||
/// </summary>
|
||||
public const string fd_myclubinfo = "myclubinfo";
|
||||
|
||||
/// <summary>
|
||||
/// 我的竞技比赛信息 新的
|
||||
/// </summary>
|
||||
public const string fd_myclubinfodata = "myclubinfodata";
|
||||
|
||||
/// <summary>
|
||||
/// 我加入的竞技比赛信息 老的
|
||||
/// </summary>
|
||||
public const string fd_joinclubinfo = "joinclubinfo";
|
||||
|
||||
/// <summary>
|
||||
/// 我加入的竞技比赛信息 新的
|
||||
/// </summary>
|
||||
public const string fd_joinclubinfodata = "joinclubinfodata";
|
||||
|
||||
/// <summary>
|
||||
/// 战斗记录id 老的
|
||||
/// </summary>
|
||||
public const string fd_fightcord = "fightrecordid";
|
||||
|
||||
/// <summary>
|
||||
/// 战斗记录 新的
|
||||
/// </summary>
|
||||
public const string fd_fightcorddata = "fightrecordiddata";
|
||||
|
||||
/// <summary>
|
||||
/// 竞技比赛消息白哦
|
||||
/// </summary>
|
||||
public const string tb_message = "clubmsg";
|
||||
|
||||
/// <summary>
|
||||
/// 消息类型字段
|
||||
/// </summary>
|
||||
public const string fd_style = "style";
|
||||
|
||||
/// <summary>
|
||||
/// 消息状态
|
||||
/// </summary>
|
||||
public const string fd_state = "state";
|
||||
|
||||
/// <summary>
|
||||
/// 内容
|
||||
/// </summary>
|
||||
public const string fd_strcontent = "strcontent";
|
||||
|
||||
/// <summary>
|
||||
/// 接收时间
|
||||
/// </summary>
|
||||
public const string fd_sendTime = "sendTime";
|
||||
|
||||
/// <summary>
|
||||
/// 处理时间
|
||||
/// </summary>
|
||||
public const string fd_dotime = "dotime";
|
||||
|
||||
/// <summary>
|
||||
/// 处理者
|
||||
/// </summary>
|
||||
public const string fd_doman = "doman";
|
||||
|
||||
/// <summary>
|
||||
/// 处理人名称
|
||||
/// </summary>
|
||||
public const string fd_domanname = "domanname";
|
||||
|
||||
/// <summary>
|
||||
/// 接收人id 转变为竞技比赛id
|
||||
/// </summary>
|
||||
public const string fd_receiveid = "receiveid";
|
||||
|
||||
/// <summary>
|
||||
/// 发送者id 转变为用户id
|
||||
/// </summary>
|
||||
public const string fd_sendid = "sendid";
|
||||
|
||||
/// <summary>
|
||||
/// 发送者名称
|
||||
/// </summary>
|
||||
public const string fd_sendname = "sendname";
|
||||
|
||||
/// <summary>
|
||||
/// 竞技比赛战斗记录表
|
||||
/// </summary>
|
||||
public const string tb_ClubFightRecord = "club_FightRecord";
|
||||
|
||||
/// <summary>
|
||||
/// 竞技比赛大赢家表
|
||||
/// </summary>
|
||||
public const string tb_ClubBigWiner = "Club_BigWiner";
|
||||
|
||||
/// <summary>
|
||||
/// 竞技比赛id
|
||||
/// </summary>
|
||||
public const string fd_clubid = "clubid";
|
||||
|
||||
/// <summary>
|
||||
/// 玩法id
|
||||
/// </summary>
|
||||
public const string fd_wayid = "wayid";
|
||||
|
||||
/// <summary>
|
||||
/// 房间的唯一码
|
||||
/// </summary>
|
||||
public const string fd_weiyima = "weiyima";
|
||||
|
||||
/// <summary>
|
||||
/// 游戏服务器id
|
||||
/// </summary>
|
||||
public const string fd_gameserid = "gameserid";
|
||||
|
||||
/// <summary>
|
||||
/// 房间号
|
||||
/// </summary>
|
||||
public const string fd_roomnum = "roomnum";
|
||||
|
||||
/// <summary>
|
||||
/// 房间战斗次数
|
||||
/// </summary>
|
||||
public const string fd_warcnt = "warcnt";
|
||||
|
||||
/// <summary>
|
||||
/// 开始时间
|
||||
/// </summary>
|
||||
public const string fd_startTime = "startTime";
|
||||
|
||||
/// <summary>
|
||||
/// 结束时间
|
||||
/// </summary>
|
||||
public const string fd_endTime = "endTime";
|
||||
|
||||
/// <summary>
|
||||
/// 玩家分值信息
|
||||
/// </summary>
|
||||
public const string fd_scores = "scores";
|
||||
|
||||
/// <summary>
|
||||
/// userid
|
||||
/// </summary>
|
||||
public const string fd_userid = "userid";
|
||||
|
||||
/// <summary>
|
||||
/// 昵称
|
||||
/// </summary>
|
||||
public const string fd_nickname = "nickname";
|
||||
|
||||
/// <summary>
|
||||
/// 备注
|
||||
/// </summary>
|
||||
public const string fd_remark = "remark";
|
||||
|
||||
/// <summary>
|
||||
/// 头像
|
||||
/// </summary>
|
||||
public const string fd_photo = "photo";
|
||||
|
||||
/// <summary>
|
||||
/// id增量
|
||||
/// </summary>
|
||||
public const int idIncrement = 100000;
|
||||
|
||||
/// <summary>
|
||||
/// 创建竞技比赛存储过程
|
||||
/// </summary>
|
||||
public const string pr_createclubnew = "createclubnew";
|
||||
|
||||
/// <summary>
|
||||
/// 创建竞技比赛玩家
|
||||
/// </summary>
|
||||
public const string pr_createplayer = "CreateClubPlayer";
|
||||
|
||||
/// <summary>
|
||||
/// 加载所有的竞技比赛数据
|
||||
/// </summary>
|
||||
public static List<Club_Base> LoadClubs()
|
||||
{
|
||||
List<Club_Base> clubs = new List<Club_Base>();
|
||||
DataTable dt = GameDB.Instance.selectDb(dbbase.game2018, tb_clubs);
|
||||
int len = dt.Rows.Count;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
clubs.Add(_LoadClub(dt.Rows[i]));
|
||||
}
|
||||
return clubs;
|
||||
}
|
||||
|
||||
public static async Task<Club_Base> LoadClubAsync(int clubid)
|
||||
{
|
||||
return await Task.Run(()=>LoadClub(clubid));
|
||||
}
|
||||
|
||||
public static Club_Base LoadClub(int clubid)
|
||||
{
|
||||
clubid = clubid -= 100000;
|
||||
DataTable dt = GameDB.Instance.selectDb(dbbase.game2018, tb_clubs, null, $"id={clubid}");
|
||||
if (dt.Rows.Count <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
return _LoadClub(dt.Rows[0]);
|
||||
}
|
||||
|
||||
public static bool ExistClub(int clubId)
|
||||
{
|
||||
clubId = clubId -= 100000;
|
||||
bool exists = GameDB.Instance.DapperExecuteScalar<int>(dbbase.game2018,
|
||||
$"SELECT COUNT(1) FROM {tb_clubs} WHERE Id = @Id",
|
||||
new { Id = clubId }) > 0;
|
||||
return exists;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从行数据中加载竞技比赛数据
|
||||
/// </summary>
|
||||
/// <param name="row">行</param>
|
||||
/// <returns></returns>
|
||||
private static Club_Base _LoadClub(DataRow row)
|
||||
{
|
||||
Club_Base club = new Club_Base();
|
||||
club.Init();
|
||||
club.id = int.Parse(row[fd_id].ToString()) + idIncrement;
|
||||
club.clubname = row[fd_clubname].ToString();
|
||||
club.notice = row[fd_notice].ToString();
|
||||
club.leadername = row[fd_leadername].ToString();
|
||||
club.wayVer = (int)row[fd_wayVer];
|
||||
int timeh = int.Parse(row[fd_createtimeh].ToString());
|
||||
int timem = int.Parse(row[fd_createtimem].ToString());
|
||||
int times = int.Parse(row[fd_createtimes].ToString());
|
||||
|
||||
//if (club.id > 100050)
|
||||
// Console.WriteLine("1111");
|
||||
|
||||
CustomTime custime = new CustomTime(timeh, (byte)timem, (byte)times, 0);
|
||||
club.createTime = TimeConvert.CustomTimeToDateTime(custime);
|
||||
club.card = int.Parse(row[fd_cards].ToString());
|
||||
club.mancnt = int.Parse(row[fd_manCnt].ToString());
|
||||
byte[] bts = row[fd_mans] as byte[];
|
||||
tr_clubMans mans = BinaryConvert.BytesToStruct<tr_clubMans>(bts, 0);
|
||||
if (mans.ids != null)
|
||||
{
|
||||
club.mansid.AddRange(mans.ids.GetNewArray(0, club.mancnt));
|
||||
}
|
||||
|
||||
if (club.mancnt != club.mansid.Count)
|
||||
{
|
||||
Debug.Error($"数据错误,玩家数量与真实数量不一致! {club.id}");
|
||||
}
|
||||
|
||||
string ways = row[fd_newways].ToString();
|
||||
|
||||
if (club.wayVer == Club_Base.allServerVer)
|
||||
{
|
||||
PlayWay[] plways = JsonPack.GetData<PlayWay[]>(ways);
|
||||
if (plways != null)
|
||||
club.ways.AddRange(plways);
|
||||
}
|
||||
|
||||
club.PassWord = row[fd_Password].ToString();
|
||||
|
||||
string setting = row[fd_setting].ToString();
|
||||
if (!string.IsNullOrEmpty(setting))
|
||||
{
|
||||
club.Setting = JsonPack.GetData<ClubSetting>(setting);
|
||||
}
|
||||
else
|
||||
{
|
||||
club.Setting = new ClubSetting();
|
||||
}
|
||||
Debug.Info("加载竞技比赛:" + club.clubname);
|
||||
// Thread.Sleep(2);//不知为何要等待100ms, 单元测试,当数据较多时(大于200),将导致测试因超时失败,因此由原100修改为2
|
||||
return club;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加载所有的拥有竞技比赛的玩家
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static List<ClubPlayer> LoadPlayers()
|
||||
{
|
||||
List<ClubPlayer> players = new List<ClubPlayer>();
|
||||
|
||||
DataTable dt = GameDB.Instance.selectDb(dbbase.game2018, tb_players);
|
||||
int len = dt.Rows.Count;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
players.Add(_LoadPlayer(dt.Rows[i]));
|
||||
}
|
||||
return players;
|
||||
}
|
||||
|
||||
public static ClubPlayer LoadPlayer(int userId)
|
||||
{
|
||||
DataTable dt = GameDB.Instance.selectDb(dbbase.game2018, tb_players, null, $"userid2018={userId}");
|
||||
int len = dt.Rows.Count;
|
||||
if (len > 0)
|
||||
{
|
||||
return _LoadPlayer(dt.Rows[0]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除俱乐部玩家
|
||||
/// </summary>
|
||||
/// <param name="userid"></param>
|
||||
/// <returns></returns>
|
||||
public static bool DeletePlayer(int userid)
|
||||
{
|
||||
string sql = $"delete from players where userid2018={userid}";
|
||||
return 1 == GameDB.Instance.ExceSql(dbbase.game2018, sql);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除俱乐部
|
||||
/// </summary>
|
||||
/// <param name="clubid"></param>
|
||||
/// <returns></returns>
|
||||
public static bool DeleteClub(int clubid)
|
||||
{
|
||||
string sql = $"DELETE FROM clubs WHERE ID = {clubid}";
|
||||
string leaguePowerSql = $"DELETE FROM LeagueClubLeaguePower WHERE ClubId = {clubid}";
|
||||
var ret = dbbase.game2018.ExecuteTransaction(t =>
|
||||
{
|
||||
t.ExecuteNonQuery(sql);
|
||||
t.ExecuteNonQuery(leaguePowerSql);
|
||||
|
||||
return true;
|
||||
});
|
||||
return ret;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除俱乐部消息,申请加入之类的消息
|
||||
/// </summary>
|
||||
/// <param name="clubId">俱乐部Id,减去了100000的id,真实的俱乐部Id</param>
|
||||
/// <returns></returns>
|
||||
public static bool DeleteClubsByClubId(int clubId)
|
||||
{
|
||||
string sql = $"DELETE FROM clubmsg WHERE receiveid = {clubId}";
|
||||
var c = GameDB.Instance.ExceSql(dbbase.game2018, sql);
|
||||
Debug.ImportantLog($"删除俱乐部:{clubId} 的消息条数为:{c}");
|
||||
return c > 0;
|
||||
}
|
||||
|
||||
public static Task<bool> PlayerIsInClubAsync(int userid)
|
||||
{
|
||||
return Task.Run(() => PlayerIsInClub(userid));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 玩家是否在俱乐部里面有数据
|
||||
/// </summary>
|
||||
/// <returns>true有数据 false没有数据</returns>
|
||||
public static bool PlayerIsInClub(int userid)
|
||||
{
|
||||
string sql = $"select top 1 * from players where userid2018={userid}";
|
||||
DataSet ds = new DataSet();
|
||||
GameDB.Instance.ExceSql(dbbase.game2018, sql, null, ds);
|
||||
var b = ds.Tables != null && ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0;
|
||||
if (!b) return false;
|
||||
var myinfo = ds.Tables[0].Rows[0][fd_myclubinfodata] == DBNull.Value;
|
||||
var joinInfo = ds.Tables[0].Rows[0][fd_joinclubinfodata] == DBNull.Value;
|
||||
//Debug.ImportantLog($"b m:{myinfo} ,j:{joinInfo}");
|
||||
if (myinfo && joinInfo)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
else
|
||||
{
|
||||
string myText = ds.Tables[0].Rows[0][fd_myclubinfodata] as string; //空数据一般是[]
|
||||
string joinText = ds.Tables[0].Rows[0][fd_joinclubinfodata] as string;
|
||||
//Debug.ImportantLog($"mytext:{myText}, join:{joinText}");
|
||||
if (myText.Length <= 3 && joinText.Length <= 3)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加载竞技比赛玩家
|
||||
///
|
||||
/// 2020-06-21 修改竞技比赛的玩家表
|
||||
/// 原来存储的是二进制数据,完全没有办法拓展。
|
||||
/// 所以把我的竞技比赛信息,加入的竞技比赛信息,战斗记录的id,换成 josn 格式存储 新增数据库字段
|
||||
/// 也就是这个版本升级之contact 字段 myclubinfo 字段 joinclubinfo 字段 fightrecordid 字段 都废弃了
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="row">行</param>
|
||||
/// <returns>竞技比赛玩家</returns>
|
||||
private static ClubPlayer _LoadPlayer(DataRow row)
|
||||
{
|
||||
ClubPlayer player = new ClubPlayer();
|
||||
//userid
|
||||
player.userid = int.Parse(row[fd_userid2018].ToString());
|
||||
//用户昵称
|
||||
player.nickname = row[fd_nickname2018].ToString();
|
||||
if (row["sex"] != DBNull.Value)
|
||||
{ //这是新加的字段
|
||||
player.sex = int.Parse(row["sex"].ToString());
|
||||
}
|
||||
bool isSave = false;
|
||||
|
||||
//先去加载新的, 如果加载不到 就去加载老的
|
||||
if (row[fd_myclubinfodata] == DBNull.Value)
|
||||
{ //新的是空 去加载老的, 并把这个数据存到新的里面去
|
||||
byte[] bts = row[fd_myclubinfo] as byte[];
|
||||
tr_clubsOfPlayer myclubinfo = BinaryConvert.BytesToStruct<tr_clubsOfPlayer>(bts);
|
||||
player.myClubs = tr_clubsOfPlayerToListPlayerofClub(ref myclubinfo);
|
||||
//存到新的里去
|
||||
isSave = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
string text = row[fd_myclubinfodata] as string;
|
||||
player.myClubs = JsonPack.GetData<List<playerofClub>>(text);
|
||||
if (player.myClubs == null)
|
||||
{
|
||||
Debug.Error("新表中没有存储到我的竞技比赛数据" + player.userid);
|
||||
player.myClubs = new List<playerofClub>();
|
||||
}
|
||||
}
|
||||
|
||||
if (row[fd_joinclubinfodata] == DBNull.Value)
|
||||
{ //新的是空 去加载老的,并把这个数据存到新的里面去
|
||||
byte[] bts = row[fd_joinclubinfo] as byte[];
|
||||
tr_clubsOfPlayer joinclubinfo = BinaryConvert.BytesToStruct<tr_clubsOfPlayer>(bts);
|
||||
player.joinClubs = tr_clubsOfPlayerToListPlayerofClub(ref joinclubinfo);
|
||||
//存到新的里面去
|
||||
isSave = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
string text = row[fd_joinclubinfodata] as string;
|
||||
player.joinClubs = JsonPack.GetData<List<playerofClub>>(text);
|
||||
if (player.joinClubs == null)
|
||||
{
|
||||
Debug.Error("新表中没有存储到我加入的竞技比赛数据:" + player.userid);
|
||||
player.joinClubs = new List<playerofClub>();
|
||||
}
|
||||
}
|
||||
|
||||
if (row[fd_fightcorddata] == DBNull.Value)
|
||||
{
|
||||
byte[] bts = row[fd_fightcord] as byte[];
|
||||
tr_playerFightRecordId fightrecord = BinaryConvert.BytesToStruct<tr_playerFightRecordId>(bts);
|
||||
player.fightRecordids = FightRecordidToListid(ref fightrecord);
|
||||
//存到新的里面去
|
||||
isSave = true;
|
||||
}
|
||||
else
|
||||
{
|
||||
string text = row[fd_fightcorddata] as string;
|
||||
player.fightRecordids = JsonPack.GetData<List<int>>(text);
|
||||
if (player.fightRecordids == null)
|
||||
{
|
||||
Debug.Error("新表中没有存储到战斗记录数据的id:" + player.userid);
|
||||
player.fightRecordids = new List<int>();
|
||||
}
|
||||
}
|
||||
|
||||
if (isSave)
|
||||
UpdatePlayer(player);
|
||||
|
||||
return player;
|
||||
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 时间转换
|
||||
/// </summary>
|
||||
/// <param name="time"></param>
|
||||
/// <returns></returns>
|
||||
private static DateTime ConvertTime(ref tr_sifangdatetime time)
|
||||
{
|
||||
CustomTime ct = new CustomTime(time.hours, time.minute, time.second);
|
||||
return TimeConvert.CustomTimeToDateTime(ct);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 时间转换
|
||||
/// </summary>
|
||||
/// <param name="time"></param>
|
||||
/// <returns></returns>
|
||||
private static tr_sifangdatetime ConvertTime(DateTime time)
|
||||
{
|
||||
CustomTime ct = TimeConvert.DateTimeToCustomTime(time);
|
||||
tr_sifangdatetime sftime;
|
||||
sftime.hours = ct.hours;
|
||||
sftime.minute = ct.minute;
|
||||
sftime.second = ct.second;
|
||||
return sftime;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 玩家的单个竞技比赛结构数据转类数据
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
private static playerofClub Tr_playerInfoOfClubToplayerofClub(ref tr_playerInfoOfClub tpic)
|
||||
{
|
||||
playerofClub item = new playerofClub();
|
||||
item.clubid = tpic.clubid;
|
||||
item.inGame = tpic.ingame;
|
||||
item.position = tpic.position;
|
||||
item.remark = BinaryConvert.BytesToShortString(tpic.remark, BinaryConvert.GB2312);
|
||||
if (item.remark.Length != 0)
|
||||
Console.WriteLine(item.remark);
|
||||
item.joinTime = ConvertTime(ref tpic.jointime);
|
||||
item.permission = tpic.bak1;
|
||||
return item;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 玩家的单个竞技比赛类数据转结构数据
|
||||
/// </summary>
|
||||
/// <param name="pc"></param>
|
||||
/// <returns></returns>
|
||||
private static tr_playerInfoOfClub PlayerofClubTotr_playerInfoOfClub(playerofClub pc)
|
||||
{
|
||||
tr_playerInfoOfClub tpic = tr_playerInfoOfClub.CreateTr_playerInfoOfClub();
|
||||
tpic.clubid = pc.clubid;
|
||||
tpic.ingame = (byte)pc.inGame;
|
||||
tpic.jointime = ConvertTime(pc.joinTime);
|
||||
tpic.position = (byte)pc.position;
|
||||
tpic.bak1 = (ushort)pc.permission;
|
||||
BinaryConvert.ShortStringToBytes(pc.remark, tpic.remark, 0, BinaryConvert.GB2312);
|
||||
return tpic;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 玩家的竞技比赛结构数据 转类数据
|
||||
/// </summary>
|
||||
/// <param name="tcp"></param>
|
||||
/// <returns></returns>
|
||||
private static List<playerofClub> tr_clubsOfPlayerToListPlayerofClub(ref tr_clubsOfPlayer tcp)
|
||||
{
|
||||
List<playerofClub> pc = new List<playerofClub>();
|
||||
for (int i = 0; i < tcp.cnt; i++)
|
||||
{
|
||||
pc.Add(Tr_playerInfoOfClubToplayerofClub(ref tcp.datas[i]));
|
||||
}
|
||||
return pc;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 玩家的竞技比赛类数据 转结构数据
|
||||
/// </summary>
|
||||
/// <param name="clubdata"></param>
|
||||
/// <returns></returns>
|
||||
private static tr_clubsOfPlayer ListPlayerofClubTotr_clubsOfPlayer(List<playerofClub> clubdata)
|
||||
{
|
||||
tr_clubsOfPlayer tcp = tr_clubsOfPlayer.CreateTr_clubsOfPlayer();//new tr_clubsOfPlayer();
|
||||
tcp.cnt = clubdata.Count;
|
||||
for (int i = 0; i < tcp.cnt; i++)
|
||||
{
|
||||
if (i < tcp.datas.Length)
|
||||
tcp.datas[i] = PlayerofClubTotr_playerInfoOfClub(clubdata[i]);
|
||||
}
|
||||
return tcp;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 玩家战斗记录id结构体转链表
|
||||
/// </summary>
|
||||
/// <param name="pfr"></param>
|
||||
/// <returns></returns>
|
||||
private static List<int> FightRecordidToListid(ref tr_playerFightRecordId pfr)
|
||||
{
|
||||
List<int> records = new List<int>();
|
||||
for (int i = 0; i < pfr.cnt; i++)
|
||||
{
|
||||
records.Add(pfr.fightrecords[i]);
|
||||
}
|
||||
return records;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 玩家战斗记录id链表转结构体
|
||||
/// </summary>
|
||||
/// <param name="ids"></param>
|
||||
/// <returns></returns>
|
||||
public static tr_playerFightRecordId ListidToFightRecordid(List<int> ids)
|
||||
{
|
||||
tr_playerFightRecordId tpfr = new tr_playerFightRecordId();
|
||||
tpfr.cnt = ids.Count;
|
||||
for (int i = 0; i < tpfr.cnt; i++)
|
||||
{
|
||||
tpfr.fightrecords[i] = ids[i];
|
||||
}
|
||||
return tpfr;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 数组转 竞技比赛 中的玩家数据
|
||||
/// </summary>
|
||||
/// <param name="mansid"></param>
|
||||
/// <returns></returns>
|
||||
public static tr_clubMans ArrayTotr_clubMans(List<int> mansid)
|
||||
{
|
||||
tr_clubMans mans = tr_clubMans.CreateClubMans();
|
||||
int len = mansid.Count;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
mans.ids[i] = mansid[i];
|
||||
}
|
||||
return mans;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建竞技比赛存储过程
|
||||
/// </summary>
|
||||
/// <param name="club">竞技比赛数据</param>
|
||||
/// <param name="myclubs">我的竞技比赛数据</param>
|
||||
/// <param name="createuser">创建者userid</param>
|
||||
/// <returns>0程序出错 -1未找到创建者 -2竞技比赛名称同名 -3表示已存在竞技比赛id</returns>
|
||||
public static int CreateClub(Club_Base club, List<playerofClub> myclubs, int createuser)
|
||||
{
|
||||
var spp = GameDB.Instance.BeginSetProcedureParameter(dbbase.game2018, pr_createclubnew);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@clubid", SqlDbType.Int, club.id - ClubDataManager.idIncrement);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@clubname", SqlDbType.NVarChar, club.clubname);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@clubnotice", SqlDbType.NVarChar, club.notice);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@createruser", SqlDbType.NVarChar, createuser);
|
||||
CustomTime ct = TimeConvert.DateTimeToCustomTime(club.createTime);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@createH", SqlDbType.Int, ct.hours);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@createM", SqlDbType.Int, ct.minute);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@createS", SqlDbType.Int, ct.second);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@cards", SqlDbType.Int, club.card);
|
||||
var ids = ArrayTotr_clubMans(club.mansid);
|
||||
byte[] bts = BinaryConvert.StructToBytes(ids);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@mans", SqlDbType.Binary, bts);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@mancnt", SqlDbType.Int, club.mancnt);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@ways", SqlDbType.Text, JsonPack.GetJson(club.ways));
|
||||
var clubsinfo = JsonPack.GetJson(myclubs);
|
||||
/* 老的二进制方式
|
||||
var clubsinfo = ListPlayerofClubTotr_clubsOfPlayer(myclubs);
|
||||
bts = BinaryConvert.StructToBytes(clubsinfo);
|
||||
*/
|
||||
GameDB.Instance.AddProdureParameters(spp, "@myclubinfo", SqlDbType.Text, clubsinfo);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@result", SqlDbType.Int, 0, ParameterDirection.Output);
|
||||
DataSet ds = new DataSet();
|
||||
Dictionary<string, object> pars = GameDB.Instance.EndAddProdureParameters(spp, ds);
|
||||
return (int)pars["@result"];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建一个竞技比赛玩家
|
||||
/// </summary>
|
||||
/// <param name="player"></param>
|
||||
/// <returns></returns>
|
||||
public static bool CreatePlayer(ClubPlayer player)
|
||||
{
|
||||
var spp = GameDB.Instance.BeginSetProcedureParameter(dbbase.game2018, pr_createplayer);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@userid", SqlDbType.Int, player.userid);
|
||||
|
||||
/* 老的
|
||||
var clubsinfo = ListPlayerofClubTotr_clubsOfPlayer(player.myClubs);
|
||||
byte[] bts = BinaryConvert.StructToBytes(clubsinfo);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@myclubinfo", SqlDbType.Binary, bts);
|
||||
*/
|
||||
|
||||
var clubsinfo = JsonPack.GetJson(player.myClubs);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@myclubinfo", SqlDbType.Text, clubsinfo);
|
||||
|
||||
/* 老的
|
||||
clubsinfo = ListPlayerofClubTotr_clubsOfPlayer(player.joinClubs);
|
||||
bts = BinaryConvert.StructToBytes(clubsinfo);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@joinclubinfo", SqlDbType.Binary, bts);
|
||||
*/
|
||||
|
||||
clubsinfo = JsonPack.GetJson(player.joinClubs);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@joinclubinfo", SqlDbType.Text, clubsinfo);
|
||||
|
||||
/* 老的
|
||||
var pfr = ListidToFightRecordid(player.fightRecordids);
|
||||
bts = BinaryConvert.StructToBytes(pfr);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@fightrecordids", SqlDbType.Binary, bts);
|
||||
*/
|
||||
|
||||
var pfr = JsonPack.GetJson(player.fightRecordids);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@fightrecordids", SqlDbType.Text, pfr);
|
||||
|
||||
|
||||
GameDB.Instance.AddProdureParameters(spp, "@result", SqlDbType.Int, 0, ParameterDirection.Output);
|
||||
DataSet ds = new DataSet();
|
||||
Dictionary<string, object> pars = GameDB.Instance.EndAddProdureParameters(spp, ds);
|
||||
if (ds.Tables.Count > 0)
|
||||
{
|
||||
player.nickname = ds.Tables[0].Rows[0][fd_nickname].ToString();
|
||||
}
|
||||
|
||||
return (int)pars["@result"] == 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新玩家 修改玩家权限,设置小黑屋都需要调用更新 玩家数据
|
||||
/// </summary>
|
||||
/// <param name="player"></param>
|
||||
public static bool UpdatePlayer(ClubPlayer player)
|
||||
{
|
||||
string sql = string.Format("update Top(1) {0} set {1}=@nickname,{2}=@myclubinfo,{3}=@joinclubinfo,{4}=@fightrecord where {5}={6};",
|
||||
tb_players, fd_nickname2018, fd_myclubinfodata, fd_joinclubinfodata, fd_fightcorddata, fd_userid2018, player.userid);
|
||||
|
||||
//List<ISqlAloneParameter<SqlDbType>> sqlpms = new List<ISqlAloneParameter<SqlDbType>>();
|
||||
|
||||
/* 老的存储
|
||||
var clubsinfo = ListPlayerofClubTotr_clubsOfPlayer(player.myClubs);
|
||||
byte[] bts1 = BinaryConvert.StructToBytes(clubsinfo);
|
||||
var param1 = new SqlParameter("@myclubinfo", SqlDbType.Binary, bts1.Length) { Value = bts1 };//sqlpms.Add(new SqlAloneParameter("@myclubinfo", bts, bts.Length));
|
||||
*/
|
||||
var paramNick = new SqlParameter("@nickname", SqlDbType.Text) { Value = player.nickname };
|
||||
|
||||
var clubsinfo = JsonPack.GetJson(player.myClubs);
|
||||
var param1 = new SqlParameter("@myclubinfo", SqlDbType.Text) { Value = clubsinfo };
|
||||
|
||||
/* 老的存储
|
||||
var clubsinfo2 = ListPlayerofClubTotr_clubsOfPlayer(player.joinClubs);
|
||||
var bts2 = BinaryConvert.StructToBytes(clubsinfo2);
|
||||
var param2 = new SqlParameter("@joinclubinfo", SqlDbType.Binary, bts2.Length) { Value = bts2 };//sqlpms.Add(new SqlAloneParameter("@joinclubinfo", bts, bts.Length));
|
||||
*/
|
||||
var clubsinfo2 = JsonPack.GetJson(player.joinClubs);
|
||||
var param2 = new SqlParameter("@joinclubinfo", SqlDbType.Text) { Value = clubsinfo2 };
|
||||
|
||||
/* 老的存储
|
||||
var pfr = ListidToFightRecordid(player.fightRecordids);
|
||||
var bts3 = BinaryConvert.StructToBytes(pfr);
|
||||
var param3 = new SqlParameter("@fightrecord", SqlDbType.Binary, bts3.Length) { Value = bts3 };//sqlpms.Add(new SqlAloneParameter("@fightrecord", bts, bts.Length));
|
||||
*/
|
||||
var pfd = JsonPack.GetJson(player.fightRecordids);
|
||||
var param3 = new SqlParameter("@fightrecord", SqlDbType.Text) { Value = pfd };
|
||||
|
||||
var sqlpms = new SqlParameter[] { paramNick, param1, param2, param3 };
|
||||
return 1 == GameDB.Instance.ExceSql(dbbase.game2018, sql, sqlpms);
|
||||
}
|
||||
|
||||
public static bool UpdatePlayers(IEnumerable<ClubPlayer> players)
|
||||
{
|
||||
var transaction = GameDB.Instance.BeginTransaction(dbbase.game2018);
|
||||
var succ = false;
|
||||
try
|
||||
{
|
||||
foreach (var player in players)
|
||||
{
|
||||
string sql = string.Format("update Top(1) {0} set {1}=@nickname,{2}=@myclubinfo,{3}=@joinclubinfo,{4}=@fightrecord where {5}={6};",
|
||||
tb_players, fd_nickname2018, fd_myclubinfodata, fd_joinclubinfodata, fd_fightcorddata, fd_userid2018, player.userid);
|
||||
var paramNick = new SqlAloneParameter("@nickname", player.nickname, player.nickname.Length, SqlDbType.Text);
|
||||
var clubsinfo = JsonPack.GetJson(player.myClubs);
|
||||
var param1 = new SqlAloneParameter("@myclubinfo", clubsinfo, clubsinfo.Length, SqlDbType.Text);
|
||||
var clubsinfo2 = JsonPack.GetJson(player.joinClubs);
|
||||
var param2 = new SqlAloneParameter("@joinclubinfo", clubsinfo2, clubsinfo2.Length, SqlDbType.Text);
|
||||
var pfd = JsonPack.GetJson(player.fightRecordids);
|
||||
var param3 = new SqlAloneParameter("@fightrecord", pfd, pfd.Length, SqlDbType.Text);
|
||||
var sqlpms = new List<ISqlAloneParameter<SqlDbType>> { paramNick, param1, param2, param3 };
|
||||
succ = GameDB.Instance.TransactionAddSql(transaction, sql, sqlpms) == 1;
|
||||
if (transaction.isException)
|
||||
{
|
||||
throw transaction.exception;//发生异常,抛出
|
||||
}
|
||||
if (!succ)
|
||||
{
|
||||
throw new Exception($"UpdatePlayers failed, sql: {sql}");
|
||||
}
|
||||
}
|
||||
succ = true;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
Debug.Error($"UpdatePlayers ex:{ex}");
|
||||
}
|
||||
finally
|
||||
{
|
||||
succ &= GameDB.Instance.SubTransaction(transaction);
|
||||
}
|
||||
return succ;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取下一个竞技比赛id
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static int GetNextClubId()
|
||||
{
|
||||
string sql = string.Format("select top(1) id from {0} order by {1} desc", tb_clubs, fd_id);
|
||||
DataSet ds = new DataSet();
|
||||
GameDB.Instance.ExceSql(dbbase.game2018, sql, null, ds);
|
||||
if (ds.Tables.Count == 0 || ds.Tables[0].Rows.Count < 1) return 1;
|
||||
return int.Parse(ds.Tables[0].Rows[0]["id"].ToString()) + 1;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查看公告格式
|
||||
/// </summary>
|
||||
/// <param name="notice"></param>
|
||||
/// <returns></returns>
|
||||
private static bool CheckNotice(string notice)
|
||||
{
|
||||
return BaseFun.CheckStringLength(notice, 0, 32, true, Encoding.GetEncoding("gb2312"))
|
||||
&& BaseFun.ProcessSqlStr(notice);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行sql语句修改竞技比赛公告
|
||||
/// </summary>
|
||||
/// <param name="clubid"></param>
|
||||
/// <param name="notice"></param>
|
||||
public static void ExceSqlSetClubNotice(int clubid, string notice)
|
||||
{
|
||||
//string sql = string.Format("update top(1) {2} set {3} = '{0}' where {4} = {1}", notice, clubid, tb_clubs, fd_notice, fd_id);
|
||||
// update top(1) {tb_clubs} set {fd_notice} = '{notice}' where {fd_id} = {clubid}
|
||||
|
||||
string sql = string.Format("update top(1) {0} set {1} = @notice where [ID] = @p2", tb_clubs, fd_notice);
|
||||
GameDB.Instance.ExceSql(dbbase.game2018, sql, new SqlParameter[]{
|
||||
new SqlParameter("@p2", SqlDbType.Int){ Value = clubid - ClubDataManager.idIncrement },
|
||||
new SqlParameter("@notice",notice ?? (object)DBNull.Value)
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存俱乐部密码
|
||||
/// </summary>
|
||||
/// <param name="clubid"></param>
|
||||
/// <param name="notice"></param>
|
||||
public static void SaveClubPassword(int clubid, string password)
|
||||
{
|
||||
string sql = string.Format("update top(1) {0} set {1} = @password where [ID] = @p2", tb_clubs, fd_Password);
|
||||
GameDB.Instance.ExceSql(dbbase.game2018, sql, new SqlParameter[]{
|
||||
new SqlParameter("@p2", SqlDbType.Int){ Value = clubid - ClubDataManager.idIncrement },
|
||||
new SqlParameter("@password",password ?? string.Empty)
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 修改俱乐部群主的名字
|
||||
/// </summary>
|
||||
/// <param name="clubid"></param>
|
||||
/// <param name="nickName"></param>
|
||||
public static void UpdateLeaderName(int clubid, string nickName)
|
||||
{
|
||||
string sql = string.Format("update top(1) {0} set {1} = @nickName where [ID] = @p2", tb_clubs, fd_leadername);
|
||||
GameDB.Instance.ExceSql(dbbase.game2018, sql, new SqlParameter[]{
|
||||
new SqlParameter("@p2", SqlDbType.Int){ Value = clubid - ClubDataManager.idIncrement },
|
||||
new SqlParameter("@nickName",nickName ?? string.Empty)
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置竞技比赛公告
|
||||
/// </summary>
|
||||
/// <param name="clubid">竞技比赛id</param>
|
||||
/// <param name="notice">公告</param>
|
||||
/// <returns>公告符不符合格式</returns>
|
||||
public static bool SetClubNotice(int clubid, string notice)
|
||||
{
|
||||
bool r = CheckNotice(notice);
|
||||
|
||||
if (r)
|
||||
{
|
||||
ExceSqlSetClubNotice(clubid, notice);
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置竞技比赛公告
|
||||
/// </summary>
|
||||
/// <param name="clubid">竞技比赛id</param>
|
||||
/// <param name="notice">公告</param>
|
||||
/// <returns></returns>
|
||||
public static bool SetClubNoticeAsyn(int clubid, string notice)
|
||||
{
|
||||
bool r = CheckNotice(notice);
|
||||
|
||||
if (r)
|
||||
{
|
||||
Task.Factory.StartNew(
|
||||
() =>
|
||||
{
|
||||
ExceSqlSetClubNotice(clubid, notice);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
return r;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算带折扣房卡的最终值
|
||||
/// </summary>
|
||||
public static int CalClubCardWithDiscount(int clubId, int cardCnt)
|
||||
{
|
||||
var discount = ClubRCDiscountRedisUtil.GetClub(clubId);
|
||||
return (int)Math.Round(cardCnt / discount);
|
||||
}
|
||||
|
||||
public static Task<bool> AddClubCardAsync(int clubId,int cardCnt)
|
||||
{
|
||||
return Task.Run(() => AddClubCard(clubId, cardCnt));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加竞技比赛房卡
|
||||
/// </summary>
|
||||
/// <param name="clubid">竞技比赛id</param>
|
||||
/// <param name="cardCnt">房卡数量</param>
|
||||
public static bool AddClubCard(int clubid, int cardCnt)
|
||||
{
|
||||
string sql;
|
||||
int cnt = Math.Abs(cardCnt);
|
||||
|
||||
if (cardCnt >= 0) //返还房卡
|
||||
sql = $"update top(1) {tb_clubs} set {fd_cards} = {fd_cards} + {cnt},{fd_integral} = {fd_integral} - {cnt} where {fd_id} = {clubid - idIncrement}";
|
||||
//sql = string.Format("update Top(1) {0} set {1} = {1} + {2}, {5} = {5} - {2} where {3} = {4}", tb_clubs, fd_cards, cardCnt, fd_id, , (clubid - idIncrement));
|
||||
else
|
||||
sql = $"update top(1) {tb_clubs} set {fd_cards} = {fd_cards} - {cnt},{fd_integral} = {fd_integral} + {cnt} where {fd_id} = {clubid - idIncrement}";
|
||||
//sql = string.Format("update Top(1) {0} set {1} = {1} {2} where {3} = {4}", tb_clubs, fd_cards, cardCnt, fd_id, (clubid - idIncrement));
|
||||
|
||||
Debug.ImportantLog(sql);
|
||||
return GameDB.Instance.ExceSql(dbbase.game2018, sql) > 0;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步添加竞技比赛房卡
|
||||
/// </summary>
|
||||
/// <param name="clubid"></param>
|
||||
/// <param name="cardCnt"></param>
|
||||
public static async Task<bool> AddClubCardAsyn(int clubid, int cardCnt)
|
||||
{
|
||||
return await Task.Factory.StartNew(
|
||||
() =>
|
||||
{
|
||||
return AddClubCard(clubid, cardCnt);
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
/*
|
||||
/// <summary>
|
||||
/// 获取竞技比赛消息_未处理的
|
||||
/// </summary>
|
||||
/// <param name="clubid">竞技比赛id</param>
|
||||
/// <param name="count">最大接收数量</param>
|
||||
/// <returns></returns>
|
||||
public static List<ClubMessage> GetClubMessage(int clubid, int count) {
|
||||
List<ClubMessage> msgs = new List<ClubMessage>();
|
||||
string sql = string.Format("select Top({0}) * from {1} where {2}={3} and {4}=0 Order By sendTime desc;",
|
||||
count, tb_message, fd_receiveid, clubid - idIncrement, fd_state);
|
||||
DataSet ds = new DataSet();
|
||||
GameDB.Instance.ExceSql(dbbase.game2018, sql, null, ds);
|
||||
if (ds.Tables.Count == 0)
|
||||
return msgs;
|
||||
DataTable dt = ds.Tables[0];
|
||||
for (int i = 0; i < dt.Rows.Count; i++) {
|
||||
msgs.Add(LoadClubMessage(dt.Rows[i]));
|
||||
}
|
||||
return msgs;
|
||||
}
|
||||
*/
|
||||
|
||||
/// <summary>
|
||||
/// 加载竞技比赛消息
|
||||
/// </summary>
|
||||
/// <param name="row">行</param>
|
||||
/// <returns></returns>
|
||||
public static ClubMessage LoadClubMessage(DataRow row)
|
||||
{
|
||||
ClubMessage clubmsg = new ClubMessage();
|
||||
clubmsg.id = (int)row[fd_id];
|
||||
clubmsg.style = (int)row[fd_style];
|
||||
clubmsg.state = (int)row[fd_state];
|
||||
clubmsg.content = row[fd_strcontent].ToString();
|
||||
clubmsg.sendTime = DateTime.Parse(row[fd_sendTime].ToString());
|
||||
string doTime = row[fd_dotime].ToString();
|
||||
if (!string.IsNullOrEmpty(doTime))
|
||||
{
|
||||
clubmsg.doTime = DateTime.Parse(doTime);
|
||||
}
|
||||
if (row[fd_doman] != DBNull.Value)
|
||||
clubmsg.doman = (int)row[fd_doman];
|
||||
if (row[fd_domanname] != DBNull.Value)
|
||||
clubmsg.domanname = row[fd_domanname].ToString();
|
||||
if (row[fd_receiveid] != DBNull.Value)
|
||||
clubmsg.reciveid = (int)row[fd_receiveid] + idIncrement;
|
||||
clubmsg.sendid = (int)row[fd_sendid];
|
||||
clubmsg.sendname = row[fd_sendname].ToString();
|
||||
if (row.Table.Columns.Contains("Sex"))
|
||||
if (row["Sex"] != DBNull.Value)
|
||||
clubmsg.SendSex = (int)row["Sex"];
|
||||
clubmsg.param1 = (int)row["param1"];
|
||||
clubmsg.param2 = row["param2"] is DBNull ? null : (string)row["param2"];
|
||||
return clubmsg;
|
||||
}
|
||||
|
||||
public static Task<ClubMessage> GetClubMessageAsync(int msgid)
|
||||
{
|
||||
return Task.Run(
|
||||
() => GetClubMessage(msgid)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取竞技比赛消息
|
||||
/// </summary>
|
||||
/// <param name="msgid"></param>
|
||||
/// <returns></returns>
|
||||
public static ClubMessage GetClubMessage(int msgid)
|
||||
{
|
||||
string sql = string.Format($"select Top(1) * from {tb_message} where {fd_id} = {msgid}");
|
||||
|
||||
DataSet ds = new DataSet();
|
||||
GameDB.Instance.ExceSql(dbbase.game2018, sql, null, ds);
|
||||
if (ds.Tables.Count == 0)
|
||||
return null;
|
||||
|
||||
DataTable dt = ds.Tables[0];
|
||||
return LoadClubMessage(dt.Rows[0]);
|
||||
}
|
||||
|
||||
public static Task<List<ClubMessage>> GetClubMessageByClubAsync(int clubId)
|
||||
{
|
||||
return Task.Run(() => GetClubMessageByClub(clubId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取竞技比赛未处理的消息
|
||||
/// </summary>
|
||||
/// <param name="club"></param>
|
||||
/// <returns></returns>
|
||||
public static List<ClubMessage> GetClubMessageByClub(int clubid)
|
||||
{
|
||||
List<ClubMessage> lst = new List<ClubMessage>();
|
||||
string sql = $"SELECT TOP 500 c.[id],c.[style],c.[state],c.[sendTime],c.[dotime],c.[doman],c.[domanname],c.[receiveid],c.[sendid],c.[sendname],c.[strcontent],c.[param1],c.[param2],us.Sex FROM [game2018].[dbo].[clubmsg] c INNER JOIN jnxdgame.dbo.tbUserBaseInfo us on c.sendid=us.UserID where c.receiveid= {clubid - idIncrement} and (((c.style=0 or c.style=2) and c.state=0) or (c.style=1 and c.state=4)) order by c.id desc";//and (c.style=0 or c.style=2)
|
||||
DataSet ds = new DataSet();
|
||||
GameDB.Instance.ExceSql(dbbase.game2018, sql, null, ds);
|
||||
if (BaseFun.DataSetIsNullOrEmpty(ds) || BaseFun.DataTableIsNullOrEmpty(ds.Tables[0]))
|
||||
return lst;
|
||||
|
||||
var dt = ds.Tables[0];
|
||||
int len = dt.Rows.Count;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
lst.Add(LoadClubMessage(dt.Rows[i]));
|
||||
}
|
||||
|
||||
return lst;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取个人的消息记录
|
||||
/// </summary>
|
||||
/// <param name="userid"></param>
|
||||
/// <returns></returns>
|
||||
public static List<ClubMessage> GetClubMessageByPerson(int userid)
|
||||
{
|
||||
List<ClubMessage> lst = new List<ClubMessage>();
|
||||
string sql = string.Format($"select * from {tb_message} where {fd_sendid} = {userid} order by {fd_id} desc");
|
||||
DataSet ds = new DataSet();
|
||||
GameDB.Instance.ExceSql(dbbase.game2018, sql, null, ds);
|
||||
if (BaseFun.DataSetIsNullOrEmpty(ds) || BaseFun.DataTableIsNullOrEmpty(ds.Tables[0]))
|
||||
return lst;
|
||||
|
||||
var dt = ds.Tables[0];
|
||||
int len = dt.Rows.Count;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
lst.Add(LoadClubMessage(dt.Rows[i]));
|
||||
}
|
||||
return lst;
|
||||
}
|
||||
|
||||
public static Task<int> DoClubMessageAsync(ClubMessage clubmsg)
|
||||
{
|
||||
return Task.Run(() => DoClubMessage(clubmsg));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更新竞技比赛消息
|
||||
/// </summary>
|
||||
/// <param name="clubmsg"></param>
|
||||
public static int DoClubMessage(ClubMessage clubmsg)
|
||||
{
|
||||
string sql = string.Format($"update top(1) {tb_message} set {fd_state}={clubmsg.state},{fd_doman}='{clubmsg.doman}',{fd_dotime}='{clubmsg.doTime}',{fd_domanname}=@domanname where {fd_id}={clubmsg.id} and ((({fd_style}=0 or {fd_style}=2) and {fd_state} = 0) or ({fd_style}=1 and {fd_state} = 4))");
|
||||
return GameDB.Instance.ExceSql(dbbase.game2018, sql, new[] { new SqlParameter("@domanname", clubmsg.domanname ?? (object)DBNull.Value) });
|
||||
}
|
||||
|
||||
public static Task<bool> InsertClubMessageAsync(ClubMessage clubmsg)
|
||||
{
|
||||
return Task.Run(() => InsertClubMessage(clubmsg));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 插入一条消息
|
||||
/// </summary>
|
||||
/// <param name="clubmsg"></param>
|
||||
/// <returns></returns>
|
||||
public static bool InsertClubMessage(ClubMessage clubmsg)
|
||||
{
|
||||
|
||||
if (clubmsg.domanname == null)
|
||||
clubmsg.domanname = string.Empty;
|
||||
|
||||
if (clubmsg.content == null)
|
||||
clubmsg.content = string.Empty;
|
||||
|
||||
|
||||
string sql = $"insert into {tb_message}({fd_style},{fd_state},{fd_sendTime},{fd_receiveid},{fd_sendid},{fd_sendname},{fd_strcontent})" +
|
||||
$" values({clubmsg.style},{clubmsg.state},'{clubmsg.sendTime}',{clubmsg.reciveid},{clubmsg.sendid},@sendname,@content)";
|
||||
|
||||
return GameDB.Instance.ExceSql(dbbase.game2018, sql, new[] {
|
||||
new SqlParameter("@content", clubmsg.content ?? (object)DBNull.Value),
|
||||
new SqlParameter("@sendname", clubmsg.sendname ?? (object)string.Empty)//clubmsg 的sendname字段不允许为null
|
||||
}) == 1;
|
||||
|
||||
}
|
||||
|
||||
public static Task<bool> AskForJoinClubMessageAsync(ClubMessage clubmsg)
|
||||
{
|
||||
return Task.Run(() => AskForJoinClubMessage(clubmsg));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 请求加入竞技比赛
|
||||
/// </summary>
|
||||
/// <param name="clubmsg"></param>
|
||||
public static bool AskForJoinClubMessage(ClubMessage clubmsg)
|
||||
{
|
||||
string sql = string.Empty;
|
||||
try
|
||||
{
|
||||
if (clubmsg.domanname == null)
|
||||
clubmsg.domanname = string.Empty;
|
||||
|
||||
if (clubmsg.content == null)
|
||||
clubmsg.content = string.Empty;
|
||||
|
||||
//如果不存在 这个竞技比赛的申请 就可以去申请
|
||||
sql = string.Format($"if not exists(select Top(1) 1 from {tb_message} where {fd_receiveid} = {clubmsg.reciveid - idIncrement} and {fd_sendid} = {clubmsg.sendid} and {fd_style} = {clubmsg.style} and {fd_state} = {clubmsg.state}) begin{Environment.NewLine}");
|
||||
sql += string.Format($"insert into {tb_message}({fd_style},{fd_state},{fd_sendTime},{fd_doman},{fd_domanname},{fd_receiveid},{fd_sendid},{fd_sendname},{fd_strcontent}, param1, param2) " +
|
||||
$"values({clubmsg.style},{clubmsg.state},'{clubmsg.sendTime}',{clubmsg.doman},@domanname,{clubmsg.reciveid - idIncrement},{clubmsg.sendid},@sendname,@content, {clubmsg.param1}, @param2);");//{(clubmsg.param2 == null ? "NULL" : string.Format("'{0}'", clubmsg.param2))}
|
||||
sql += " end;";
|
||||
|
||||
//Debug.Warning("AskForJoinClubMessage:" + sql);
|
||||
|
||||
/*
|
||||
* 0724 帮看下,这里有语法错误,输出日志看下 --over
|
||||
*
|
||||
*
|
||||
* */
|
||||
|
||||
return GameDB.Instance.ExceSql(dbbase.game2018, sql, new[]{
|
||||
new SqlParameter("@domanname", clubmsg.domanname),
|
||||
new SqlParameter("@sendname", clubmsg.sendname),
|
||||
new SqlParameter("@content", clubmsg.content),
|
||||
new SqlParameter("@param2", clubmsg.param2 ?? (object)DBNull.Value)
|
||||
}) == 1;
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
throw new Exception("AskForJoinClubMessage: " + sql, ex);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加入竞技比赛数据处理_异步的
|
||||
/// </summary>
|
||||
/// <param name="club"></param>
|
||||
/// <param name="clubPlayer"></param>
|
||||
/// <returns></returns>
|
||||
public static Task ClubPlayerChange_Asyn(Club_Base club, ClubPlayer clubPlayer)
|
||||
{
|
||||
return Task.Factory.StartNew(
|
||||
() => ClubPlayerChange(club, clubPlayer)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加入竞技比赛数据处理
|
||||
/// </summary>
|
||||
/// <param name="club"></param>
|
||||
/// <param name="clubPlayer"></param>
|
||||
public static void ClubPlayerChange(Club_Base club, ClubPlayer clubPlayer)
|
||||
{
|
||||
//保存竞技比赛数据以及玩家数据
|
||||
var spp = GameDB.Instance.BeginTransaction(dbbase.game2018);
|
||||
string sql = string.Format("update Top(1) {0} set {1} = {2}, {3}=@mans where {4} = {5};" //更改竞技比赛
|
||||
, tb_clubs, fd_manCnt, club.mancnt, fd_mans, fd_id, club.id - idIncrement);
|
||||
|
||||
var ids = ArrayTotr_clubMans(club.mansid);
|
||||
byte[] bts = BinaryConvert.StructToBytes(ids);
|
||||
List<ISqlAloneParameter<SqlDbType>> sqlpms = new List<ISqlAloneParameter<SqlDbType>>();
|
||||
sqlpms.Add(new SqlAloneParameter("@mans", bts, bts.Length));
|
||||
GameDB.Instance.TransactionAddSql(spp, sql, sqlpms);
|
||||
|
||||
sql = string.Format("update Top(1) {0} set {1} = @joinclub,{4}=@joinclubnew where {2} = {3};",
|
||||
tb_players, fd_joinclubinfo, fd_userid2018, clubPlayer.userid, fd_joinclubinfodata);
|
||||
|
||||
var clubsinfo = ListPlayerofClubTotr_clubsOfPlayer(clubPlayer.joinClubs);
|
||||
bts = BinaryConvert.StructToBytes(clubsinfo);
|
||||
var strJoin = JsonPack.GetJson(clubPlayer.joinClubs);
|
||||
sqlpms = new List<ISqlAloneParameter<SqlDbType>>();
|
||||
sqlpms.Add(new SqlAloneParameter("joinclub", bts, bts.Length));
|
||||
sqlpms.Add(new SqlAloneParameter("joinclubnew", strJoin, strJoin.Length, SqlDbType.Text));
|
||||
GameDB.Instance.TransactionAddSql(spp, sql, sqlpms);
|
||||
|
||||
if (!GameDB.Instance.SubTransaction(spp))
|
||||
throw spp.exception;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存玩法
|
||||
/// </summary>
|
||||
/// <param name="clubid"></param>
|
||||
/// <param name="ways"></param>
|
||||
static void SavePlayWay(int clubid, string ways)
|
||||
{
|
||||
string sql = string.Format("update Top(1) {0} set {1}={2},{3}=@way where {4}={5};",
|
||||
tb_clubs, fd_wayVer, Club_Base.allServerVer, fd_newways, fd_id, clubid - idIncrement);
|
||||
|
||||
//List<ISqlAloneParameter<SqlDbType>> sqlpms = new List<ISqlAloneParameter<SqlDbType>>();
|
||||
//sqlpms.Add(new SqlAloneParameter("@way", ways, ways.Length, SqlDbType.Text));
|
||||
|
||||
GameDB.Instance.ExceSql(dbbase.game2018, sql, new SqlParameter[] { new SqlParameter("@way", SqlDbType.Text, ways.Length) { Value = ways } });
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存玩法
|
||||
/// </summary>
|
||||
/// <param name="club"></param>
|
||||
public static void SavePlayWay(Club_Base club)
|
||||
{
|
||||
int clubid = club.id;
|
||||
string ways = JsonPack.GetJson(club.ways);
|
||||
|
||||
SavePlayWay(clubid, ways);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存玩法_异步操作
|
||||
/// </summary>
|
||||
/// <param name="club"></param>
|
||||
public static void SavePlayWayAysn(Club_Base club)
|
||||
{
|
||||
int clubid = club.id;
|
||||
string ways = JsonPack.GetJson(club.ways);
|
||||
|
||||
Task.Factory.StartNew(
|
||||
() => SavePlayWay(clubid, ways)
|
||||
);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 分页查询
|
||||
/// </summary>
|
||||
public static List<FightScore> GetFightScoresByPage(int clubId, DateTime startDateTime, DateTime endDateTime,
|
||||
int pageSize, int pageIndex)
|
||||
{
|
||||
var sqlclubId = clubId - ClubDataManager.idIncrement;
|
||||
string subSql = "(SELECT ROW_NUMBER() OVER (ORDER BY id ASC) AS rownumber, * FROM club_FightRecord";
|
||||
subSql += $" WHERE clubid={sqlclubId} AND endtime BETWEEN '{startDateTime}' and '{endDateTime}')";
|
||||
string sql = $"SELECT TOP {pageSize} * FROM {subSql} AS temp_row WHERE rownumber > {pageSize * pageIndex}";
|
||||
Debug.Info($"sql:{sql}");
|
||||
return GetFightScoreBySql(sql, sqlclubId);
|
||||
}
|
||||
|
||||
private static List<FightScore> GetFightScoreBySql(string sql,int clubId=0)
|
||||
{
|
||||
List<FightScore> fights = new List<FightScore>();
|
||||
DataSet ds = new DataSet();
|
||||
GameDB.Instance.ExceSql(dbbase.game2018, sql, null, ds);
|
||||
if (ds.Tables == null || ds.Tables.Count == 0)
|
||||
{
|
||||
//没有记录
|
||||
return fights;
|
||||
}
|
||||
DataTable dt = ds.Tables[0];
|
||||
if (dt.Rows != null && dt.Rows.Count > 0)
|
||||
{
|
||||
int len = dt.Rows.Count;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
fights.Add(GetFightScore(clubId, dt.Rows[i]));
|
||||
}
|
||||
}
|
||||
return fights;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取某个俱乐部的某个玩法的前多少条战斗记录
|
||||
/// </summary>
|
||||
/// <param name="clubid">界面显示的俱乐部ID</param>
|
||||
/// <param name="wayId">玩法ID</param>
|
||||
/// <param name="top">前多少条</param>
|
||||
/// <returns></returns>
|
||||
public static List<FightScore> GetFightScoreByWayId(int clubid,string wayId,int top = 100)
|
||||
{
|
||||
var sql = $"select top {top} * from club_FightRecord where clubid = {clubid- idIncrement} and wayid='{wayId}' order by id desc";
|
||||
return GetFightScoreBySql(sql);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加载战斗记录
|
||||
/// </summary>
|
||||
/// <param name="clubid"></param>
|
||||
/// <param name="weiyima"></param>
|
||||
/// <returns></returns>
|
||||
public static FightScore LoadFightScore(int clubid, string weiyima)
|
||||
{
|
||||
DataTable dt = GameDB.Instance.selectDb(dbbase.game2018, tb_ClubFightRecord, null, string.Format("clubid={0} and weiyima='{1}'", clubid - idIncrement, weiyima));
|
||||
if (dt.Rows != null && dt.Rows.Count > 0)
|
||||
{
|
||||
return GetFightScore(clubid, dt.Rows[0]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据id获取战绩记录
|
||||
/// </summary>
|
||||
/// <param name="id"></param>
|
||||
/// <returns></returns>
|
||||
public static FightScore GetFightScoreById(int id)
|
||||
{
|
||||
DataTable dt = GameDB.Instance.selectDb(dbbase.game2018, tb_ClubFightRecord, null, string.Format("id={0}", id));
|
||||
if (dt.Rows != null && dt.Rows.Count > 0)
|
||||
{
|
||||
return GetFightScore(-1, dt.Rows[0]);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取战斗记录
|
||||
/// </summary>
|
||||
/// <param name="row"></param>
|
||||
/// <returns></returns>
|
||||
public static FightScore GetFightScore(int clubid, DataRow row)
|
||||
{
|
||||
FightScore fs = new FightScore();
|
||||
fs.clubid = clubid > 0 ? clubid : (idIncrement + (int)row["clubid"]);
|
||||
fs.id = (int)row[fd_id];
|
||||
fs.roomnum = (int)row[fd_roomnum];
|
||||
fs.warCnt = (int)row[fd_warcnt];
|
||||
fs.wayid = row[fd_wayid].ToString(); //未使用
|
||||
fs.game_serid = (int)row[fd_gameserid];
|
||||
fs.weiyima = row[fd_weiyima].ToString();
|
||||
string json = row[fd_scores].ToString();
|
||||
fs.scores = JsonPack.GetData<FightScore.Player[]>(json);
|
||||
fs.startTime = DateTime.Parse(row[fd_startTime].ToString());
|
||||
fs.endTime = DateTime.Parse(row[fd_endTime].ToString());
|
||||
if (row["CardNum"] != DBNull.Value)
|
||||
{
|
||||
fs.CardNum = (int)row["CardNum"];
|
||||
}
|
||||
if (row["style"] != DBNull.Value)
|
||||
{
|
||||
fs.Style = (short)row["style"];
|
||||
}
|
||||
if (row["disUserId"] != DBNull.Value)
|
||||
{
|
||||
fs.DisUserId = (int)row["disUserId"];
|
||||
}
|
||||
//if (row["playclub"] != DBNull.Value)
|
||||
//{
|
||||
// string strp = row["playclub"].ToString();
|
||||
// if (!string.IsNullOrEmpty(strp) && strp.Length > 2)
|
||||
// {
|
||||
// if (strp.IndexOf("Name") >= 0)
|
||||
// {
|
||||
// fs.PlayInClubInfo = JsonPack.GetData<Dictionary<int, IdName>>(strp);
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// fs.PlayInClub = JsonPack.GetData<Dictionary<int, int>>(strp);
|
||||
// }
|
||||
// }
|
||||
//}
|
||||
return fs;
|
||||
}
|
||||
|
||||
static string GetHidesKey(int clubid)
|
||||
{
|
||||
return $"HidesWay:{clubid}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存俱乐部隐藏玩法
|
||||
/// </summary>
|
||||
/// <param name="clubId"></param>
|
||||
/// <param name="list"></param>
|
||||
public static void SaveHideWays(int clubId, List<string> list,bool isSync = false)
|
||||
{
|
||||
if (clubId <= 0 || list == null) return;
|
||||
var key = GetHidesKey(clubId);
|
||||
var str = JsonPack.GetJson(list);
|
||||
|
||||
Debug.Info($"保存隐藏:{clubId}{str}");
|
||||
if (isSync)
|
||||
{
|
||||
redisManager.GetBiSaidb(6).StringSetAsync(key, str);
|
||||
}
|
||||
else
|
||||
{
|
||||
redisManager.GetBiSaidb(6).StringSet(key, str);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除隐藏玩法
|
||||
/// </summary>
|
||||
public static void RemoveHideWays(int clubId)
|
||||
{
|
||||
var key = GetHidesKey(clubId);
|
||||
redisManager.GetBiSaidb(6).KeyDelete(key);
|
||||
}
|
||||
|
||||
public static Task<List<string>> GetHidesAsync(int clubId)
|
||||
{
|
||||
return Task.Run(() => GetHides(clubId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 读取俱乐部隐藏玩法
|
||||
/// </summary>
|
||||
/// <param name="clubid"></param>
|
||||
/// <returns></returns>
|
||||
public static List<string> GetHides(int clubid)
|
||||
{
|
||||
if (clubid <= 0) return new List<string>();
|
||||
var key = GetHidesKey(clubid);
|
||||
string str = redisManager.GetBiSaidb(6).StringGet(key);
|
||||
if (!string.IsNullOrWhiteSpace(str) && str.Length > 2)
|
||||
{
|
||||
Debug.Info($"读取隐藏:{clubid}{str}");
|
||||
return JsonPack.GetData<List<string>>(str);
|
||||
}
|
||||
else
|
||||
{
|
||||
return new List<string>();
|
||||
}
|
||||
}
|
||||
|
||||
static string GetPlayerHideWayKey(int clubId)
|
||||
{
|
||||
return $"GetPlayerHideWayKey:{clubId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存玩家不能玩哪些玩法
|
||||
/// </summary>
|
||||
/// <param name="clubId"></param>
|
||||
/// <param name="data"></param>
|
||||
public static void SavePlayerHideWay(int clubId, Dictionary<int, List<string>> data)
|
||||
{
|
||||
if (clubId <= 0 || data == null) return;
|
||||
var key = GetPlayerHideWayKey(clubId);
|
||||
var str = JsonPack.GetJson(data);
|
||||
redisManager.GetBiSaidb(6).StringSet(key, str);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取玩家不能玩哪些玩法
|
||||
/// </summary>
|
||||
/// <param name="clubId"></param>
|
||||
/// <returns></returns>
|
||||
public static Dictionary<int, List<string>> GetPlayerHideWay(int clubId)
|
||||
{
|
||||
if (clubId <= 0) return new Dictionary<int, List<string>>();
|
||||
var key = GetPlayerHideWayKey(clubId);
|
||||
string str = redisManager.GetBiSaidb(6).StringGet(key);
|
||||
if (!string.IsNullOrWhiteSpace(str) && str.Length > 2)
|
||||
{
|
||||
return JsonPack.GetData<Dictionary<int, List<string>>>(str);
|
||||
}
|
||||
else
|
||||
{
|
||||
return new Dictionary<int, List<string>>();
|
||||
}
|
||||
}
|
||||
|
||||
static string GetClubFightRecordKey()
|
||||
{
|
||||
return "GetClubFightRecordKey";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 游戏报错战斗结束数据到reids,俱乐部服务器去redis里面去拿
|
||||
/// </summary>
|
||||
/// <param name="jsonData"></param>
|
||||
/// <returns>true保存成功 false保存失败</returns>
|
||||
public static bool SaveClubFightRecord(string jsonData)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(jsonData)) return true;
|
||||
try
|
||||
{
|
||||
redisManager.Getdb(9).ListRightPush(GetClubFightRecordKey(), jsonData); //从尾部添加
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error($"保存战绩数据失败,msg:{e.Message},code:{e.StackTrace}");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static string GetOneClubFightRecord()
|
||||
{
|
||||
return redisManager.Getdb(9).ListLeftPop(GetClubFightRecordKey()); //从头部取
|
||||
}
|
||||
}
|
||||
}
|
||||
330
GameDAL/Club/ClubLeagueMatchAdo.cs
Normal file
330
GameDAL/Club/ClubLeagueMatchAdo.cs
Normal file
@ -0,0 +1,330 @@
|
||||
using ObjectModel.Club;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using GameDAL.Game;
|
||||
using MrWu.DB;
|
||||
using MrWu.Debug;
|
||||
using Server.DB.Sql;
|
||||
|
||||
namespace GameDAL.Club
|
||||
{
|
||||
/// <summary>
|
||||
/// 俱乐部联赛数据逻辑
|
||||
/// </summary>
|
||||
public static class ClubLeagueMatchAdo
|
||||
{
|
||||
public static readonly dbbase sqldb = dbbase.game2018;
|
||||
public static readonly string tb_JoinInClubLeagueMatch = "JoinInClubLeagueMatch";
|
||||
public static readonly string tb_LeagueAwardRecord = "LeagueAwardRecord";
|
||||
public static readonly string tb_LeagueClubLeaguePower = "LeagueClubLeaguePower";
|
||||
public static readonly string tb_LeagueClubLiveTask = "LeagueClubLiveTask";
|
||||
public static readonly string tb_LeagueMatchBanDesk = "LeagueMatchBanDesk";
|
||||
public static readonly string tb_LeagueMatchClubScore = "LeagueMatchClubScore";
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取俱乐部权限 异步的
|
||||
/// </summary>
|
||||
/// <param name="clubId"></param>
|
||||
/// <returns></returns>
|
||||
public static Task<ClubLeaguePower> GetClubLeaguePowerAsync(int clubId)
|
||||
{
|
||||
return Task.Run(() => GetClubLeaguePower(clubId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取俱乐部权限
|
||||
/// </summary>
|
||||
/// <param name="clubId"></param>
|
||||
/// <returns></returns>
|
||||
public static ClubLeaguePower GetClubLeaguePower(int clubId)
|
||||
{
|
||||
var sql = $"select top 1 * from {tb_LeagueClubLeaguePower} where clubId = {clubId}";
|
||||
return sqldb.ExecuteEntities(sql, p => p.ToObject<ClubLeaguePower>()).FirstOrDefault();
|
||||
}
|
||||
|
||||
public static bool SaveClubLeaguePower(ClubLeaguePower model)
|
||||
{
|
||||
var sql = new StringBuilder();
|
||||
if (model.ClubLeaguePowerId < 1)
|
||||
{
|
||||
sql.Append(
|
||||
$"insert into {tb_LeagueClubLeaguePower}({nameof(model.ClubId)},{nameof(model.IsCanCreate)},{nameof(model.IsCanJoin)}) ");
|
||||
sql.Append($"values({model.ClubId},{model.IsCanCreate.SQLValue()},{model.IsCanJoin.SQLValue()})");
|
||||
sql.AppendLine($"if @@rowcount > 0 begin");
|
||||
sql.AppendLine(
|
||||
$" select top 1 {nameof(model.ClubLeaguePowerId)} from {tb_LeagueClubLeaguePower} where {nameof(model.ClubLeaguePowerId)} = SCOPE_IDENTITY()");
|
||||
sql.AppendLine("end");
|
||||
var result = sqldb.ExecuteScalar(sql.ToString());
|
||||
model.ClubLeaguePowerId = result is int id ? id : throw new Exception("增加记录失败, sql:" + sql);
|
||||
}
|
||||
else
|
||||
{
|
||||
sql.Append($"update {tb_LeagueClubLeaguePower} set ");
|
||||
sql.Append($"{nameof(model.ClubId)} = {model.ClubId},");
|
||||
sql.Append($"{nameof(model.IsCanCreate)} = {model.IsCanCreate.SQLValue()},");
|
||||
sql.Append($"{nameof(model.IsCanJoin)} = {model.IsCanJoin.SQLValue()}");
|
||||
sql.Append($" where {nameof(model.ClubLeaguePowerId)} = {model.ClubLeaguePowerId}");
|
||||
if (1 != sqldb.ExecuteNonQuery(sql.ToString()))
|
||||
{
|
||||
throw new Exception("更新记录失败,sql: " + sql);
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存联赛禁桌数据,每次删除数据在保存。根据ClubMatchId 删除
|
||||
/// </summary>
|
||||
/// <param name="list"></param>
|
||||
public static bool SaveBanDesks(List<LeagueMatchBanDesk> list, int clubMatchId)
|
||||
{
|
||||
return sqldb.ExecuteTransaction(false, t =>
|
||||
{
|
||||
//var todeleteItems = list.Select(p => clubMatchId).Distinct().Where(p => p > 0).ToArray();
|
||||
//if (todeleteItems.Length > 0) {
|
||||
var deleteSql = $"delete {tb_LeagueMatchBanDesk} where ClubMatchId = {clubMatchId}";
|
||||
var deletedCount = t.ExecuteNonQuery(deleteSql);
|
||||
if (deletedCount > 0)
|
||||
{
|
||||
Console.WriteLine("SaveBanDesks delete count:" + deletedCount);
|
||||
}
|
||||
|
||||
//}
|
||||
var sql = new StringBuilder();
|
||||
foreach (var p in list)
|
||||
{
|
||||
sql.Append(
|
||||
$"insert into {tb_LeagueMatchBanDesk}(ClubMatchId,{nameof(p.WayId)},{nameof(p.JSONString)}) ");
|
||||
sql.AppendLine($"values({clubMatchId}, @wayId, @json)");
|
||||
sql.AppendLine($"if @@rowcount > 0 begin");
|
||||
sql.AppendLine(
|
||||
$" select top 1 {nameof(p.LeagueMatchBanDeskId)} from {tb_LeagueMatchBanDesk} where {nameof(p.LeagueMatchBanDeskId)} = SCOPE_IDENTITY()");
|
||||
sql.AppendLine("end");
|
||||
var result = t.ExecuteScalar(sql.ToString(), new SqlParameter("@wayId", p.WayId),
|
||||
new SqlParameter("@json", p.GetClubsToString()));
|
||||
p.LeagueMatchBanDeskId = result is int id ? id : throw new Exception("增加记录失败, sql:" + sql);
|
||||
sql.Clear();
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取联赛禁桌数据
|
||||
/// </summary>
|
||||
/// <param name="clubMatchId"></param>
|
||||
/// <returns></returns>
|
||||
public static List<LeagueMatchBanDesk> GetLeagueMatchBanDesks(int clubMatchId)
|
||||
{
|
||||
var sql = $"select * from {tb_LeagueMatchBanDesk} where ClubMatchId = {clubMatchId}";
|
||||
return sqldb.ExecuteEntities(sql, p =>
|
||||
{
|
||||
var model = p.ToObject<LeagueMatchBanDesk>();
|
||||
model.ClubIds = model.GetClubIdsByJSON();
|
||||
return model;
|
||||
}).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存联赛俱乐部统计数据,每次删除数据在保存。根据ClubMatchId 删除
|
||||
/// </summary>
|
||||
/// <param name="list"></param>
|
||||
public static bool SaveLeagueMatchClubScore(List<LeagueMatchClubScore> list, int matchId)
|
||||
{
|
||||
return sqldb.ExecuteTransaction(false, t =>
|
||||
{
|
||||
var deleteSql =
|
||||
$"delete {tb_LeagueMatchClubScore} where ClubMatchId = {matchId}";
|
||||
var deletedCount = t.ExecuteNonQuery(deleteSql);
|
||||
if (deletedCount > 0)
|
||||
{
|
||||
Console.WriteLine("SaveLeagueMatchClubScore delete count:" + deletedCount);
|
||||
}
|
||||
|
||||
var sql = new StringBuilder();
|
||||
foreach (var p in list)
|
||||
{
|
||||
sql.Append(
|
||||
$"insert into {tb_LeagueMatchClubScore}(ClubMatchId,{nameof(p.ClubName)},{nameof(p.ClubId)},{nameof(p.CardScore)},{nameof(p.DeskScore)},{nameof(p.ClubUserSumScore)},{nameof(p.JoinRoom)},[Index],{nameof(p.LeagueScore)}) ");
|
||||
sql.AppendLine(
|
||||
$"values({matchId}, @clubName,{p.ClubId},{p.CardScore},{p.DeskScore},{p.ClubUserSumScore},{p.JoinRoom},0,@score)");
|
||||
sql.AppendLine($"if @@rowcount > 0 begin");
|
||||
sql.AppendLine(
|
||||
$" select top 1 {nameof(p.LeagueMatchClubScoreId)} from {tb_LeagueMatchClubScore} where {nameof(p.LeagueMatchClubScoreId)} = SCOPE_IDENTITY()");
|
||||
sql.AppendLine("end");
|
||||
var result = t.ExecuteScalar(sql.ToString(), new SqlParameter("@clubName", p.ClubName),
|
||||
new SqlParameter("@score", p.LeagueScore));
|
||||
p.LeagueMatchClubScoreId = result is int id ? id : throw new Exception("增加记录失败, sql:" + sql);
|
||||
sql.Clear();
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取联赛俱乐部统计数据,过期时间7天
|
||||
/// </summary>
|
||||
/// <param name="clubMatchId"></param>
|
||||
/// <returns></returns>
|
||||
public static List<LeagueMatchClubScore> GetLeagueMatchClubScores(int clubMatchId)
|
||||
{
|
||||
var sql = $"select * from {tb_LeagueMatchClubScore} where clubMatchId = {clubMatchId}";
|
||||
return sqldb.ExecuteEntities(sql, p => p.ToObject<LeagueMatchClubScore>()).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存联赛颁奖记录,清空对应clubMatchId比赛的缓存(每次都是新的数据,不用做删除操作)
|
||||
/// </summary>
|
||||
/// <param name="mode"></param>
|
||||
public static bool SaveAwardRecord(List<AwardRecord> list)
|
||||
{
|
||||
return sqldb.ExecuteTransaction(false, t =>
|
||||
{
|
||||
var sql = new StringBuilder();
|
||||
foreach (var p in list)
|
||||
{
|
||||
sql.Append(
|
||||
$"insert into {tb_LeagueAwardRecord}({nameof(p.ClubMatchId)},{nameof(p.ClubName)},{nameof(p.ClubId)},{nameof(p.CardScore)},{nameof(p.DeskScore)},{nameof(p.ClubUserSumScore)},{nameof(p.JoinRoom)},[{nameof(p.Index)}],{nameof(p.RecordId)},{nameof(p.LeagueScore)}) ");
|
||||
sql.AppendLine(
|
||||
$"values({p.ClubMatchId}, @clubName,{p.ClubId},{p.CardScore},{p.DeskScore},{p.ClubUserSumScore},{p.JoinRoom},{p.Index},{p.RecordId},@score)");
|
||||
// sql.AppendLine($"if @@rowcount > 0 begin");
|
||||
// sql.AppendLine(
|
||||
// $" select top 1 {nameof(p.AwardRecordId)} from {tb_LeagueAwardRecord} where {nameof(p.AwardRecordId)} = SCOPE_IDENTITY()");
|
||||
// sql.AppendLine("end");
|
||||
var result = t.ExecuteScalar(sql.ToString(), new SqlParameter("@clubName", p.ClubName),
|
||||
new SqlParameter("@score", p.LeagueScore));
|
||||
//p.AwardRecordId = result is int id ? id : throw new Exception("增加记录失败, sql:" + sql);
|
||||
sql.Clear();
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取联赛颁奖记录 近几条
|
||||
/// </summary>
|
||||
/// <param name="clubMatchId"></param>
|
||||
/// <param name="topNum"></param>
|
||||
/// <returns></returns>
|
||||
public static AwardRecord GetAwardByTop(int clubMatchId, int topNum = 1)
|
||||
{
|
||||
var sql = $"select top 1 * from {tb_LeagueAwardRecord} where clubMatchId = {clubMatchId}";
|
||||
return sqldb.ExecuteEntities(sql, p => p.ToObject<AwardRecord>()).FirstOrDefault();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取联赛颁奖记录。根据主键id倒序
|
||||
/// </summary>
|
||||
/// <param name="clubMatchId">比赛Id</param>
|
||||
/// <param name="dateTime"> CreateTime>dateTime </param>
|
||||
/// <returns></returns>
|
||||
public static List<AwardRecord> GetAwardRecords(int clubMatchId, DateTime dateTime)
|
||||
{
|
||||
var sql =
|
||||
$"select * from {tb_LeagueAwardRecord} where clubMatchId = {clubMatchId} and CreateTime > @datetime";
|
||||
return sqldb.ExecuteEntities(sql, p => p.ToObject<AwardRecord>(), new SqlParameter("@datetime", dateTime))
|
||||
.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取联赛颁奖记录。根据主键id倒序,根据比赛:clubMatchId缓存 时间1天
|
||||
/// </summary>
|
||||
/// <param name="clubMatchId"></param>
|
||||
/// <returns></returns>
|
||||
public static List<AwardRecord> GetAwardRecords(int clubMatchId)
|
||||
{
|
||||
var sql = $"select * from {tb_LeagueAwardRecord} where clubMatchId = {clubMatchId}";
|
||||
return sqldb.ExecuteEntities(sql, p => p.ToObject<AwardRecord>()).ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存生存任务,先删除再保存
|
||||
/// </summary>
|
||||
/// <param name="lists"></param>
|
||||
public static bool SaveLeagueClubLiveTasks(List<LeagueClubLiveTask> list, int clubMatchId)
|
||||
{
|
||||
return sqldb.ExecuteTransaction(false, t =>
|
||||
{
|
||||
if (clubMatchId > 0)
|
||||
{
|
||||
var deleteSql = $"delete {tb_LeagueClubLiveTask} where ClubMatchId = {clubMatchId}";
|
||||
Debug.Info($"执行Sql语句{deleteSql}");
|
||||
var deletedCount = t.ExecuteNonQuery(deleteSql);
|
||||
if (deletedCount > 0)
|
||||
{
|
||||
Console.WriteLine("SaveLeagueClubLiveTasks delete count:" + deletedCount);
|
||||
}
|
||||
}
|
||||
|
||||
var sql = new StringBuilder();
|
||||
foreach (var p in list)
|
||||
{
|
||||
sql.Append(
|
||||
$"insert into {tb_LeagueClubLiveTask}(ClubMatchId,{nameof(p.ClubId)},{nameof(p.TaskScore)},{nameof(p.IsActive)}) ");
|
||||
sql.AppendLine($"values({clubMatchId}, {p.ClubId},{p.TaskScore},{p.IsActive.SQLValue()})");
|
||||
sql.AppendLine($"if @@rowcount > 0 begin");
|
||||
sql.AppendLine(
|
||||
$" select top 1 LeagueClubLiveTaskId from {tb_LeagueClubLiveTask} where LeagueClubLiveTaskId = SCOPE_IDENTITY()");
|
||||
sql.AppendLine("end");
|
||||
var result = t.ExecuteScalar(sql.ToString());
|
||||
p.LeagueClubLiveTaskId = result is int id ? id : throw new Exception("增加记录失败, sql:" + sql);
|
||||
sql.Clear();
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存加入到联赛的俱乐部集合
|
||||
/// </summary>
|
||||
/// <param name="model"></param>
|
||||
public static bool SaveJoinInClubLeagueMatch(JoinInClubLeagueMatch model)
|
||||
{
|
||||
Debug.Info($"保存加入联赛的俱乐部集合:{model.ClubMatchId} {model.GetJoinInLeagueMatchClubsToString()}");
|
||||
|
||||
var spp = GameDB.Instance.BeginTransaction(dbbase.game2018);
|
||||
|
||||
string sql =
|
||||
$@"if not exists (select 1 from {tb_JoinInClubLeagueMatch} where ClubMatchId = {model.ClubMatchId})
|
||||
insert into {tb_JoinInClubLeagueMatch}(ClubMatchId,JoinInLeagueMatchClubs) values ({model.ClubMatchId},@json)
|
||||
else
|
||||
update {tb_JoinInClubLeagueMatch} set JoinInLeagueMatchClubs=@json where ClubMatchId = {model.ClubMatchId}";
|
||||
List<ISqlAloneParameter<SqlDbType>> sqlpms = new List<ISqlAloneParameter<SqlDbType>>();
|
||||
sqlpms.Add(new SqlAloneParameter("@json", model.GetJoinInLeagueMatchClubsToString(),5000, SqlDbType.VarChar));
|
||||
GameDB.Instance.TransactionAddSql(spp, sql, sqlpms);
|
||||
|
||||
if (!GameDB.Instance.SubTransaction(spp))
|
||||
return false;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取 保存加入到联赛的俱乐部集合 对象
|
||||
/// </summary>
|
||||
/// <param name="clubMatchId"></param>
|
||||
/// <returns></returns>
|
||||
public static JoinInClubLeagueMatch GetJoinInClubLeagueMatch(int clubMatchId)
|
||||
{
|
||||
var sql = $"select top 1 * from {tb_JoinInClubLeagueMatch} where clubMatchId = {clubMatchId}";
|
||||
Debug.Info(sql);
|
||||
return sqldb.ExecuteEntities(sql, p =>
|
||||
{
|
||||
var model = p.ToObject<JoinInClubLeagueMatch>();
|
||||
model.ClubIds = model.GetClubIdsByJSON();
|
||||
return model;
|
||||
}).FirstOrDefault();
|
||||
}
|
||||
}
|
||||
}
|
||||
268
GameDAL/Club/ClubLeagueMatchDal.cs
Normal file
268
GameDAL/Club/ClubLeagueMatchDal.cs
Normal file
@ -0,0 +1,268 @@
|
||||
using GameData;
|
||||
using ObjectModel.Club;
|
||||
using Server.DB.Redis;
|
||||
using StackExchange.Redis;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using GameData.Club;
|
||||
|
||||
namespace GameDAL.Club
|
||||
{
|
||||
/// <summary>
|
||||
/// 俱乐部联赛数据逻辑
|
||||
/// </summary>
|
||||
public static class ClubLeagueMatchDal
|
||||
{
|
||||
|
||||
public static readonly string clubMatchKeyPrefix = "ClubLeagueMatch";
|
||||
public static readonly DbStyle redisdb = DbStyle.main;
|
||||
public static readonly int dbidx = 7;
|
||||
static TimeSpan expiry = TimeSpan.FromDays(1);
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 获取俱乐部权限
|
||||
/// </summary>
|
||||
/// <param name="clubId"></param>
|
||||
/// <returns></returns>
|
||||
public static ClubLeaguePower GetClubLeaguePower(int clubId)
|
||||
{
|
||||
if (clubId <= 0) return null;
|
||||
return ClubLeagueMatchAdo.GetClubLeaguePower(clubId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取俱乐部权限
|
||||
/// </summary>
|
||||
/// <param name="clubId"></param>
|
||||
/// <returns></returns>
|
||||
public static Task<ClubLeaguePower> GetClubLeaguePowerAsync(int clubId)
|
||||
{
|
||||
return ClubLeagueMatchAdo.GetClubLeaguePowerAsync(clubId);
|
||||
}
|
||||
|
||||
public static async Task<bool> SaveClubLeaguePowerAsync(ClubLeaguePower leaguePower)
|
||||
{
|
||||
return await Task.Run(()=>ClubLeagueMatchAdo.SaveClubLeaguePower(leaguePower));
|
||||
}
|
||||
|
||||
public static Task SaveBanDesksAsync(List<LeagueMatchBanDesk> list,int matchId)
|
||||
{
|
||||
return Task.Run(() => SaveBanDesks(list, matchId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存联赛禁桌数据,每次删除数据在保存。根据ClubMatchId 删除
|
||||
/// </summary>
|
||||
/// <param name="list"></param>
|
||||
public static void SaveBanDesks(List<LeagueMatchBanDesk> list,int matchId)
|
||||
{
|
||||
if (list == null || list.Count < 1) return;
|
||||
ClubLeagueMatchAdo.SaveBanDesks(list,matchId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取联赛禁桌数据
|
||||
/// </summary>
|
||||
/// <param name="clubMatchId"></param>
|
||||
/// <returns></returns>
|
||||
public static List<LeagueMatchBanDesk> GetLeagueMatchBanDesks(int clubMatchId)
|
||||
{
|
||||
if (clubMatchId <= 0) return null;
|
||||
return ClubLeagueMatchAdo.GetLeagueMatchBanDesks(clubMatchId);
|
||||
}
|
||||
|
||||
public static Task SaveLeagueMatchClubScoreAsync(List<LeagueMatchClubScore> list,int matchId)
|
||||
{
|
||||
return Task.Run(() => SaveLeagueMatchClubScore(list, matchId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存联赛俱乐部统计数据,每次删除数据在保存。根据ClubMatchId 删除
|
||||
/// </summary>
|
||||
/// <param name="list"></param>
|
||||
public static void SaveLeagueMatchClubScore(List<LeagueMatchClubScore> list,int matchId)
|
||||
{
|
||||
if (list == null || list.Count < 1) return;
|
||||
ClubLeagueMatchAdo.SaveLeagueMatchClubScore(list,matchId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取联赛俱乐部统计数据
|
||||
/// </summary>
|
||||
/// <param name="clubMatchId"></param>
|
||||
/// <returns></returns>
|
||||
public static List<LeagueMatchClubScore> GetLeagueMatchClubScores(int clubMatchId)
|
||||
{
|
||||
if (clubMatchId <= 0) return null;
|
||||
return ClubLeagueMatchAdo.GetLeagueMatchClubScores(clubMatchId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存联赛颁奖记录,清空对应clubMatchId比赛的缓存(每次都是新的数据,不用做删除操作)
|
||||
/// </summary>
|
||||
public static async Task<bool> SaveAwardRecord(long awardId, int leagueClubId, int leagueMatchId, List<AwardRecord> list)
|
||||
{
|
||||
if (list == null || list.Count < 1) return false;
|
||||
var b = await ClubDBUtil.DoLeagueAwardRecord(awardId, leagueClubId, leagueMatchId, list);
|
||||
if (b)
|
||||
{
|
||||
var clubMatchIds = list.Select(p => p.ClubMatchId).Distinct().ToArray();
|
||||
var keys1 = clubMatchIds.Select(p => GetAwardRecordListKey(p));
|
||||
var keys2 = clubMatchIds.Select(p => GetAwardRecordKey(p));
|
||||
var keys3 = clubMatchIds.Select(p => GetAwardRecordListByDateKey(p));
|
||||
_ = redisdb.DeleteAsync(dbidx, keys1.Concat(keys2).Concat(keys3).ToArray());
|
||||
}
|
||||
return b;
|
||||
}
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取联赛颁奖记录 近几条
|
||||
// /// </summary>
|
||||
// /// <param name="clubMatchId"></param>
|
||||
// /// <param name="topNum"></param>
|
||||
// /// <returns></returns>
|
||||
// public static AwardRecord GetAwardByTop(int clubMatchId, int topNum = 1)
|
||||
// {
|
||||
// if (clubMatchId <= 0) return null;
|
||||
// var result = redisdb.GetOrAdd(RedisType.String, GetAwardRecordKey(clubMatchId), () =>
|
||||
// {
|
||||
// return ClubLeagueMatchAdo.GetAwardByTop(clubMatchId, topNum) ?? new AwardRecord();
|
||||
// }, dbidx, expiry);
|
||||
// return result.AwardRecordId != 0 ? result : null;
|
||||
// }
|
||||
|
||||
#if Server
|
||||
/// <summary>
|
||||
/// 获取联赛颁奖记录。根据主键id倒序
|
||||
/// </summary>
|
||||
/// <param name="clubMatchId">比赛Id</param>
|
||||
/// <param name="dateTime"> CreateTime>dateTime </param>
|
||||
/// <returns></returns>
|
||||
public static List<AwardRecord> GetAwardRecords(int clubMatchId, DateTime dateTime)
|
||||
{
|
||||
if (clubMatchId <= 0) return null;
|
||||
return redisdb.GetOrAdd(GetAwardRecordListByDateKey(clubMatchId), dateTime.ToString("yyyyMMddHHmmss"), () =>
|
||||
ClubLeagueMatchAdo.GetAwardRecords(clubMatchId, dateTime)
|
||||
, dbidx, expiry);
|
||||
}
|
||||
|
||||
public static FightScore GetFightScorebyId(int id)
|
||||
{
|
||||
return DbStyle.bisai.GetOrAdd(RedisType.String, GetFightScoreByIdKey(id), () =>
|
||||
ClubDataManager.GetFightScoreById(id)
|
||||
, dbidx, TimeSpan.FromMinutes(30));
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
static RedisKey GetFightScoreByIdKey(int id)
|
||||
{
|
||||
return $"GetFightScores:id:{id}";
|
||||
}
|
||||
|
||||
static RedisKey GetAwardRecordListByDateKey(int clubMatchId)
|
||||
{
|
||||
return $"{clubMatchKeyPrefix}:AwardRecordListBydate:{clubMatchId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取联赛颁奖记录。根据主键id倒序,根据比赛:clubMatchId缓存 时间1天
|
||||
/// </summary>
|
||||
/// <param name="clubMatchId"></param>
|
||||
/// <returns></returns>
|
||||
public static List<AwardRecord> GetAwardRecords(int clubMatchId)
|
||||
{
|
||||
if (clubMatchId <= 0) return null;
|
||||
return redisdb.GetOrAdd(RedisType.String, GetAwardRecordListKey(clubMatchId),
|
||||
() => ClubLeagueMatchAdo.GetAwardRecords(clubMatchId)
|
||||
, dbidx, expiry);
|
||||
}
|
||||
|
||||
static RedisKey GetAwardRecordListKey(int clubMatchId)
|
||||
{
|
||||
return $"{clubMatchKeyPrefix}:AwardRecordList:{clubMatchId}";
|
||||
}
|
||||
|
||||
static RedisKey GetAwardRecordKey(int clubMatchId)
|
||||
{
|
||||
return $"{clubMatchKeyPrefix}:AwardRecord:{clubMatchId}";
|
||||
}
|
||||
|
||||
public static Task SaveLeagueClubLiveTasksAsync(List<LeagueClubLiveTask> list,int matchId)
|
||||
{
|
||||
return Task.Run(() => SaveLeagueClubLiveTasks(list, matchId));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存生存任务,先删除再保存
|
||||
/// </summary>
|
||||
/// <param name="lists"></param>
|
||||
public static void SaveLeagueClubLiveTasks(List<LeagueClubLiveTask> list,int matchId)
|
||||
{
|
||||
if (list == null || list.Count < 1) return;
|
||||
ClubLeagueMatchAdo.SaveLeagueClubLiveTasks(list,matchId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存加入到联赛的俱乐部集合
|
||||
/// </summary>
|
||||
/// <param name="model"></param>
|
||||
public static void SaveJoinInClubLeagueMatch(JoinInClubLeagueMatch model)
|
||||
{
|
||||
if (model == null) return;
|
||||
ClubLeagueMatchAdo.SaveJoinInClubLeagueMatch(model);
|
||||
}
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取 保存加入到联赛的俱乐部集合 对象
|
||||
// /// </summary>
|
||||
// /// <param name="clubMatchId"></param>
|
||||
// /// <returns></returns>
|
||||
// public static JoinInClubLeagueMatch GetJoinInClubLeagueMatch(int clubMatchId)
|
||||
// {
|
||||
// if (clubMatchId <= 0) return null;
|
||||
// return ClubLeagueMatchAdo.GetJoinInClubLeagueMatch(clubMatchId);
|
||||
// }
|
||||
|
||||
static string GetLeagueAdminClubsKey(int clubId)
|
||||
{
|
||||
return $"GetLeagueAdminClubsKey:{clubId}";
|
||||
}
|
||||
|
||||
#if Server
|
||||
/// <summary>
|
||||
/// 保存联赛俱乐部管理员
|
||||
/// </summary>
|
||||
public static void SaveLeagueAdminClubs(int clubId, List<LeagueAdminClub> data)
|
||||
{
|
||||
if (clubId <= 0 || data == null) return;
|
||||
var key = GetLeagueAdminClubsKey(clubId);
|
||||
var str = JsonPack.GetJson(data);
|
||||
redisManager.GetBiSaidb(6).StringSet(key, str, TimeSpan.FromDays(365)); //数据缓存一年
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取联赛管理员列表
|
||||
/// </summary>
|
||||
/// <param name="clubId"></param>
|
||||
/// <returns></returns>
|
||||
public static List<LeagueAdminClub> GetLeagueAdminClubs(int clubId)
|
||||
{
|
||||
var result = new List<LeagueAdminClub>();
|
||||
if (clubId <= 0) return result;
|
||||
var key = GetLeagueAdminClubsKey(clubId);
|
||||
string str = redisManager.GetBiSaidb(6).StringGet(key);
|
||||
if (!string.IsNullOrWhiteSpace(str) && str.Length > 2)
|
||||
{
|
||||
return JsonPack.GetData<List<LeagueAdminClub>>(str);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
#endif
|
||||
}
|
||||
}
|
||||
459
GameDAL/Club/ClubMatchManagerAdo.cs
Normal file
459
GameDAL/Club/ClubMatchManagerAdo.cs
Normal file
@ -0,0 +1,459 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using GameData;
|
||||
using ObjectModel.Club;
|
||||
using MrWu;
|
||||
using MrWu.Debug;
|
||||
using Server.DB.Sql;
|
||||
using GameData.Club;
|
||||
|
||||
/// <summary>
|
||||
/// 竞技比赛统计数据存取
|
||||
/// </summary>
|
||||
public static class ClubMatchManagerAdo {
|
||||
|
||||
public const dbbase sqldb = dbbase.game2018;
|
||||
public static readonly string tb_ClubMatch = "ClubMatch";
|
||||
public static readonly string tb_ClubMatchNotes = "ClubMatchNotes";
|
||||
public static readonly string tb_ClubMatchPlayWay = "ClubMatchPlayWay";
|
||||
public static readonly string tb_ClubMatchScoreNotes = "ClubMatchScoreNotes";
|
||||
public static readonly string tb_ClubMatchUserScore = "ClubMatchUserScore";
|
||||
public static readonly string tb_ClubMatchPlayWayMaxWinnerScoreRange = "ClubMatchPlayWayMaxWinnerScoreRange";
|
||||
|
||||
public static bool DeleteMatchPlayWayById(int id)
|
||||
{
|
||||
if (id <= 0) return false;
|
||||
var sql = " DELETE from ClubMatchPlayWay where MatchPlayWayId = @id";
|
||||
return sqldb.ExecuteTransaction(t => {
|
||||
|
||||
var succ = t.ExecuteNonQuery(sql, new SqlParameter[]{
|
||||
new SqlParameter("@id",id)
|
||||
}) == 1;
|
||||
if (!succ)
|
||||
{
|
||||
throw new Exception("DELETE ClubMatchPlayWay 记录失败!" + sql);
|
||||
}
|
||||
return succ;
|
||||
});
|
||||
}
|
||||
|
||||
//这里需要加个新表
|
||||
|
||||
public static ClubMatch GetClubMatchByClubId(int clubId, out List<ClubMatchUserScore> list, int statusFlag = 1) {
|
||||
var statusFlagWhere = statusFlag >= 0 ? $"and statusFlag = {statusFlag} " : string.Empty;
|
||||
list = null;
|
||||
var sql = new StringBuilder();
|
||||
|
||||
//查询比赛 比赛表 连接 玩法表 以及比赛规则 找的是最后一条数据
|
||||
sql.AppendLine($"select p1.*, p2.*, p3.* from");//比赛与玩法及子项,
|
||||
sql.AppendLine($" (select top(1) * from {tb_ClubMatch} where clubId = {clubId} {statusFlagWhere} order by ClubMatchId desc) as p1");
|
||||
sql.AppendLine($"left join {tb_ClubMatchPlayWay} as p2");
|
||||
sql.AppendLine($"on p1.ClubMatchId = p2.ClubMatchId");
|
||||
sql.AppendLine($"left join {tb_ClubMatchPlayWayMaxWinnerScoreRange} as p3");
|
||||
sql.AppendLine($"on p2.MatchPlayWayId = p3.MatchPlayWayId");
|
||||
sql.AppendLine($"order by p1.ClubMatchId desc, p2.MatchPlayWayId desc");
|
||||
|
||||
sql.AppendLine($"select p2.* from");//参加比赛的玩家分数
|
||||
sql.AppendLine($" (select top(1) * from {tb_ClubMatch} where clubId = {clubId} {statusFlagWhere} order by ClubMatchId desc) as p1");
|
||||
sql.AppendLine($"left join {tb_ClubMatchUserScore} as p2");
|
||||
sql.AppendLine($"on p1.ClubMatchId = p2.ClubMatchId");
|
||||
sql.AppendLine($"where p2.ClubMatchId > 0");
|
||||
sql.AppendLine($"order by p2.UserScoreId desc");
|
||||
|
||||
var tabs = sqldb.ExecuteTables(sql.ToString());
|
||||
if (tabs.Length > 0 && tabs[0].Rows.Count > 0) {
|
||||
var clubMatchs = tabs[0].GetClubMatche();
|
||||
|
||||
list = new List<ClubMatchUserScore>();
|
||||
if (tabs.Length > 1 && tabs[1].Rows.Count > 0) {
|
||||
foreach (DataRow row in tabs[1].Rows) {
|
||||
var score = row.ToObject<ClubMatchUserScore>();
|
||||
list.Add(score);
|
||||
}
|
||||
}
|
||||
return clubMatchs.Single();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
public static bool SaveClubMatch(ClubMatch model) {
|
||||
|
||||
Debug.Info($"保存比赛数据:{model.ClubId},{model.StatusFlag},{model.ClubMatchId}");
|
||||
|
||||
if (model.ClubMatchId == 0) {
|
||||
return AddClubMatch(model);
|
||||
} else {
|
||||
return UpdateClubMatch(model);
|
||||
}
|
||||
}
|
||||
|
||||
public static bool AddClubMatch(ClubMatch model) {
|
||||
var sql = new StringBuilder();
|
||||
sql.Append($"insert into {tb_ClubMatch}(");
|
||||
sql.Append($"clubid,ClubMatchName,MatchStartTime,MatchEndTime,DieOutNum,StatusFlag,AutoOpen,HowTopUser,Round,MatchRate,VisibleDesk,isOnlyVisibleMyClub,isVisibleScoreBak,isScoreReset,JsonData) ");
|
||||
sql.AppendLine($"values({model.ClubId},@ClubMatchName,@MatchStartTime,@MatchEndTime,{model.DieOutNum},{model.StatusFlag},{model.AutoOpen.SQLValue()},{model.HowTopUser},{model.Round},{model.MatchRate},{model.VisibleDesk},{model.isOnlyVisibleMyClub},{model.isVisibleScoreBak},{model.isScoreReset},@JsonData)");
|
||||
sql.AppendLine($"select cast(SCOPE_IDENTITY() as int)");
|
||||
return sqldb.ExecuteTransaction(t => {
|
||||
var result = t.ExecuteScalar(sql.ToString(), new SqlParameter[]{
|
||||
new SqlParameter("@ClubMatchName",model.ClubMatchName),
|
||||
new SqlParameter("@MatchStartTime", model.MatchStartTime),
|
||||
new SqlParameter("@MatchEndTime",model.MatchEndTime),
|
||||
new SqlParameter("@JsonData",model.GetJsonData())
|
||||
});
|
||||
if (result is int id) {
|
||||
model.ClubMatchId = id;
|
||||
} else {
|
||||
throw new Exception("AddClubMatch 增加新记录失败!" + sql);
|
||||
}
|
||||
|
||||
if (model.LeagueClubMatch == null) //只有创建比赛的俱乐部才需要保存玩法信息
|
||||
{
|
||||
if (model.MatchPlayWays != null && model.MatchPlayWays.Count > 0) {
|
||||
foreach (var way in model.MatchPlayWays) {
|
||||
AddOrUpdateClubMatchPlayWay(t, way, model.ClubMatchId);
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
public static bool UpdateClubMatch(ClubMatch model) {
|
||||
return sqldb.ExecuteTransaction(t => {
|
||||
var sql = new StringBuilder();
|
||||
sql.Append($"update {tb_ClubMatch} set ");
|
||||
sql.Append($"ClubMatchName = @ClubMatchName,");
|
||||
sql.Append($"MatchStartTime = @MatchStartTime,");
|
||||
sql.Append($"MatchEndTime = @MatchEndTime,");
|
||||
sql.Append($"JsonData = @JsonData,");
|
||||
sql.Append($"DieOutNum = {model.DieOutNum},");
|
||||
sql.Append($"StatusFlag = {model.StatusFlag},");
|
||||
sql.Append($"AutoOpen = {model.AutoOpen.SQLValue()},");
|
||||
sql.Append($"HowTopUser = {model.HowTopUser},");
|
||||
sql.Append($"Round = {model.Round},");
|
||||
sql.Append($"isOnlyVisibleMyClub = {model.isOnlyVisibleMyClub},");
|
||||
sql.Append($"VisibleDesk = {model.VisibleDesk},");
|
||||
sql.Append($"MatchRate = {model.MatchRate},");
|
||||
sql.Append($"isVisibleScoreBak={model.isVisibleScoreBak},");
|
||||
sql.Append($"isScoreReset={model.isScoreReset} ");
|
||||
sql.Append($"where ClubMatchId = {model.ClubMatchId}");
|
||||
|
||||
var succ = t.ExecuteNonQuery(sql.ToString(), new SqlParameter[]{
|
||||
new SqlParameter("@ClubMatchName",model.ClubMatchName),
|
||||
new SqlParameter("@MatchStartTime", model.MatchStartTime),
|
||||
new SqlParameter("@MatchEndTime",model.MatchEndTime),
|
||||
new SqlParameter("@JsonData",model.GetJsonData())
|
||||
}) == 1;
|
||||
if (!succ) {
|
||||
throw new Exception("UpdateClubMatch 更新记录失败!" + sql);
|
||||
}
|
||||
|
||||
if (model.LeagueClubMatch == null)
|
||||
{
|
||||
if (model.MatchPlayWays != null && model.MatchPlayWays.Count > 0) {
|
||||
foreach (var way in model.MatchPlayWays) {
|
||||
AddOrUpdateClubMatchPlayWay(t, way, model.ClubMatchId);
|
||||
}
|
||||
}
|
||||
}
|
||||
return succ;
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只更新ClubMatchModel
|
||||
/// </summary>
|
||||
/// <param name="model"></param>
|
||||
/// <returns></returns>
|
||||
public static bool UpdateClubMatchModel(ClubMatch model) {
|
||||
return sqldb.ExecuteTransaction(t => {
|
||||
var sql = new StringBuilder();
|
||||
sql.Append($"update {tb_ClubMatch} set ");
|
||||
sql.Append($"ClubMatchName = @ClubMatchName,");
|
||||
sql.Append($"MatchStartTime = @MatchStartTime,");
|
||||
sql.Append($"MatchEndTime = @MatchEndTime,");
|
||||
sql.Append($"DieOutNum = {model.DieOutNum},");
|
||||
sql.Append($"StatusFlag = {model.StatusFlag},");
|
||||
sql.Append($"AutoOpen = {model.AutoOpen.SQLValue()},");
|
||||
sql.Append($"HowTopUser = {model.HowTopUser},");
|
||||
sql.Append($"Round = {model.Round},");
|
||||
sql.Append($"MatchRate = {model.MatchRate} ");
|
||||
sql.Append($"where ClubMatchId = {model.ClubMatchId}");
|
||||
|
||||
var succ = t.ExecuteNonQuery(sql.ToString(), new SqlParameter[]{
|
||||
new SqlParameter("@ClubMatchName",model.ClubMatchName),
|
||||
new SqlParameter("@MatchStartTime", model.MatchStartTime),
|
||||
new SqlParameter("@MatchEndTime",model.MatchEndTime)
|
||||
}) == 1;
|
||||
if (!succ) {
|
||||
throw new Exception("UpdateClubMatch 更新记录失败!" + sql);
|
||||
}
|
||||
return succ;
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
public static void AddOrUpdateClubMatchPlayWay(SqlTransaction t, MatchPlayWay way, int ClubMatchId) {
|
||||
var sql = new StringBuilder();
|
||||
if (way.MatchPlayWayId == 0) {
|
||||
sql.Append($"insert into {tb_ClubMatchPlayWay} (ClubMatchId,weiyima,MinScore,DeskCost,TypeMode,MinFreeDeskCostNum,IsFirstCalcDeskCost,BuresMinScore,IsBuresMin,IsRealCalcScore,LeagueDeskScore)");
|
||||
sql.AppendLine($"values({ClubMatchId},@weiyima,{way.MinScore},{way.DeskCost},{way.TypeMode},{way.MinFreeDeskCostNum},{way.IsFirstCalcDeskCost.SQLValue()},{way.BuresMinScore},{way.IsBuresMin.SQLValue()},{way.IsRealCalcScore.SQLValue()},{way.LeagueDeskScore})");
|
||||
sql.AppendLine($"select cast(SCOPE_IDENTITY() as int)");
|
||||
var result = t.ExecuteScalar(sql.ToString(), new SqlParameter("@weiyima", way.weiyima));
|
||||
if (result is int id) {
|
||||
way.MatchPlayWayId = id;
|
||||
} else {
|
||||
throw new Exception("AddOrUpdateClubMatchPlayWay ClubMatchPlayWay 增加新记录失败!" + sql);
|
||||
}
|
||||
way.ClubMatchId = ClubMatchId;
|
||||
} else {
|
||||
sql.Append($"update {tb_ClubMatchPlayWay} set ");
|
||||
sql.Append($"weiyima = @weiyima,");
|
||||
sql.Append($"MinScore = {way.MinScore},");
|
||||
sql.Append($"DeskCost = {way.DeskCost},");
|
||||
sql.Append($"TypeMode = {way.TypeMode},");
|
||||
sql.Append($"MinFreeDeskCostNum = {way.MinFreeDeskCostNum},");
|
||||
sql.Append($"IsFirstCalcDeskCost = {way.IsFirstCalcDeskCost.SQLValue()},");
|
||||
sql.Append($"BuresMinScore = {way.BuresMinScore},");
|
||||
sql.Append($"IsBuresMin = {way.IsBuresMin.SQLValue()},");
|
||||
sql.Append($"IsRealCalcScore = {way.IsRealCalcScore.SQLValue()}, ");
|
||||
sql.Append($"LeagueDeskScore = @score ");
|
||||
sql.Append($"where MatchPlayWayId = {way.MatchPlayWayId}");
|
||||
if (t.ExecuteNonQuery(sql.ToString(), new SqlParameter("@weiyima", way.weiyima), new SqlParameter("@score", way.LeagueDeskScore)) != 1) {
|
||||
throw new Exception("AddOrUpdateClubMatchPlayWay ClubMatchPlayWay 更新记录失败!" + sql);
|
||||
}
|
||||
t.ExecuteNonQuery($"delete {tb_ClubMatchPlayWayMaxWinnerScoreRange} where MatchPlayWayId = {way.MatchPlayWayId}");
|
||||
}
|
||||
if (way.MaxWinnerScoreRanges != null && way.MaxWinnerScoreRanges.Count > 0) {
|
||||
foreach (var item in way.MaxWinnerScoreRanges) {
|
||||
AddWayMaxWinnerScoreRange(t, item, way.MatchPlayWayId);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 返回俱乐部的比赛日志
|
||||
/// </summary>
|
||||
/// <param name="clubId">记录表的Id</param>
|
||||
/// <param name="createTime">返回该时间之后的日志 按时间倒序排序</param>
|
||||
/// <returns></returns>
|
||||
public static List<ClubMatchNotes> GetClubMatchNotesByClubId(int clubId, DateTime createTime,int topCnt) {
|
||||
var sql = new StringBuilder();
|
||||
sql.AppendLine($"select top {topCnt} * from {tb_ClubMatchNotes} where clubId = {clubId} and createTime >= '{createTime.Date}' order by ClubMatchNotesId desc");
|
||||
Debug.Info($"执行Sql:{sql}");
|
||||
var list = sqldb.ExecuteEntities(sql.ToString(), p => p.ToObject<ClubMatchNotes>()).ToList();
|
||||
return list;
|
||||
}
|
||||
|
||||
static void AddWayMaxWinnerScoreRange(SqlTransaction t, MaxWinnerScoreRange maxWinnerScoreRange, int matchPlayWayId) {
|
||||
var sql = new StringBuilder();
|
||||
sql.Append($"insert into {tb_ClubMatchPlayWayMaxWinnerScoreRange} (matchPlayWayId,MaxWinnerMinScore,DeskScore)");
|
||||
sql.AppendLine($"values({matchPlayWayId},{maxWinnerScoreRange.MaxWinnerMinScore},{maxWinnerScoreRange.DeskScore})");
|
||||
sql.AppendLine($"select cast(SCOPE_IDENTITY() as int)");
|
||||
var result = t.ExecuteScalar(sql.ToString());
|
||||
if (result is int id) {
|
||||
maxWinnerScoreRange.MaxWinnerScoreRangeId = id;
|
||||
} else {
|
||||
throw new Exception("AddOrUpdateWayMaxWinnerScoreRange MaxWinnerScoreRange 增加新记录失败!" + sql);
|
||||
}
|
||||
maxWinnerScoreRange.MatchPlayWayId = matchPlayWayId;
|
||||
}
|
||||
|
||||
// public static List<ClubMatch> GetClubMatches(int clubId, DateTime date) {
|
||||
// return GetClubMatches(clubId, $"and MatchStartTime >= '{date.Date}'");
|
||||
// }
|
||||
|
||||
// public static List<ClubMatch> GetClubMatches(int clubId, string otherWhere, int size = -1) {
|
||||
// var sql = new StringBuilder();
|
||||
// var topSize = size > 0 ? $" top ({size})" : string.Empty;
|
||||
//
|
||||
// sql.AppendLine($"select p1.*, p2.*, p3.* from");
|
||||
// sql.AppendLine($" (select {topSize} * from {tb_ClubMatch} where clubId = {clubId} {otherWhere}) as p1");
|
||||
// sql.AppendLine($"left join {tb_ClubMatchPlayWay} as p2");
|
||||
// sql.AppendLine($"on p1.ClubMatchId = p2.ClubMatchId");
|
||||
// sql.AppendLine($"left join {tb_ClubMatchPlayWayMaxWinnerScoreRange} as p3");
|
||||
// sql.AppendLine($"on p2.MatchPlayWayId = p3.MatchPlayWayId");
|
||||
// sql.AppendLine($"order by p1.ClubMatchId desc, p2.MatchPlayWayId desc, p3.MaxWinnerScoreRangeId desc");
|
||||
//
|
||||
// var table = sqldb.ExecuteTable(sql.ToString());
|
||||
// return table.GetClubMatche().ToList();
|
||||
// }
|
||||
|
||||
/// <summary>
|
||||
/// 获取比赛数据,不关联其他数据
|
||||
/// </summary>
|
||||
/// <param name="clubId"></param>
|
||||
/// <param name="topSize"></param>
|
||||
/// <returns></returns>
|
||||
public static List<ClubMatch> GetClubMatches(int clubId,int topSize=5)
|
||||
{
|
||||
if(topSize<=0) topSize = 5;
|
||||
string sql = $"SELECT top {topSize} * from ClubMatch where ClubId={clubId} order by ClubMatchId desc";
|
||||
//Debug.ImportantLog($"获取比赛数据,不关联其他数据 sql:{sql}");
|
||||
var table = sqldb.ExecuteTable(sql.ToString());
|
||||
return table.GetClubMatche().ToList();
|
||||
}
|
||||
|
||||
static IEnumerable<ClubMatch> GetClubMatche(this DataTable table) {
|
||||
var clubMatchs = new Dictionary<int, ClubMatch>();
|
||||
foreach (DataRow row in table.Rows) {
|
||||
var newWay = row.ToObject<MatchPlayWay>();
|
||||
if (newWay.MatchPlayWayId > 0) {
|
||||
newWay.MaxWinnerScoreRanges = new List<MaxWinnerScoreRange>();
|
||||
if (!clubMatchs.TryGetValue(newWay.ClubMatchId, out var clubMatch)) {
|
||||
clubMatch = row.ToObject<ClubMatch>();
|
||||
clubMatch.InitOtherSetting();
|
||||
clubMatch.MatchPlayWays = new List<MatchPlayWay>();
|
||||
clubMatchs.Add(clubMatch.ClubMatchId, clubMatch);
|
||||
}
|
||||
var way = clubMatch.MatchPlayWays.SingleOrDefault(p => p.MatchPlayWayId == newWay.MatchPlayWayId);
|
||||
if (way == null) {
|
||||
clubMatch.MatchPlayWays.Add(newWay);
|
||||
way = newWay;
|
||||
}
|
||||
var maxWinnerScoreRange = row.ToObject<MaxWinnerScoreRange>();
|
||||
if (maxWinnerScoreRange.MaxWinnerScoreRangeId != 0) {
|
||||
way.MaxWinnerScoreRanges.Add(maxWinnerScoreRange);
|
||||
}
|
||||
} else {
|
||||
//玩法为空的比赛
|
||||
var clubMatch = row.ToObject<ClubMatch>();
|
||||
clubMatch.InitOtherSetting();
|
||||
if (clubMatch.ClubMatchId > 0 && !clubMatchs.Keys.Contains(clubMatch.ClubMatchId)) {
|
||||
clubMatch.MatchPlayWays = new List<MatchPlayWay>();
|
||||
clubMatchs.Add(clubMatch.ClubMatchId, clubMatch);
|
||||
}
|
||||
}
|
||||
}
|
||||
return clubMatchs.Values;
|
||||
}
|
||||
|
||||
// public static List<ClubMatch> GetTopOneClubMatch(int clubId, int top) {
|
||||
// return GetClubMatches(clubId, "order by ClubMatchId desc", top);
|
||||
// }
|
||||
|
||||
// public static void SaveClubMatchScoreNotes(ClubMatchScoreNotes model) {
|
||||
// sqldb.ExecuteTransaction(t => SaveClubMatchScoreNote(t, model));
|
||||
// }
|
||||
|
||||
// static bool SaveClubMatchScoreNote(SqlTransaction t, ClubMatchScoreNotes model) {
|
||||
//
|
||||
// var sql = new StringBuilder();
|
||||
// sql.Append($"insert into {tb_ClubMatchScoreNotes} (clubId,ClubMatchId,UserId,TypeId,Score,DeskScore,NewScore)");
|
||||
// sql.Append($"values({model.ClubId},{model.ClubMatchId},{model.UserId},{model.TypeId},@Score,@DeskScore,@NewScore)");
|
||||
// if (t.ExecuteNonQuery(sql.ToString(), new SqlParameter("@Score", model.Score), new SqlParameter("@DeskScore", model.DeskScore)
|
||||
// , new SqlParameter("@NewScore", model.NewScore)) != 1) {
|
||||
// throw new Exception("SaveClubMatchScoreNotes ClubMatchScoreNotes 增加新记录失败!" + sql);
|
||||
// }
|
||||
// return true;
|
||||
// }
|
||||
|
||||
public static List<ClubMatchScoreNotes> GetClubMatchScoreNotes(int clubId, int clubMatchId, int userId,int cnt) {
|
||||
var sql = new StringBuilder();
|
||||
sql.Append($"select top {cnt} * from {tb_ClubMatchScoreNotes} where clubId = {clubId} and clubMatchId = {clubMatchId} and userId = {userId} order by ScoreNotesId desc");
|
||||
Debug.Info(sql);
|
||||
var list = sqldb.ExecuteEntities(sql.ToString(), p => p.ToObject<ClubMatchScoreNotes>()).ToList();
|
||||
return list;
|
||||
}
|
||||
|
||||
// /// <summary>
|
||||
// /// 批量保存比赛日志
|
||||
// /// </summary>
|
||||
// /// <param name="model"></param>
|
||||
// public static void SaveClubMatchNotes(List<ClubMatchNotes> model)
|
||||
// {
|
||||
// if (model == null || model.Count <= 0) return;
|
||||
// var transaction = GameDB.Instance.BeginTransaction(dbbase.game2018);
|
||||
// foreach (var item in model)
|
||||
// {
|
||||
// var sql = $"insert into {tb_ClubMatchNotes} (TypeId,clubId,ClubMatchId,Content) values({(int)item.TypeId},{item.ClubId},{item.ClubMatchId},'{item.Content}')";
|
||||
// if (1 != GameDB.Instance.TransactionAddSql(transaction, sql))
|
||||
// {
|
||||
// GameDB.Instance.Rollback(transaction);
|
||||
// return;
|
||||
// }
|
||||
// }
|
||||
// GameDB.Instance.SubTransaction(transaction);
|
||||
// }
|
||||
|
||||
/// <summary>
|
||||
/// 返回俱乐部的操作日志
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static List<ClubMatchNotes> GetClubMatchNotesByClubIdType(int clubId,int type, DateTime createTime)
|
||||
{
|
||||
var sql = new StringBuilder();
|
||||
sql.AppendLine($"select * from {tb_ClubMatchNotes} where clubId = {clubId} and createTime >= '{createTime.Date}' and TypeId={type} order by ClubMatchNotesId desc");
|
||||
var list = sqldb.ExecuteEntities(sql.ToString(), p => p.ToObject<ClubMatchNotes>()).ToList();
|
||||
return list;
|
||||
}
|
||||
|
||||
// public static void SaveClubMatchNotes(ClubMatchNotes model) {
|
||||
// var sql = new StringBuilder();
|
||||
// sql.Append($"insert into {tb_ClubMatchNotes} (TypeId,clubId,ClubMatchId,Content)");
|
||||
// sql.Append($"values({(int)model.TypeId},{model.ClubId},{model.ClubMatchId},@content)");
|
||||
// if (sqldb.ExecuteNonQuery(sql.ToString(), new SqlParameter("@Content", model.Content)) != 1) {
|
||||
// Debug.Fatal("SaveClubMatchNotes ClubMatchNotes 增加新记录失败!" + sql);
|
||||
// }
|
||||
// }
|
||||
|
||||
// public static List<ClubMatchNotes> GetClubMatchNotes(int clubId, int clubMatchId) {
|
||||
// var sql = new StringBuilder();
|
||||
// sql.Append($"select * from {tb_ClubMatchNotes} where clubId = {clubId} and clubMatchId = {clubMatchId} order by ClubMatchNotesId desc");
|
||||
// var list = sqldb.ExecuteEntities(sql.ToString(), p => p.ToObject<ClubMatchNotes>()).ToList();
|
||||
// return list;
|
||||
// }
|
||||
|
||||
// public static void SaveClubMatchScoreNotesList(List<ClubMatchScoreNotes> model) {
|
||||
// sqldb.ExecuteTransaction(t => model.All(p => SaveClubMatchScoreNote(t, p)));
|
||||
// }
|
||||
|
||||
public static ClubMatchUserScore GetClubMatchUserScore(int clubId, int clubMatchId, int userId) {
|
||||
var sql = new StringBuilder();
|
||||
sql.Append($"select * from {tb_ClubMatchUserScore} where clubId = {clubId} and clubMatchId = {clubMatchId} and userId = {userId}");
|
||||
var item = sqldb.ExecuteEntities(sql.ToString(), p => p.ToObject<ClubMatchUserScore>()).SingleOrDefault();
|
||||
return item;
|
||||
}
|
||||
|
||||
public static bool SaveClubMatchUserScore(ClubMatchUserScore model) {
|
||||
return sqldb.ExecuteTransaction(t => SaveClubMatchUserScore(t, model));
|
||||
}
|
||||
|
||||
public static bool SaveClubMatchUserScores(List<ClubMatchUserScore> models) {
|
||||
return sqldb.ExecuteTransaction(t => models.All(model => SaveClubMatchUserScore(t, model)));
|
||||
}
|
||||
|
||||
public static bool SaveClubMatchUserScore(SqlTransaction t, ClubMatchUserScore model) {
|
||||
var sql = new StringBuilder();
|
||||
var parameters = new[] { new SqlParameter("@Score", model.Score), new SqlParameter("@deskScore", model.DeskScore)
|
||||
, new SqlParameter("@ScoreBak", model.ScoreBak)};
|
||||
if (model.UserScoreId == 0) {
|
||||
sql.Append($"insert into {tb_ClubMatchUserScore} (clubId,ClubMatchId,UserId,Score,DeskScore,ScoreBak)");
|
||||
sql.AppendLine($"values({model.ClubId},{model.ClubMatchId},{model.UserId},@Score,@DeskScore,@ScoreBak)");
|
||||
sql.Append($"select cast(SCOPE_IDENTITY() as int)");
|
||||
var result = t.ExecuteScalar(sql.ToString(), parameters);
|
||||
if (result is int id) {
|
||||
model.UserScoreId = id;
|
||||
} else {
|
||||
throw new Exception($"SaveClubMatchUserScore ClubMatchUserScore 增加记录失败!" + sql);
|
||||
}
|
||||
} else {
|
||||
sql.AppendLine($"update {tb_ClubMatchUserScore} set score = @Score, deskScore = @deskScore,ScoreBak=@ScoreBak where UserScoreId = {model.UserScoreId}");
|
||||
if (t.ExecuteNonQuery(sql.ToString(), parameters) != 1) {
|
||||
throw new Exception("SaveClubMatchUserScore ClubMatchUserScore 更新记录失败!" + sql);
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
public static List<ClubMatchUserScore> GetClubMatchUserScores(int clubId, int clubMatchId) {
|
||||
var sql = new StringBuilder();
|
||||
sql.Append($"select * from {tb_ClubMatchUserScore} where clubId = {clubId} and clubMatchId = {clubMatchId} order by UserScoreId desc");
|
||||
var list = sqldb.ExecuteEntities(sql.ToString(), p => p.ToObject<ClubMatchUserScore>()).ToList();
|
||||
return list;
|
||||
}
|
||||
}
|
||||
373
GameDAL/Club/ClubMatchManagerDal.cs
Normal file
373
GameDAL/Club/ClubMatchManagerDal.cs
Normal file
@ -0,0 +1,373 @@
|
||||
using ObjectModel.Club;
|
||||
using Server.DB.Redis;
|
||||
using StackExchange.Redis;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace GameDAL.Club
|
||||
{
|
||||
/// <summary>
|
||||
/// 俱乐部比赛数据库操作对象
|
||||
/// 先从redis获取数据,没有在从数据库获取并保存到redis
|
||||
/// </summary>
|
||||
public static class ClubMatchManagerDal
|
||||
{
|
||||
public static readonly string clubMatchKeyPrefix = "ClubMatch";
|
||||
public static readonly DbStyle redisdb = DbStyle.main;
|
||||
public static readonly int dbidx = 7;
|
||||
static TimeSpan expiry = TimeSpan.FromDays(3);
|
||||
|
||||
static RedisKey GetTopOneClubMatch2Key(int clubId) => $"{clubMatchKeyPrefix}:GetTopOneClubMatch2:{clubId}";
|
||||
|
||||
// /// <summary>
|
||||
// /// 返回比赛数据
|
||||
// /// </summary>
|
||||
// /// <param name="clubId">俱乐部Id</param>
|
||||
// /// <param name="list">需要返回的数据</param>
|
||||
// /// <param name="statusFlag">1进行中 2已结束</param>
|
||||
// /// <returns></returns>
|
||||
// public static ClubMatch GetClubMatchByClubId(int clubId, out List<ClubMatchUserScore> list, int statusFlag = 1)
|
||||
// {
|
||||
// list = null;
|
||||
// var result = redisdb.GetOrAdd(GetClubMatchByClubIdKey(clubId), statusFlag, () =>
|
||||
// {
|
||||
// var clubMatch = ClubMatchManagerAdo.GetClubMatchByClubId(clubId, out var list2, statusFlag);
|
||||
// var ts = clubMatch != null ? expiry : TimeSpan.FromMinutes(10);
|
||||
// return Tuple.Create(Tuple.Create(clubMatch ?? new ClubMatch(), list2 ?? new List<ClubMatchUserScore>()), ts);
|
||||
// }, dbidx, false);
|
||||
// if (result.Item1.ClubMatchId == 0)
|
||||
// {
|
||||
// return null;
|
||||
// }
|
||||
// list = result.Item2;
|
||||
// return result.Item1;
|
||||
// }
|
||||
|
||||
// static RedisKey GetClubMatchByClubIdKey(int clubId) => $"{clubMatchKeyPrefix}:ClubMatchByClubId:{clubId}";
|
||||
|
||||
/// <summary>
|
||||
/// 保存比赛数据库到数据库
|
||||
/// 这里要做 比赛玩法保存的逻辑,
|
||||
/// 保存完以后把自增Id赋值
|
||||
/// </summary>
|
||||
public static bool SaveClubMatch(ClubMatch model)
|
||||
{
|
||||
if (model == null) return false;
|
||||
var succ = ClubMatchManagerAdo.SaveClubMatch(model);
|
||||
if (succ)
|
||||
{
|
||||
RemoveCachingOfClubMatch(model.ClubId, model.ClubMatchId);
|
||||
}
|
||||
return succ;
|
||||
}
|
||||
|
||||
public static async Task<bool> SaveClubMatchAsync(ClubMatch model)
|
||||
{
|
||||
return await Task.Run(() => SaveClubMatch(model));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 只更新ClubMatchModel
|
||||
/// </summary>
|
||||
/// <param name="model"></param>
|
||||
/// <returns></returns>
|
||||
public static bool UpdateClubMatchModel(ClubMatch model)
|
||||
{
|
||||
if (model == null || model.ClubMatchId <= 0) return false;
|
||||
var succ = ClubMatchManagerAdo.UpdateClubMatchModel(model);
|
||||
if (succ)
|
||||
{
|
||||
RemoveCachingOfClubMatch(model.ClubId, model.ClubMatchId);
|
||||
}
|
||||
return succ;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除缓存的比赛数据
|
||||
/// </summary>
|
||||
/// <param name="clubId"></param>
|
||||
/// <param name="clubMatchId"></param>
|
||||
static void RemoveCachingOfClubMatch(int clubId, int clubMatchId)
|
||||
{
|
||||
var key1 = GetClubMatchesKey(clubId);
|
||||
var key2 = GetTopOneClubMatchKey(clubId);
|
||||
redisdb.GetRedisDataBase(dbidx).KeyDelete(new[] { key1, key2 });
|
||||
}
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取俱乐部的比赛,,要把比赛玩法的数据组合进来返回
|
||||
// /// </summary>
|
||||
// /// <param name="clubId">俱乐部Id</param>
|
||||
// /// <param name="date">截止时间与比赛开始比较</param>
|
||||
// /// <returns></returns>
|
||||
// public static List<ClubMatch> GetClubMatches(int clubId, DateTime date)
|
||||
// {
|
||||
// return redisdb.GetOrAdd(GetClubMatchesKey(clubId), date.ToString("yyyyMMdd"), () =>
|
||||
// {
|
||||
// var list = ClubMatchManagerAdo.GetClubMatches(clubId, date);
|
||||
// var ts = list.Count > 0 ? expiry : TimeSpan.FromMinutes(10);
|
||||
// return Tuple.Create(list, ts);
|
||||
// }, dbidx, false);
|
||||
// }
|
||||
|
||||
#region 获取最近5局的一个比赛信息
|
||||
|
||||
public static void DeleteGetClubMatchesByTopRedis(int clubId)
|
||||
{
|
||||
string key = $"GetClubMatchesByTop:{clubId}";
|
||||
redisManager.Getdb(dbidx).KeyDelete(key);
|
||||
}
|
||||
|
||||
public static Task<List<ClubMatch>> GetClubMatchesByTopAsync(int clubId, int top = 5)
|
||||
{
|
||||
return Task.Run(() => GetClubMatchesByTop(clubId, top));
|
||||
}
|
||||
|
||||
public static List<ClubMatch> GetClubMatchesByTop(int clubId,int top =5)
|
||||
{
|
||||
string key = $"GetClubMatchesByTop:{clubId}";
|
||||
return redisdb.GetOrAdd(key, string.Empty, () =>
|
||||
{
|
||||
var list = ClubMatchManagerAdo.GetClubMatches(clubId, top);
|
||||
var ts = TimeSpan.FromHours(12);
|
||||
return Tuple.Create(list, ts);
|
||||
}, dbidx, false);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
static RedisKey GetClubMatchesKey(int clubId) => $"{clubMatchKeyPrefix}:ClubMatches:{clubId}";
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取俱乐部比赛最近几条 ,要把比赛玩法的数据组合进来返回
|
||||
// /// </summary>
|
||||
// /// <param name="clubId"></param>
|
||||
// /// <param name="top"></param>
|
||||
// /// <returns></returns>
|
||||
// public static List<ClubMatch> GetTopOneClubMatch(int clubId, int top = 1)
|
||||
// {
|
||||
// return redisdb.GetOrAdd(GetTopOneClubMatchKey(clubId), top, () =>
|
||||
// {
|
||||
// var list = ClubMatchManagerAdo.GetTopOneClubMatch(clubId, top);
|
||||
// var ts = list.Count > 0 ? expiry : TimeSpan.FromMinutes(10);
|
||||
// return Tuple.Create(list, ts);
|
||||
// }, dbidx, false);
|
||||
// }
|
||||
static RedisKey GetTopOneClubMatchKey(int clubId) => $"{clubMatchKeyPrefix}:TopOneClubMatch:{clubId}";
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取某个玩家的比赛的积分记录
|
||||
// /// </summary>
|
||||
// /// <param name="clubId"></param>
|
||||
// /// <param name="clubMatchId"></param>
|
||||
// /// <param name="userId"></param>
|
||||
// /// <param name="IsNow">是否是当前的比赛。true是 false不是。如果是当前比赛过期时间只能设置分钟如5分钟,结束的比赛过期时间可以设置长一点如3天</param>
|
||||
// /// <returns></returns>
|
||||
// public static List<ClubMatchScoreNotes> GetClubMatchScoreNotes(int clubId, int clubMatchId, int userId, bool IsNow = false)
|
||||
// {
|
||||
// return redisdb.GetOrAdd(RedisType.List, GetClubMatchScoreNotesKey(clubId, clubMatchId, userId), () =>
|
||||
// {
|
||||
// var list = ClubMatchManagerAdo.GetClubMatchScoreNotes(clubId, clubMatchId, userId);
|
||||
// var ts = IsNow ? TimeSpan.FromMinutes(5) : list.Count > 0 ? expiry : TimeSpan.FromMinutes(3);
|
||||
// return Tuple.Create(list, ts);
|
||||
// }, dbidx, false);
|
||||
// }
|
||||
|
||||
// static RedisKey GetClubMatchScoreNotesKey(int clubId, int clubMatchId, int userId) => $"{clubMatchKeyPrefix}:ClubMatchScoreNotes:{clubId}:{clubMatchId}:{userId}";
|
||||
|
||||
// /// <summary>
|
||||
// /// 保存玩家分值日志
|
||||
// /// </summary>
|
||||
// /// <param name="model"></param>
|
||||
// public static void SaveClubMatchScoreNotes(ClubMatchScoreNotes model)
|
||||
// {
|
||||
// ClubMatchManagerAdo.SaveClubMatchScoreNotes(model);
|
||||
// RemoveCachingOfClubMatchScoreNotes(model.ClubId, model.ClubMatchId, model.UserId);
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 批量保存玩家分值日志
|
||||
// /// </summary>
|
||||
// /// <param name="model"></param>
|
||||
// public static void SaveClubMatchScoreNotesList(List<ClubMatchScoreNotes> model)
|
||||
// {
|
||||
// if (model.Count > 0)
|
||||
// {
|
||||
// ClubMatchManagerAdo.SaveClubMatchScoreNotesList(model);
|
||||
// RemoveCachingOfClubMatchScoreNotes(model[0].ClubId, model[0].ClubMatchId, model.Select(p => p.UserId).ToArray());
|
||||
// }
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 移除缓存的玩家分值日志
|
||||
// /// </summary>
|
||||
// /// <param name="clubId"></param>
|
||||
// /// <param name="clubMatchId"></param>
|
||||
// /// <param name="userIds"></param>
|
||||
// static void RemoveCachingOfClubMatchScoreNotes(int clubId, int clubMatchId, params int[] userIds)
|
||||
// {
|
||||
// var keys = userIds.Select(p => GetClubMatchScoreNotesKey(clubId, clubMatchId, p)).ToArray();
|
||||
// redisdb.GetRedisDataBase(dbidx).KeyDelete(keys);
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取比赛记录
|
||||
// /// </summary>
|
||||
// /// <param name="clubId"></param>
|
||||
// /// <param name="clubMatchId"></param>
|
||||
// /// <param name="IsNow">是否是当前的比赛。true是 false不是。如果是当前比赛过期时间只能设置分钟如5分钟,结束的比赛过期时间可以设置长一点如3天</param>
|
||||
// /// <returns></returns>
|
||||
// public static List<ClubMatchNotes> GetClubMatchNotes(int clubId, int clubMatchId, bool IsNow = false)
|
||||
// {
|
||||
// return redisdb.GetOrAdd(RedisType.List, GetClubMatchNotesKey(clubId, clubMatchId), () =>
|
||||
// {
|
||||
// var list = ClubMatchManagerAdo.GetClubMatchNotes(clubId, clubMatchId);
|
||||
// var ts = IsNow ? TimeSpan.FromMinutes(5) : list.Count > 0 ? expiry : TimeSpan.FromMinutes(3);
|
||||
// return Tuple.Create(list, ts);
|
||||
// }, dbidx, false);
|
||||
// }
|
||||
// static RedisKey GetClubMatchNotesKey(int clubId, int clubMatchId) => $"{clubMatchKeyPrefix}:ClubMatchNotes:{clubId}:{clubMatchId}";
|
||||
|
||||
// /// <summary>
|
||||
// /// 返回俱乐部的比赛日志
|
||||
// /// </summary>
|
||||
// /// <param name="clubId">记录表的Id</param>
|
||||
// /// <param name="createTime">返回该时间之后的日志 按时间倒序排序</param>
|
||||
// /// <returns></returns>
|
||||
// public static List<ClubMatchNotes> GetClubMatchNotesByClubId(int clubId, DateTime createTime)
|
||||
// {
|
||||
// return redisdb.GetOrAdd(GetClubMatchNotesByClubIdKey(clubId), createTime.ToString("yyyyMMdd"), () =>
|
||||
// {
|
||||
// var list = ClubMatchManagerAdo.GetClubMatchNotesByClubId(clubId, createTime);
|
||||
// var ts = TimeSpan.FromMinutes(5); //这个是累积实时的,故过期时间短
|
||||
// return Tuple.Create(list, ts);
|
||||
// }, dbidx, false);
|
||||
// }
|
||||
// static RedisKey GetClubMatchNotesByClubIdKey(int clubId) => $"{clubMatchKeyPrefix}:GetClubMatchNotesByClubId:{clubId}";
|
||||
|
||||
// /// <summary>
|
||||
// /// 返回俱乐部的比赛日志
|
||||
// /// </summary>
|
||||
// public static List<ClubMatchNotes> GetClubMatchNotesByClubIdType(int clubId, int type ,DateTime createTime)
|
||||
// {
|
||||
// return redisdb.GetOrAdd(GetClubMatchNotesByClubIdKeyType(clubId,type), createTime.ToString("yyyyMMdd"), () =>
|
||||
// {
|
||||
// var list = ClubMatchManagerAdo.GetClubMatchNotesByClubIdType(clubId, type, createTime);
|
||||
// var ts = TimeSpan.FromMinutes(5); //这个是累积实时的,故过期时间短
|
||||
// return Tuple.Create(list, ts);
|
||||
// }, dbidx, false);
|
||||
// }
|
||||
//static RedisKey GetClubMatchNotesByClubIdKeyType(int clubId,int type) => $"{clubMatchKeyPrefix}:GetClubMatchNotesByClubId:{clubId}_t{type}";
|
||||
|
||||
// public static void RemoveGetClubMatchNotesByClubIdKeyType(int clubId,int type)
|
||||
// {
|
||||
// var key = GetClubMatchNotesByClubIdKeyType(clubId, type);
|
||||
// redisdb.GetRedisDataBase(dbidx).KeyDelete(key);
|
||||
// }
|
||||
|
||||
// /// <summary>
|
||||
// /// 保存俱乐部日志记录
|
||||
// /// </summary>
|
||||
// /// <param name="model"></param>
|
||||
// public static void SaveClubMatchNotes(ClubMatchNotes model)
|
||||
// {
|
||||
// ClubMatchManagerAdo.SaveClubMatchNotes(model);
|
||||
// RemoveCachingOfClubMatchNotes(model.ClubId, model.ClubMatchId);
|
||||
// }
|
||||
//
|
||||
// /// <summary>
|
||||
// /// 移除缓存的群主俱乐部日志记录
|
||||
// /// </summary>
|
||||
// /// <param name="clubId"></param>
|
||||
// /// <param name="clubMatchId"></param>
|
||||
// static void RemoveCachingOfClubMatchNotes(int clubId, int clubMatchId)
|
||||
// {
|
||||
// var key1 = GetClubMatchNotesKey(clubId, clubMatchId);
|
||||
// var key2 = GetClubMatchNotesByClubIdKey(clubId);
|
||||
// redisdb.GetRedisDataBase(dbidx).KeyDelete(new[] { key1, key2 });
|
||||
// }
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有玩家的比赛积分 过期时间3天
|
||||
/// </summary>
|
||||
/// <param name="clubId"></param>
|
||||
/// <param name="clubMatchId"></param>
|
||||
/// <returns></returns>
|
||||
public static List<ClubMatchUserScore> GetClubMatchUserScores(int clubId, int clubMatchId)
|
||||
{
|
||||
return redisdb.GetOrAdd(RedisType.List, GetClubMatchUserScoresKey(clubId, clubMatchId), () =>
|
||||
{
|
||||
//去数据库查询历史数据, 在放到 Redis 中
|
||||
var list = ClubMatchManagerAdo.GetClubMatchUserScores(clubId, clubMatchId);
|
||||
var ts = list.Count > 0 ? expiry : TimeSpan.FromMinutes(10);
|
||||
return Tuple.Create(list, ts);
|
||||
}, dbidx, false);
|
||||
}
|
||||
|
||||
static RedisKey GetClubMatchUserScoresKey(int clubId, int clubMatchId) => $"{clubMatchKeyPrefix}:ClubMatchUserScores:{clubId}:{clubMatchId}";
|
||||
|
||||
// /// <summary>
|
||||
// /// 获取单个玩家的比赛积分
|
||||
// /// </summary>
|
||||
// /// <param name="clubId"></param>
|
||||
// /// <param name="clubMatchId"></param>
|
||||
// /// <param name="userId"></param>
|
||||
// /// <returns></returns>
|
||||
// public static ClubMatchUserScore GetClubMatchUserScore(int clubId, int clubMatchId, int userId)
|
||||
// {
|
||||
// var userScore = redisdb.GetOrAdd(RedisType.String, GetClubMatchUserScoreKey(clubId, clubMatchId, userId), () =>
|
||||
// {
|
||||
// var item = ClubMatchManagerAdo.GetClubMatchUserScore(clubId, clubMatchId, userId);
|
||||
// var ts = item != null ? expiry : TimeSpan.FromMinutes(10);
|
||||
// return Tuple.Create(item ?? new ClubMatchUserScore(), ts);
|
||||
// }, dbidx, false);
|
||||
// return userScore.ClubMatchId != 0 ? userScore : null;
|
||||
// }
|
||||
// static RedisKey GetClubMatchUserScoreKey(int clubId, int clubMatchId, int userId) => $"{clubMatchKeyPrefix}:ClubMatchUserScore:{clubId}:{clubMatchId}:{userId}";
|
||||
|
||||
|
||||
// /// <summary>
|
||||
// /// 保存玩家记录
|
||||
// /// </summary>
|
||||
// /// <param name="model"></param>
|
||||
// public static void SaveClubMatchUserScore(ClubMatchUserScore model)
|
||||
// {
|
||||
// if (ClubMatchManagerAdo.SaveClubMatchUserScore(model))
|
||||
// {
|
||||
// RemoveCachingOfClubMatchUserScore(model.ClubId, model.ClubMatchId, model.UserId);
|
||||
// }
|
||||
// }
|
||||
|
||||
/// <summary>
|
||||
/// 批量保存玩家记录
|
||||
/// </summary>
|
||||
/// <param name="models"></param>
|
||||
public static void SaveSaveClubMatchUserScores(List<ClubMatchUserScore> models)
|
||||
{
|
||||
if (models == null || models.Count < 1) return;
|
||||
if (models.Count > 0)
|
||||
{
|
||||
if (ClubMatchManagerAdo.SaveClubMatchUserScores(models))
|
||||
{
|
||||
RemoveCachingOfClubMatchUserScore(models[0].ClubId, models[0].ClubMatchId, models.Select(p => p.UserId).ToArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除缓存的玩家记录
|
||||
/// </summary>
|
||||
/// <param name="clubId"></param>
|
||||
/// <param name="clubMatchId"></param>
|
||||
/// <param name="userIds"></param>
|
||||
static void RemoveCachingOfClubMatchUserScore(int clubId, int clubMatchId, params int[] userIds)
|
||||
{
|
||||
var keys = new List<RedisKey>();
|
||||
keys.Add(GetClubMatchUserScoresKey(clubId, clubMatchId));
|
||||
redisdb.GetRedisDataBase(dbidx).KeyDelete(keys.ToArray());
|
||||
}
|
||||
}
|
||||
}
|
||||
209
GameDAL/Club/ClubRCDiscountRedisUtil.cs
Normal file
209
GameDAL/Club/ClubRCDiscountRedisUtil.cs
Normal file
@ -0,0 +1,209 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using Server.DB.Redis;
|
||||
using System.Text;
|
||||
using StackExchange.Redis;
|
||||
using MrWu.Debug;
|
||||
|
||||
namespace GameDAL {
|
||||
/// <summary>
|
||||
/// 俱乐部房卡折扣记录
|
||||
/// </summary>
|
||||
public static class ClubRCDiscountRedisUtil {
|
||||
|
||||
private const int DbIdx = 5;
|
||||
private static IDatabaseProxy dbp => redisManager.Getdb(DbIdx);
|
||||
private static IDatabase db => redisManager.GetDataBase(DbStyle.main, DbIdx);
|
||||
private const string baseKey = "ClubRCDiscount";
|
||||
|
||||
#region 直充俱乐部折扣
|
||||
|
||||
private static string GetClubKey() {
|
||||
return $"{baseKey}:Club";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有的折扣信息
|
||||
/// </summary>
|
||||
public static List<string> GetClubAll()
|
||||
{
|
||||
string key = GetClubKey();
|
||||
var allEntry = dbp.HashGetAll(key);
|
||||
List<string> list = allEntry.Select(x=>$"{x.Name}, {Convert.ToSingle(x.Value)}").ToList();
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<(int Id, float Discount)> GetClubAllEntry()
|
||||
{
|
||||
string key = GetClubKey();
|
||||
var allEntry = dbp.HashGetAll(key);
|
||||
List<(int, float)> list = new List<(int, float)>();
|
||||
foreach (var item in allEntry)
|
||||
{
|
||||
list.Add((int.Parse(item.Name), float.Parse(item.Value)));
|
||||
}
|
||||
return list.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加折扣
|
||||
/// </summary>
|
||||
public static bool AddClub(int clubId, float discount) {
|
||||
string key = GetClubKey();
|
||||
return dbp.HashSet(key, clubId, discount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除折扣
|
||||
/// </summary>
|
||||
public static bool RemoveClub(int clubId) {
|
||||
string key = GetClubKey();
|
||||
return dbp.HashDelete(key, clubId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取折扣
|
||||
/// </summary>
|
||||
public static float GetClub(int clubId) {
|
||||
string key = GetClubKey();
|
||||
var value = dbp.HashGet(key, clubId);
|
||||
if (value.HasValue && float.TryParse(value, out var discount))
|
||||
{
|
||||
return discount;
|
||||
}
|
||||
return 0.7f;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 玩家房卡折扣
|
||||
private static string GetPlayerKey() {
|
||||
return $"{baseKey}:Player";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有的折扣信息
|
||||
/// </summary>
|
||||
public static List<string> GetPlayerAll()
|
||||
{
|
||||
string key = GetPlayerKey();
|
||||
var allEntry = dbp.HashGetAll(key);
|
||||
List<string> list = allEntry.Select(x=>$"{x.Name}, {Convert.ToSingle(x.Value)}").ToList();
|
||||
return list;
|
||||
}
|
||||
|
||||
public static List<(int Id, float Discount)> GetPlayerAllEntry()
|
||||
{
|
||||
string key = GetPlayerKey();
|
||||
var allEntry = dbp.HashGetAll(key);
|
||||
List<(int, float)> list = new List<(int, float)>();
|
||||
foreach (var item in allEntry)
|
||||
{
|
||||
list.Add((int.Parse(item.Name), float.Parse(item.Value)));
|
||||
}
|
||||
return list.ToList();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加折扣
|
||||
/// </summary>
|
||||
public static bool AddPlayer(int userId, float discount) {
|
||||
string key = GetPlayerKey();
|
||||
return dbp.HashSet(key, userId, discount);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除折扣
|
||||
/// </summary>
|
||||
public static bool RemovePlayer(int userId) {
|
||||
string key = GetPlayerKey();
|
||||
return dbp.HashDelete(key, userId);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取折扣
|
||||
/// </summary>
|
||||
public static float GetPlayer(int userId) {
|
||||
string key = GetPlayerKey();
|
||||
var value = dbp.HashGet(key, userId);
|
||||
if (value.HasValue && float.TryParse(value, out var discount))
|
||||
{
|
||||
return discount;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 玩家俱乐部房卡转入限制
|
||||
private static string GetPlayerClubLimitKey(int userId) {
|
||||
return $"{baseKey}:PlayerClubLimit:{userId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加玩家俱乐部转入限制
|
||||
/// </summary>
|
||||
public static bool AddPlayerClubLimit(int userId, int clubId) {
|
||||
string key = GetPlayerClubLimitKey(userId);
|
||||
return dbp.SetAdd(key,clubId);
|
||||
}
|
||||
|
||||
public static bool AddPlayerClubLimit(int userId, List<int> ids) {
|
||||
string key = GetPlayerClubLimitKey(userId);
|
||||
dbp.KeyDelete(key);
|
||||
RedisValue[] redisValues = ids.Select(id => (RedisValue)id).ToArray();
|
||||
if (redisValues.Length == 0)
|
||||
return true;
|
||||
return dbp.SetAdd(key, redisValues) > 0;
|
||||
}
|
||||
|
||||
public static bool RemovePlayerClubLimit(int userId) {
|
||||
string key = GetPlayerClubLimitKey(userId);
|
||||
return dbp.KeyDelete(key);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否允许转入房卡
|
||||
/// </summary>
|
||||
public static bool IsPlayerClubGiveEnable(int userId, int clubId) {
|
||||
string key = GetPlayerClubLimitKey(userId);
|
||||
if (!dbp.KeyExists(key)) return true; // 不存在key就没有限制,都可以转入
|
||||
return dbp.SetContains(key, clubId); // 存在key,只能转入对应的俱乐部
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取玩家俱乐部转入限制
|
||||
/// </summary>
|
||||
public static List<int> GetPlayerClubLimit(int userId)
|
||||
{
|
||||
string key = GetPlayerClubLimitKey(userId);
|
||||
if (!dbp.KeyExists(key)) return new List<int>();
|
||||
return dbp.SetMembers(key).Select(x=>int.Parse(x)).ToList();
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 工具方法
|
||||
|
||||
public static (int TotalNum, int GiveNum) CalPlayerCardWithDiscount(int userId, int cardCnt)
|
||||
{
|
||||
var discount = GetPlayer(userId);
|
||||
if (discount <=0 || discount >= 1) return (cardCnt, 0);
|
||||
var totalNum = (int)Math.Round(cardCnt / discount);
|
||||
var giveNum = totalNum - cardCnt;
|
||||
return (totalNum, giveNum);
|
||||
}
|
||||
|
||||
public static (int TotalNum, int GiveNum) CalClubCardWithDiscount(int clubId, int cardCnt)
|
||||
{
|
||||
var discount = GetClub(clubId);
|
||||
if (discount <= 0 || discount >= 1) return (cardCnt, 0);
|
||||
var totalNum = (int)Math.Round(cardCnt / discount);
|
||||
var giveNum = totalNum - cardCnt;
|
||||
return (totalNum, giveNum);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
79
GameDAL/Eml/EmailManager.cs
Normal file
79
GameDAL/Eml/EmailManager.cs
Normal file
@ -0,0 +1,79 @@
|
||||
/*
|
||||
* 作者:吴隆健
|
||||
* 日期: 2019-04-08
|
||||
* 时间: 13:59
|
||||
*
|
||||
*/
|
||||
using System;
|
||||
using Server.DB.Sql;
|
||||
using System.Data;
|
||||
using System.Threading.Tasks;
|
||||
using GameData;
|
||||
using MrWu.Debug;
|
||||
using GameMessage;
|
||||
|
||||
namespace GameDAL.Eml
|
||||
{
|
||||
/// <summary>
|
||||
/// 邮件处理
|
||||
/// </summary>
|
||||
public static class EmailManager
|
||||
{
|
||||
/// <summary>
|
||||
/// 发送邮件
|
||||
/// </summary>
|
||||
/// <param name="send_id">发件人id 系统消息表示的是可阅读数量</param>
|
||||
/// <param name="send_type">发件人类型 0系统 1用户 2竞技比赛</param>
|
||||
/// <param name="receive_id">接收人 -1表示群发</param>
|
||||
/// <param name="receive_type">0系统 1用户 2竞技比赛 1000以上表示系统消息 1000游戏游戏 2000竞技比赛消息 1000+gameid金币子游戏消息 2000+gameid朋友场子游戏消息</param>
|
||||
/// <param name="title">邮件标题,不能超过10个汉字</param>
|
||||
/// <param name="content">邮件内容</param>
|
||||
/// <param name="res">游戏资源</param>
|
||||
public static void WriteEml(int send_id, int send_type, int receive_id, int receive_type, string title, string content, GameRes[] res = null)
|
||||
{
|
||||
|
||||
if (receive_id < -1)
|
||||
{
|
||||
Debug.Error("游戏逻辑错误,请检查-邮件发送:" + receive_id);
|
||||
return;
|
||||
}
|
||||
|
||||
|
||||
string strres = string.Empty;
|
||||
|
||||
if (res != null)
|
||||
{
|
||||
strres = JsonPack.GetJson(res);
|
||||
}
|
||||
|
||||
var spp = GameDB.Instance.BeginSetProcedureParameter(dbbase.game2018, "add_user_mail_new");
|
||||
GameDB.Instance.AddProdureParameters(spp, "@send_id", SqlDbType.Int, send_id);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@send_type", SqlDbType.Int, send_type);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@receive_id", SqlDbType.Int, receive_id);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@receive_type", SqlDbType.Int, receive_type);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@mail_title", SqlDbType.NVarChar, title);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@str_content", SqlDbType.NVarChar, content);
|
||||
GameDB.Instance.AddProdureParameters(spp, "@mail_res", SqlDbType.NVarChar, strres);
|
||||
GameDB.Instance.EndAddProdureParameters(spp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发送邮件
|
||||
/// </summary>
|
||||
/// <param name="send_id">发件人id 系统消息表示的是可阅读数量</param>
|
||||
/// <param name="send_type">发件人类型 0系统 1用户 2竞技比赛</param>
|
||||
/// <param name="receive_id">接收人 -1表示群发</param>
|
||||
/// <param name="receive_type">0系统 1用户 2竞技比赛 1000以上表示系统消息 1000游戏游戏 2000竞技比赛消息 1000+gameid金币子游戏消息 2000+gameid朋友场子游戏消息</param>
|
||||
/// <param name="title">邮件标题</param>
|
||||
/// <param name="content">邮件内容</param>
|
||||
/// <param name="res">游戏资源</param>
|
||||
public static Task WriteEmlAysn(int send_id, int send_type, int receive_id, int receive_type, string title, string content, GameRes[] res = null)
|
||||
{
|
||||
|
||||
|
||||
return Task.Factory.StartNew(
|
||||
() => WriteEml(send_id, send_type, receive_id, receive_type, title, content, res)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
15
GameDAL/ExpressionsParser/ILambdaValue.cs
Normal file
15
GameDAL/ExpressionsParser/ILambdaValue.cs
Normal file
@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ExpressionsParser {
|
||||
/// <summary>
|
||||
/// Represents a value in expressions produced by <see cref="LambdaParser"/>.
|
||||
/// </summary>
|
||||
public interface ILambdaValue {
|
||||
object Value { get; }
|
||||
}
|
||||
|
||||
}
|
||||
24
GameDAL/ExpressionsParser/IValueComparer.cs
Normal file
24
GameDAL/ExpressionsParser/IValueComparer.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ExpressionsParser {
|
||||
/// <summary>
|
||||
/// Exposes a method that compares two objects.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Unlike <see cref="System.Collections.IComparer"/> this interface allows to return null as comparison result
|
||||
/// for case when values cannot be compared without throwing an exception.
|
||||
/// </remarks>
|
||||
public interface IValueComparer {
|
||||
|
||||
/// <summary>
|
||||
/// Compares two objects and returns a value indicating whether one is less than, equal to, or greater than the other.
|
||||
/// </summary>
|
||||
/// <returns>A signed integer that indicates the relative values of x and y or null if values cannot be compared.</returns>
|
||||
int? Compare(object x, object y);
|
||||
}
|
||||
|
||||
}
|
||||
154
GameDAL/ExpressionsParser/InvokeMethod.cs
Normal file
154
GameDAL/ExpressionsParser/InvokeMethod.cs
Normal file
@ -0,0 +1,154 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections;
|
||||
using System.Text;
|
||||
using System.Reflection;
|
||||
|
||||
namespace ExpressionsParser {
|
||||
|
||||
/// <summary>
|
||||
/// Invoke object's method that is most compatible with provided arguments
|
||||
/// </summary>
|
||||
internal class InvokeMethod {
|
||||
|
||||
public object TargetObject { get; set; }
|
||||
|
||||
public string MethodName { get; set; }
|
||||
|
||||
public InvokeMethod(object o, string methodName) {
|
||||
TargetObject = o;
|
||||
MethodName = methodName;
|
||||
}
|
||||
|
||||
protected MethodInfo FindMethod(Type[] argTypes) {
|
||||
if (TargetObject is Type) {
|
||||
// static method
|
||||
#if NET40
|
||||
return ((Type)TargetObject).GetMethod(MethodName, BindingFlags.Static | BindingFlags.Public);
|
||||
#else
|
||||
return ((Type)TargetObject).GetRuntimeMethod(MethodName, argTypes);
|
||||
#endif
|
||||
}
|
||||
#if NET40
|
||||
return TargetObject.GetType().GetMethod(MethodName, argTypes);
|
||||
#else
|
||||
return TargetObject.GetType().GetRuntimeMethod(MethodName, argTypes);
|
||||
#endif
|
||||
}
|
||||
|
||||
protected IEnumerable<MethodInfo> GetAllMethods() {
|
||||
if (TargetObject is Type) {
|
||||
#if NET40
|
||||
return ((Type)TargetObject).GetMethods(BindingFlags.Static | BindingFlags.Public);
|
||||
#else
|
||||
return ((Type)TargetObject).GetRuntimeMethods();
|
||||
#endif
|
||||
}
|
||||
#if NET40
|
||||
return TargetObject.GetType().GetMethods();
|
||||
#else
|
||||
return TargetObject.GetType().GetRuntimeMethods();
|
||||
#endif
|
||||
}
|
||||
|
||||
public object Invoke(object[] args) {
|
||||
Type[] argTypes = new Type[args.Length];
|
||||
for (int i = 0; i < argTypes.Length; i++)
|
||||
argTypes[i] = args[i] != null ? args[i].GetType() : typeof(object);
|
||||
|
||||
// strict matching first
|
||||
MethodInfo targetMethodInfo = FindMethod(argTypes);
|
||||
// fuzzy matching
|
||||
if (targetMethodInfo==null) {
|
||||
var methods = GetAllMethods();
|
||||
|
||||
foreach (var m in methods)
|
||||
if (m.Name==MethodName &&
|
||||
m.GetParameters().Length == args.Length &&
|
||||
CheckParamsCompatibility(m.GetParameters(), argTypes, args)) {
|
||||
targetMethodInfo = m;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (targetMethodInfo == null) {
|
||||
string[] argTypeNames = new string[argTypes.Length];
|
||||
for (int i=0; i<argTypeNames.Length; i++)
|
||||
argTypeNames[i] = argTypes[i].Name;
|
||||
string argTypeNamesStr = String.Join(",",argTypeNames);
|
||||
throw new MissingMemberException(
|
||||
(TargetObject is Type ? (Type)TargetObject : TargetObject.GetType()).FullName+"."+MethodName );
|
||||
}
|
||||
object[] argValues = PrepareActualValues(targetMethodInfo.GetParameters(),args);
|
||||
object res = null;
|
||||
try {
|
||||
res = targetMethodInfo.Invoke( TargetObject is Type ? null : TargetObject, argValues);
|
||||
} catch (TargetInvocationException tiEx) {
|
||||
if (tiEx.InnerException!=null)
|
||||
throw new Exception(tiEx.InnerException.Message, tiEx.InnerException);
|
||||
else {
|
||||
throw;
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
internal static bool IsInstanceOfType(Type t, object val) {
|
||||
#if NET40
|
||||
return t.IsInstanceOfType(val);
|
||||
#else
|
||||
return val!=null && t.GetTypeInfo().IsAssignableFrom(val.GetType().GetTypeInfo());
|
||||
#endif
|
||||
}
|
||||
|
||||
protected bool CheckParamsCompatibility(ParameterInfo[] paramsInfo, Type[] types, object[] values) {
|
||||
for (int i=0; i<paramsInfo.Length; i++) {
|
||||
Type paramType = paramsInfo[i].ParameterType;
|
||||
var val = values[i];
|
||||
if (IsInstanceOfType(paramType, val))
|
||||
continue;
|
||||
// null and reference types
|
||||
if (val==null &&
|
||||
#if NET40
|
||||
!paramType.IsValueType
|
||||
#else
|
||||
!paramType.GetTypeInfo().IsValueType
|
||||
#endif
|
||||
)
|
||||
continue;
|
||||
// possible autocast between generic/non-generic common types
|
||||
try {
|
||||
Convert.ChangeType(val, paramType, System.Globalization.CultureInfo.InvariantCulture);
|
||||
continue;
|
||||
} catch { }
|
||||
//if (ConvertManager.CanChangeType(types[i],paramType))
|
||||
// continue;
|
||||
// incompatible parameter
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
protected object[] PrepareActualValues(ParameterInfo[] paramsInfo, object[] values) {
|
||||
object[] res = new object[paramsInfo.Length];
|
||||
for (int i=0; i<paramsInfo.Length; i++) {
|
||||
if (values[i]==null || IsInstanceOfType( paramsInfo[i].ParameterType, values[i])) {
|
||||
res[i] = values[i];
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
res[i] = Convert.ChangeType( values[i], paramsInfo[i].ParameterType, System.Globalization.CultureInfo.InvariantCulture );
|
||||
continue;
|
||||
} catch {
|
||||
throw new InvalidCastException(
|
||||
String.Format("Invoke method '{0}': cannot convert argument #{1} from {2} to {3}",
|
||||
MethodName, i, values[i].GetType(), paramsInfo[i].ParameterType));
|
||||
}
|
||||
}
|
||||
return res;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
294
GameDAL/ExpressionsParser/LambdaParameterWrapper.cs
Normal file
294
GameDAL/ExpressionsParser/LambdaParameterWrapper.cs
Normal file
@ -0,0 +1,294 @@
|
||||
// using System;
|
||||
// using System.Collections.Generic;
|
||||
// using System.Collections;
|
||||
// using System.Linq;
|
||||
// using System.Text;
|
||||
// using System.Reflection;
|
||||
// using System.Globalization;
|
||||
//
|
||||
// namespace ExpressionsParser {
|
||||
//
|
||||
// /// <summary>
|
||||
// /// This is wrapper that makes runtime types conversions real.
|
||||
// /// </summary>
|
||||
// internal sealed class LambdaParameterWrapper : IComparable, ILambdaValue {
|
||||
// object _Value;
|
||||
// IValueComparer Cmp;
|
||||
//
|
||||
// public object Value {
|
||||
// get { return _Value; }
|
||||
// }
|
||||
//
|
||||
// public LambdaParameterWrapper(object val, IValueComparer valueComparer) {
|
||||
// Cmp = valueComparer;
|
||||
// if (val is LambdaParameterWrapper)
|
||||
// _Value = ((LambdaParameterWrapper)val).Value; // unwrap
|
||||
// else if (val is object[]) {
|
||||
// var objArr = (object[])val;
|
||||
// for (int i=0; i<objArr.Length; i++)
|
||||
// if (objArr[i] is LambdaParameterWrapper)
|
||||
// objArr[i] = ((LambdaParameterWrapper)objArr[i]).Value;
|
||||
// _Value = val;
|
||||
// } else {
|
||||
// _Value = val;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public int CompareTo(object obj) {
|
||||
// var objResolved = obj is LambdaParameterWrapper ? ((LambdaParameterWrapper)obj).Value : obj;
|
||||
// var cmpRes = Cmp.Compare(Value, objResolved);
|
||||
// if (!cmpRes.HasValue)
|
||||
// throw new ArgumentException();
|
||||
// return cmpRes.Value;
|
||||
// }
|
||||
//
|
||||
// public bool IsTrue {
|
||||
// get {
|
||||
// return Cmp.Compare(Value, true)==0;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public LambdaParameterWrapper CreateDictionary(object[] keys, object[] values) {
|
||||
// if (keys.Length!=values.Length)
|
||||
// throw new ArgumentException();
|
||||
// var d = new Dictionary<object,object>();
|
||||
// for (int i = 0; i < keys.Length; i++) {
|
||||
// var k = keys[i];
|
||||
// var v = values[i];
|
||||
// // unwrap
|
||||
// if (k is LambdaParameterWrapper)
|
||||
// k = ((LambdaParameterWrapper)k).Value;
|
||||
// if (v is LambdaParameterWrapper)
|
||||
// v = ((LambdaParameterWrapper)v).Value;
|
||||
// d[k] = v;
|
||||
// }
|
||||
// return new LambdaParameterWrapper(d, Cmp);
|
||||
// }
|
||||
//
|
||||
// public LambdaParameterWrapper InvokeMethod(object obj, string methodName, object[] args) {
|
||||
// if (obj is LambdaParameterWrapper)
|
||||
// obj = ((LambdaParameterWrapper)obj).Value;
|
||||
//
|
||||
// if (obj == null)
|
||||
// throw new NullReferenceException(String.Format("Method {0} target is null", methodName));
|
||||
//
|
||||
// var argsResolved = new object[args.Length];
|
||||
// for (int i = 0; i < args.Length; i++)
|
||||
// argsResolved[i] = args[i] is LambdaParameterWrapper ? ((LambdaParameterWrapper)args[i]).Value : args[i];
|
||||
//
|
||||
// var invoke = new InvokeMethod(obj, methodName);
|
||||
// var res = invoke.Invoke(argsResolved);
|
||||
// return new LambdaParameterWrapper(res, Cmp);
|
||||
// }
|
||||
//
|
||||
// public LambdaParameterWrapper InvokeDelegate(object obj, object[] args) {
|
||||
// if (obj is LambdaParameterWrapper)
|
||||
// obj = ((LambdaParameterWrapper)obj).Value;
|
||||
// if (obj == null)
|
||||
// throw new NullReferenceException("Delegate is null");
|
||||
// if (!(obj is Delegate))
|
||||
// throw new NullReferenceException(String.Format("{0} is not a delegate", obj.GetType()));
|
||||
// var deleg = (Delegate)obj;
|
||||
//
|
||||
// var delegParams =
|
||||
// #if NET40
|
||||
// deleg.Method.GetParameters();
|
||||
// #else
|
||||
// deleg.GetMethodInfo().GetParameters();
|
||||
// #endif
|
||||
// if (delegParams.Length != args.Length)
|
||||
// throw new TargetParameterCountException(
|
||||
// String.Format("Target delegate expects {0} parameters", delegParams.Length));
|
||||
//
|
||||
// var resolvedArgs = new object[args.Length];
|
||||
// for (int i = 0; i < resolvedArgs.Length; i++) {
|
||||
// var argObj = args[i] is LambdaParameterWrapper ? ((LambdaParameterWrapper)args[i]).Value : args[i];
|
||||
// if (!ExpressionsParser.InvokeMethod.IsInstanceOfType(delegParams[i].ParameterType, argObj))
|
||||
// argObj = Convert.ChangeType(argObj, delegParams[i].ParameterType, CultureInfo.InvariantCulture);
|
||||
// resolvedArgs[i] = argObj;
|
||||
// }
|
||||
// return new LambdaParameterWrapper( deleg.DynamicInvoke(resolvedArgs), Cmp );
|
||||
// }
|
||||
//
|
||||
// public LambdaParameterWrapper InvokePropertyOrField(object obj, string propertyName) {
|
||||
// if (obj == null)
|
||||
// throw new NullReferenceException(String.Format("Property or field {0} target is null", propertyName));
|
||||
// if (obj is LambdaParameterWrapper)
|
||||
// obj = ((LambdaParameterWrapper)obj).Value;
|
||||
//
|
||||
// #if NET40
|
||||
// var prop = obj.GetType().GetProperty(propertyName);
|
||||
// #else
|
||||
// var prop = obj.GetType().GetRuntimeProperty(propertyName);
|
||||
// #endif
|
||||
//
|
||||
// if (prop != null) {
|
||||
// var propVal = prop.GetValue(obj, null);
|
||||
// return new LambdaParameterWrapper(propVal, Cmp);
|
||||
// }
|
||||
// #if NET40
|
||||
// var fld = obj.GetType().GetField(propertyName);
|
||||
// #else
|
||||
// var fld = obj.GetType().GetRuntimeField(propertyName);
|
||||
// #endif
|
||||
// if (fld != null) {
|
||||
// var fldVal = fld.GetValue(obj);
|
||||
// return new LambdaParameterWrapper(fldVal, Cmp);
|
||||
// }
|
||||
// throw new MissingMemberException(obj.GetType().ToString()+"."+propertyName);
|
||||
// }
|
||||
//
|
||||
// public LambdaParameterWrapper InvokeIndexer(object obj, object[] args) {
|
||||
// if (obj == null)
|
||||
// throw new NullReferenceException(String.Format("Indexer target is null"));
|
||||
// if (obj is LambdaParameterWrapper)
|
||||
// obj = ((LambdaParameterWrapper)obj).Value;
|
||||
//
|
||||
// var argsResolved = new object[args.Length];
|
||||
// for (int i = 0; i < args.Length; i++)
|
||||
// argsResolved[i] = args[i] is LambdaParameterWrapper ? ((LambdaParameterWrapper)args[i]).Value : args[i];
|
||||
//
|
||||
// if (obj is Array) {
|
||||
// var objArr = (Array)obj;
|
||||
// if (objArr.Rank != args.Length) {
|
||||
// throw new RankException(String.Format("Array rank ({0}) doesn't match number of indicies ({1})",
|
||||
// objArr.Rank, args.Length));
|
||||
// }
|
||||
// var indicies = new int[argsResolved.Length];
|
||||
// for (int i = 0; i < argsResolved.Length; i++)
|
||||
// indicies[i] = Convert.ToInt32(argsResolved[i]);
|
||||
//
|
||||
// var res = objArr.GetValue(indicies);
|
||||
// return new LambdaParameterWrapper(res, Cmp);
|
||||
// } else {
|
||||
// // indexer method
|
||||
// var invoke = new InvokeMethod(obj, "get_Item");
|
||||
// var res = invoke.Invoke(argsResolved);
|
||||
// return new LambdaParameterWrapper(res, Cmp);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public static LambdaParameterWrapper operator +(LambdaParameterWrapper c1, LambdaParameterWrapper c2) {
|
||||
// if (c1.Value is string || c2.Value is string) {
|
||||
// return new LambdaParameterWrapper( Convert.ToString(c1.Value) + Convert.ToString(c2.Value), c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// if (c1.Value is TimeSpan c1TimeSpan && c2.Value is DateTime c2DateTime)
|
||||
// {
|
||||
// return new LambdaParameterWrapper(c2DateTime.Add(c1TimeSpan), c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// if (c1.Value is DateTime c1DateTime && c2.Value is TimeSpan c2TimeSpan)
|
||||
// {
|
||||
// return new LambdaParameterWrapper(c1DateTime.Add(c2TimeSpan), c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// if (c1.Value is TimeSpan c1ts && c2.Value is TimeSpan c2ts)
|
||||
// {
|
||||
// return new LambdaParameterWrapper(c1ts + c2ts, c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// var c1decimal = Convert.ToDecimal(c1.Value, CultureInfo.InvariantCulture);
|
||||
// var c2decimal = Convert.ToDecimal(c2.Value, CultureInfo.InvariantCulture);
|
||||
// return new LambdaParameterWrapper(c1decimal + c2decimal, c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// public static LambdaParameterWrapper operator -(LambdaParameterWrapper c1, LambdaParameterWrapper c2) {
|
||||
// if (c1.Value is TimeSpan c1ts && c2.Value is TimeSpan c2ts)
|
||||
// {
|
||||
// return new LambdaParameterWrapper(c1ts - c2ts, c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// if (c1.Value is DateTime c1dt && c2.Value is DateTime c2dt)
|
||||
// {
|
||||
// return new LambdaParameterWrapper(c1dt - c2dt, c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// if (c1.Value is DateTime c1DateTime && c2.Value is TimeSpan c2TimeSpan)
|
||||
// {
|
||||
// return new LambdaParameterWrapper(c1DateTime.Add(c2TimeSpan.Negate()), c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// var c1decimal = Convert.ToDecimal(c1.Value, CultureInfo.InvariantCulture);
|
||||
// var c2decimal = Convert.ToDecimal(c2.Value, CultureInfo.InvariantCulture);
|
||||
// return new LambdaParameterWrapper(c1decimal - c2decimal, c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// public static LambdaParameterWrapper operator -(LambdaParameterWrapper c1) {
|
||||
// if(c1.Value is TimeSpan ts)
|
||||
// {
|
||||
// return new LambdaParameterWrapper(ts.Negate(), c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// var c1decimal = Convert.ToDecimal(c1.Value, CultureInfo.InvariantCulture);
|
||||
// return new LambdaParameterWrapper(-c1decimal, c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// public static LambdaParameterWrapper operator *(LambdaParameterWrapper c1, LambdaParameterWrapper c2) {
|
||||
// var c1decimal = Convert.ToDecimal(c1.Value, CultureInfo.InvariantCulture);
|
||||
// var c2decimal = Convert.ToDecimal(c2.Value, CultureInfo.InvariantCulture);
|
||||
// return new LambdaParameterWrapper(c1decimal * c2decimal, c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// public static LambdaParameterWrapper operator /(LambdaParameterWrapper c1, LambdaParameterWrapper c2) {
|
||||
// var c1decimal = Convert.ToDecimal(c1.Value, CultureInfo.InvariantCulture);
|
||||
// var c2decimal = Convert.ToDecimal(c2.Value, CultureInfo.InvariantCulture);
|
||||
// return new LambdaParameterWrapper(c1decimal / c2decimal, c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// public static LambdaParameterWrapper operator %(LambdaParameterWrapper c1, LambdaParameterWrapper c2) {
|
||||
// var c1decimal = Convert.ToDecimal(c1.Value, CultureInfo.InvariantCulture);
|
||||
// var c2decimal = Convert.ToDecimal(c2.Value, CultureInfo.InvariantCulture);
|
||||
// return new LambdaParameterWrapper(c1decimal % c2decimal, c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// public static bool operator ==(LambdaParameterWrapper c1, LambdaParameterWrapper c2) {
|
||||
// return c1.Cmp.Compare(c1.Value, c2.Value)==0;
|
||||
// }
|
||||
// public static bool operator ==(LambdaParameterWrapper c1, bool c2) {
|
||||
// return c1.Cmp.Compare(c1.Value, c2)==0;
|
||||
// }
|
||||
// public static bool operator ==(bool c1, LambdaParameterWrapper c2) {
|
||||
// return c2.Cmp.Compare(c1, c2.Value)==0;
|
||||
// }
|
||||
//
|
||||
// public static bool operator !=(LambdaParameterWrapper c1, LambdaParameterWrapper c2) {
|
||||
// return c1.Cmp.Compare(c1.Value, c2.Value)!=0;
|
||||
// }
|
||||
// public static bool operator !=(LambdaParameterWrapper c1, bool c2) {
|
||||
// return c1.Cmp.Compare(c1.Value, c2)!=0;
|
||||
// }
|
||||
// public static bool operator !=(bool c1, LambdaParameterWrapper c2) {
|
||||
// return c2.Cmp.Compare(c1, c2.Value)!=0;
|
||||
// }
|
||||
//
|
||||
// public static bool operator >(LambdaParameterWrapper c1, LambdaParameterWrapper c2) {
|
||||
// return c1.Cmp.Compare(c1.Value, c2.Value)>0;
|
||||
// }
|
||||
// public static bool operator <(LambdaParameterWrapper c1, LambdaParameterWrapper c2) {
|
||||
// return c1.Cmp.Compare(c1.Value, c2.Value) < 0;
|
||||
// }
|
||||
//
|
||||
// public static bool operator >=(LambdaParameterWrapper c1, LambdaParameterWrapper c2) {
|
||||
// return c1.Cmp.Compare(c1.Value, c2.Value)>= 0;
|
||||
// }
|
||||
// public static bool operator <=(LambdaParameterWrapper c1, LambdaParameterWrapper c2) {
|
||||
// return c1.Cmp.Compare(c1.Value, c2.Value)<=0;
|
||||
// }
|
||||
//
|
||||
// public static LambdaParameterWrapper operator !(LambdaParameterWrapper c1) {
|
||||
// var c1bool = c1.Cmp.Compare(c1.Value, true)==0;
|
||||
// return new LambdaParameterWrapper( !c1bool, c1.Cmp);
|
||||
// }
|
||||
//
|
||||
// public static bool operator true(LambdaParameterWrapper x) {
|
||||
// return x.IsTrue;
|
||||
// }
|
||||
//
|
||||
// public static bool operator false(LambdaParameterWrapper x) {
|
||||
// return !x.IsTrue;
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// }
|
||||
675
GameDAL/ExpressionsParser/LambdaParser.cs
Normal file
675
GameDAL/ExpressionsParser/LambdaParser.cs
Normal file
@ -0,0 +1,675 @@
|
||||
// using System;
|
||||
// using System.Collections.Generic;
|
||||
// using System.Linq;
|
||||
// using System.Linq.Expressions;
|
||||
// using System.Text;
|
||||
// using System.Reflection;
|
||||
// using System.ComponentModel;
|
||||
// using System.Globalization;
|
||||
//
|
||||
//
|
||||
// namespace ExpressionsParser {
|
||||
//
|
||||
// /// <summary>
|
||||
// /// Runtime parser for string expressions (formulas, method calls etc) into LINQ expression tree or lambda delegate.
|
||||
// /// </summary>
|
||||
// public class LambdaParser {
|
||||
//
|
||||
// static readonly char[] delimiters = new char[] {
|
||||
// '(', ')', '[', ']', '?', ':', '.', ',', '=', '<', '>', '!', '&', '|', '*', '/', '%', '+','-', '{', '}'};
|
||||
// static readonly char[] specialNameChars = new char[] {
|
||||
// '_' };
|
||||
// const char charQuote = '"';
|
||||
// static readonly string[] mulOps = new[] {"*", "/", "%" };
|
||||
// static readonly string[] addOps = new[] { "+", "-" };
|
||||
// static readonly string[] eqOps = new[] { "==", "!=", "<", ">", "<=", ">=" };
|
||||
//
|
||||
// readonly IDictionary<string, CompiledExpression> CachedExpressions = new Dictionary<string, CompiledExpression>();
|
||||
// readonly object _lock = new object();
|
||||
//
|
||||
// /// <summary>
|
||||
// /// Gets or sets whether LambdaParser should use the cache for parsed expressions.
|
||||
// /// </summary>
|
||||
// public bool UseCache { get; set; }
|
||||
//
|
||||
// /// <summary>
|
||||
// /// Allows usage of "=" for equality comparison (in addition to "=="). False by default.
|
||||
// /// </summary>
|
||||
// public bool AllowSingleEqualSign { get; set; }
|
||||
//
|
||||
// /// <summary>
|
||||
// /// Gets value comparer used by the parser for comparison operators.
|
||||
// /// </summary>
|
||||
// public IValueComparer Comparer { get; private set; }
|
||||
//
|
||||
// public LambdaParser() {
|
||||
// UseCache = true;
|
||||
// AllowSingleEqualSign = false;
|
||||
// Comparer = ValueComparer.Instance;
|
||||
// }
|
||||
//
|
||||
// public LambdaParser(IValueComparer valueComparer) : this() {
|
||||
// Comparer = valueComparer;
|
||||
// }
|
||||
//
|
||||
// internal class ExtractParamsVisitor : ExpressionVisitor {
|
||||
// internal List<ParameterExpression> ParamsList;
|
||||
// public ExtractParamsVisitor() {
|
||||
// ParamsList = new List<ParameterExpression>();
|
||||
// }
|
||||
//
|
||||
// public override Expression Visit(Expression node) {
|
||||
// if (node!=null && node.NodeType == ExpressionType.Parameter)
|
||||
// ParamsList.Add( (ParameterExpression)node);
|
||||
// return base.Visit(node);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// public static ParameterExpression[] GetExpressionParameters(Expression expr) {
|
||||
// var paramsVisitor = new ExtractParamsVisitor();
|
||||
// paramsVisitor.Visit(expr);
|
||||
// return paramsVisitor.ParamsList.ToArray();
|
||||
// }
|
||||
//
|
||||
// public object Eval(string expr, IDictionary<string, object> vars) {
|
||||
// return Eval(expr, (varName) => {
|
||||
// object val = null;
|
||||
// vars.TryGetValue(varName, out val);
|
||||
// return val;
|
||||
// });
|
||||
// }
|
||||
//
|
||||
// public LambdaExpression CurrentExpression { get; private set; }
|
||||
// public Delegate CurrentCompileDelegate { get; private set; }
|
||||
//
|
||||
// public object Eval(string expr, Func<string,object> getVarValue) {
|
||||
// CompiledExpression compiledExpr = null;
|
||||
// if (UseCache) {
|
||||
// lock (_lock) {
|
||||
// CachedExpressions.TryGetValue(expr, out compiledExpr);
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// if (compiledExpr == null) {
|
||||
// var linqExpr = Parse(expr);
|
||||
// compiledExpr = new CompiledExpression() {
|
||||
// Parameters = GetExpressionParameters(linqExpr)
|
||||
// };
|
||||
// CurrentExpression = Expression.Lambda(linqExpr, compiledExpr.Parameters);
|
||||
// CurrentCompileDelegate = compiledExpr.Lambda = CurrentExpression.Compile();
|
||||
//
|
||||
// if (UseCache)
|
||||
// lock (_lock) {
|
||||
// CachedExpressions[expr] = compiledExpr;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// var valuesList = new List<object>();
|
||||
// foreach (var paramExpr in compiledExpr.Parameters) {
|
||||
// valuesList.Add( new LambdaParameterWrapper( getVarValue(paramExpr.Name), Comparer) );
|
||||
// }
|
||||
//
|
||||
// var lambdaRes = compiledExpr.Lambda.DynamicInvoke(valuesList.ToArray());
|
||||
// if (lambdaRes is LambdaParameterWrapper)
|
||||
// lambdaRes = ((LambdaParameterWrapper)lambdaRes).Value;
|
||||
// return lambdaRes;
|
||||
// }
|
||||
//
|
||||
//
|
||||
// public Expression Parse(string expr) {
|
||||
// var parseResult = ParseConditional(expr, 0);
|
||||
// var lastLexem = ReadLexem(expr, parseResult.End);
|
||||
// if (lastLexem.Type != LexemType.Stop)
|
||||
// throw new LambdaParserException(expr, parseResult.End, "Invalid expression");
|
||||
// return parseResult.Expr;
|
||||
// }
|
||||
//
|
||||
// protected Lexem ReadLexem(string s, int startIdx) {
|
||||
// var lexem = new Lexem();
|
||||
// lexem.Type = LexemType.Unknown;
|
||||
// lexem.Expr = s;
|
||||
// lexem.Start = startIdx;
|
||||
// lexem.End = startIdx;
|
||||
// while (lexem.End < s.Length) {
|
||||
// if (Array.IndexOf(delimiters, s[lexem.End]) >= 0) {
|
||||
// if (lexem.Type == LexemType.Unknown) {
|
||||
// lexem.End++;
|
||||
// lexem.Type = LexemType.Delimiter;
|
||||
// return lexem;
|
||||
// }
|
||||
// if (lexem.Type != LexemType.StringConstant && (lexem.Type != LexemType.NumberConstant || s[lexem.End] != '.'))
|
||||
// return lexem; // stop
|
||||
// } else if (char.IsSeparator(s[lexem.End])) {
|
||||
// if (lexem.Type != LexemType.StringConstant && lexem.Type != LexemType.Unknown)
|
||||
// return lexem; // stop
|
||||
// } else if (char.IsLetter(s[lexem.End])) {
|
||||
// if (lexem.Type == LexemType.Unknown)
|
||||
// lexem.Type = LexemType.Name;
|
||||
// } else if (char.IsDigit(s[lexem.End])) {
|
||||
// if (lexem.Type == LexemType.Unknown)
|
||||
// lexem.Type = LexemType.NumberConstant;
|
||||
// } else if (Array.IndexOf(specialNameChars, s[lexem.End]) >= 0) {
|
||||
// if (lexem.Type == LexemType.Unknown || lexem.Type==LexemType.Name) {
|
||||
// lexem.Type = LexemType.Name;
|
||||
// } else if (lexem.Type!=LexemType.StringConstant)
|
||||
// return lexem;
|
||||
// } else if (s[lexem.End] == charQuote) {
|
||||
// if (lexem.Type == LexemType.Unknown)
|
||||
// lexem.Type = LexemType.StringConstant;
|
||||
// else {
|
||||
// if (lexem.Type == LexemType.StringConstant) {
|
||||
// // check for "" combination
|
||||
// if (((lexem.End + 1) >= s.Length || s[lexem.End + 1] != charQuote)) {
|
||||
// lexem.End++;
|
||||
// return lexem;
|
||||
// } else
|
||||
// if ((lexem.End + 1) < s.Length)
|
||||
// lexem.End++; // skip next quote
|
||||
// } else {
|
||||
// return lexem;
|
||||
// }
|
||||
// }
|
||||
// } else if (char.IsControl(s[lexem.End]) && lexem.Type != LexemType.Unknown && lexem.Type != LexemType.StringConstant)
|
||||
// return lexem;
|
||||
//
|
||||
// // goto next char
|
||||
// lexem.End++;
|
||||
// }
|
||||
//
|
||||
// if (lexem.Type == LexemType.Unknown) {
|
||||
// lexem.Type = LexemType.Stop;
|
||||
// return lexem;
|
||||
// }
|
||||
// if (lexem.Type == LexemType.StringConstant)
|
||||
// throw new LambdaParserException(s, startIdx, "Unterminated string constant");
|
||||
// return lexem;
|
||||
// }
|
||||
//
|
||||
//
|
||||
// static readonly ConstructorInfo LambdaParameterWrapperConstructor =
|
||||
// #if NET40
|
||||
// typeof(LambdaParameterWrapper).GetConstructor(new[] { typeof(object) });
|
||||
// #else
|
||||
// typeof(LambdaParameterWrapper).GetTypeInfo().DeclaredConstructors.First();
|
||||
// #endif
|
||||
//
|
||||
// protected ParseResult ParseConditional(string expr, int start) {
|
||||
// var testExpr = ParseOr(expr, start);
|
||||
// var ifLexem = ReadLexem(expr, testExpr.End);
|
||||
// if (ifLexem.Type == LexemType.Delimiter && ifLexem.GetValue() == "?") {
|
||||
// // read positive expr
|
||||
// var positiveOp = ParseOr(expr, ifLexem.End);
|
||||
// var positiveOpExpr = Expression.New(LambdaParameterWrapperConstructor,
|
||||
// Expression.Convert(positiveOp.Expr,typeof(object)),
|
||||
// Expression.Constant(Comparer));
|
||||
//
|
||||
// var elseLexem = ReadLexem(expr, positiveOp.End);
|
||||
// if (elseLexem.Type == LexemType.Delimiter && elseLexem.GetValue() == ":") {
|
||||
// var negativeOp = ParseOr(expr, elseLexem.End);
|
||||
// var negativeOpExpr = Expression.New(LambdaParameterWrapperConstructor,
|
||||
// Expression.Convert( negativeOp.Expr, typeof(object)),
|
||||
// Expression.Constant(Comparer));
|
||||
// return new ParseResult() {
|
||||
// End = negativeOp.End,
|
||||
// Expr = Expression.Condition( Expression.IsTrue( testExpr.Expr ), positiveOpExpr, negativeOpExpr)
|
||||
// };
|
||||
//
|
||||
// } else {
|
||||
// throw new LambdaParserException(expr, positiveOp.End, "Expected ':'");
|
||||
// }
|
||||
// }
|
||||
// return testExpr;
|
||||
// }
|
||||
//
|
||||
// Expression WrapLambdaParameterIsTrueIfNeeded(Expression expr) {
|
||||
// if (expr.Type == typeof(LambdaParameterWrapper))
|
||||
// return Expression.Property(expr, "IsTrue");
|
||||
// return expr;
|
||||
// }
|
||||
//
|
||||
// protected ParseResult ParseOr(string expr, int start) {
|
||||
// var firstOp = ParseAnd(expr, start);
|
||||
// do {
|
||||
// var opLexem = ReadLexem(expr, firstOp.End);
|
||||
// var isOr = false;
|
||||
// if (opLexem.Type == LexemType.Name && opLexem.GetValue() == "or") {
|
||||
// isOr = true;
|
||||
// } else if (opLexem.Type == LexemType.Delimiter && opLexem.GetValue() == "|") {
|
||||
// opLexem = ReadLexem(expr, opLexem.End);
|
||||
// if (opLexem.Type == LexemType.Delimiter && opLexem.GetValue() == "|")
|
||||
// isOr = true;
|
||||
// }
|
||||
//
|
||||
// if (isOr) {
|
||||
// var secondOp = ParseOr(expr, opLexem.End);
|
||||
// firstOp = new ParseResult() {
|
||||
// End = secondOp.End,
|
||||
// Expr = Expression.OrElse(
|
||||
// WrapLambdaParameterIsTrueIfNeeded(firstOp.Expr),
|
||||
// WrapLambdaParameterIsTrueIfNeeded(secondOp.Expr) )
|
||||
// };
|
||||
// } else
|
||||
// break;
|
||||
// } while (true);
|
||||
// return firstOp;
|
||||
// }
|
||||
//
|
||||
// protected ParseResult ParseAnd(string expr, int start) {
|
||||
// var firstOp = ParseEq(expr, start);
|
||||
// do {
|
||||
// var opLexem = ReadLexem(expr, firstOp.End);
|
||||
// var isAnd = false;
|
||||
// if (opLexem.Type == LexemType.Name && opLexem.GetValue() == "and") {
|
||||
// isAnd = true;
|
||||
// } else if (opLexem.Type == LexemType.Delimiter && opLexem.GetValue() == "&") {
|
||||
// opLexem = ReadLexem(expr, opLexem.End);
|
||||
// if (opLexem.Type == LexemType.Delimiter && opLexem.GetValue() == "&")
|
||||
// isAnd = true;
|
||||
// }
|
||||
//
|
||||
// if (isAnd) {
|
||||
// var secondOp = ParseAnd(expr, opLexem.End);
|
||||
// firstOp = new ParseResult() {
|
||||
// End = secondOp.End,
|
||||
// Expr = Expression.AndAlso(
|
||||
// WrapLambdaParameterIsTrueIfNeeded(firstOp.Expr),
|
||||
// WrapLambdaParameterIsTrueIfNeeded(secondOp.Expr))
|
||||
// };
|
||||
// } else
|
||||
// break;
|
||||
// } while (true);
|
||||
// return firstOp;
|
||||
// }
|
||||
//
|
||||
// protected ParseResult ParseEq(string expr, int start) {
|
||||
// var firstOp = ParseAdditive(expr, start);
|
||||
// do {
|
||||
// var opLexem = ReadLexem(expr, firstOp.End);
|
||||
// if (opLexem.Type == LexemType.Delimiter) {
|
||||
// var nextOpLexem = ReadLexem(expr, opLexem.End);
|
||||
// if (nextOpLexem.Type == LexemType.Delimiter) {
|
||||
// var opVal = opLexem.GetValue() + nextOpLexem.GetValue();
|
||||
// if (eqOps.Contains(opVal)) {
|
||||
// var secondOp = ParseAdditive(expr, nextOpLexem.End);
|
||||
//
|
||||
// switch (opVal) {
|
||||
// case "==":
|
||||
// firstOp = new ParseResult() {
|
||||
// End = secondOp.End,
|
||||
// Expr = Expression.Equal(firstOp.Expr, secondOp.Expr)
|
||||
// };
|
||||
// continue;
|
||||
// case "<>":
|
||||
// case "!=":
|
||||
// firstOp = new ParseResult() {
|
||||
// End = secondOp.End,
|
||||
// Expr = Expression.NotEqual(firstOp.Expr, secondOp.Expr)
|
||||
// };
|
||||
// continue;
|
||||
// case ">=":
|
||||
// firstOp = new ParseResult() {
|
||||
// End = secondOp.End,
|
||||
// Expr = Expression.GreaterThanOrEqual(firstOp.Expr, secondOp.Expr)
|
||||
// };
|
||||
// continue;
|
||||
// case "<=":
|
||||
// firstOp = new ParseResult() {
|
||||
// End = secondOp.End,
|
||||
// Expr = Expression.LessThanOrEqual(firstOp.Expr, secondOp.Expr)
|
||||
// };
|
||||
// continue;
|
||||
//
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// }
|
||||
//
|
||||
// if (opLexem.GetValue() == ">" || opLexem.GetValue() == "<"
|
||||
// || (AllowSingleEqualSign && opLexem.GetValue() == "=") ) {
|
||||
// var secondOp = ParseAdditive(expr, opLexem.End);
|
||||
// switch (opLexem.GetValue()) {
|
||||
// case ">":
|
||||
// firstOp = new ParseResult() {
|
||||
// End = secondOp.End,
|
||||
// Expr = Expression.GreaterThan(firstOp.Expr, secondOp.Expr)
|
||||
// };
|
||||
// continue;
|
||||
// case "<":
|
||||
// firstOp = new ParseResult() {
|
||||
// End = secondOp.End,
|
||||
// Expr = Expression.LessThan(firstOp.Expr, secondOp.Expr)
|
||||
// };
|
||||
// continue;
|
||||
// case "=":
|
||||
// firstOp = new ParseResult() {
|
||||
// End = secondOp.End,
|
||||
// Expr = Expression.Equal(firstOp.Expr, secondOp.Expr)
|
||||
// };
|
||||
// continue;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// }
|
||||
// break;
|
||||
// } while (true);
|
||||
// return firstOp;
|
||||
// }
|
||||
//
|
||||
//
|
||||
// protected ParseResult ParseAdditive(string expr, int start) {
|
||||
// var firstOp = ParseMultiplicative(expr, start);
|
||||
// do {
|
||||
// var opLexem = ReadLexem(expr, firstOp.End);
|
||||
// if (opLexem.Type == LexemType.Delimiter && addOps.Contains(opLexem.GetValue())) {
|
||||
// var secondOp = ParseMultiplicative(expr, opLexem.End);
|
||||
// var res = new ParseResult() { End = secondOp.End };
|
||||
// switch (opLexem.GetValue()) {
|
||||
// case "+":
|
||||
// res.Expr = Expression.Add(firstOp.Expr, secondOp.Expr);
|
||||
// break;
|
||||
// case "-":
|
||||
// res.Expr = Expression.Subtract(firstOp.Expr, secondOp.Expr);
|
||||
// break;
|
||||
// }
|
||||
// firstOp = res;
|
||||
// continue;
|
||||
// }
|
||||
// break;
|
||||
// } while (true);
|
||||
// return firstOp;
|
||||
// }
|
||||
//
|
||||
// protected ParseResult ParseMultiplicative(string expr, int start) {
|
||||
// var firstOp = ParseUnary(expr, start);
|
||||
// do {
|
||||
// var opLexem = ReadLexem(expr, firstOp.End);
|
||||
// if (opLexem.Type == LexemType.Delimiter && mulOps.Contains(opLexem.GetValue())) {
|
||||
// var secondOp = ParseUnary(expr, opLexem.End);
|
||||
// var res = new ParseResult() { End = secondOp.End };
|
||||
// switch (opLexem.GetValue()) {
|
||||
// case "*":
|
||||
// res.Expr = Expression.Multiply(firstOp.Expr, secondOp.Expr);
|
||||
// break;
|
||||
// case "/":
|
||||
// res.Expr = Expression.Divide(firstOp.Expr, secondOp.Expr);
|
||||
// break;
|
||||
// case "%":
|
||||
// res.Expr = Expression.Modulo(firstOp.Expr, secondOp.Expr);
|
||||
// break;
|
||||
// }
|
||||
// firstOp = res;
|
||||
// continue;
|
||||
// }
|
||||
// break;
|
||||
// } while (true);
|
||||
// return firstOp;
|
||||
// }
|
||||
//
|
||||
// protected ParseResult ParseUnary(string expr, int start) {
|
||||
// var opLexem = ReadLexem(expr, start);
|
||||
// if (opLexem.Type == LexemType.Delimiter) {
|
||||
// switch (opLexem.GetValue()) {
|
||||
// case "-": {
|
||||
// var operand = ParsePrimary(expr, opLexem.End);
|
||||
// operand.Expr = Expression.Negate(operand.Expr);
|
||||
// return operand;
|
||||
// }
|
||||
// case "!": {
|
||||
// var operand = ParsePrimary(expr, opLexem.End);
|
||||
// operand.Expr = Expression.Not(operand.Expr);
|
||||
// return operand;
|
||||
// }
|
||||
// }
|
||||
// }
|
||||
// return ParsePrimary(expr, start);
|
||||
// }
|
||||
//
|
||||
// private static MethodInfo GetLambdaParameterWrapperMethod(string methodName) {
|
||||
// #if NET40
|
||||
// return typeof(LambdaParameterWrapper).GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public);
|
||||
// #else
|
||||
// return typeof(LambdaParameterWrapper).GetTypeInfo().DeclaredMethods.Where(m=>m.Name==methodName).First();
|
||||
// #endif
|
||||
// }
|
||||
//
|
||||
// static readonly MethodInfo InvokeMethodMI = GetLambdaParameterWrapperMethod("InvokeMethod");
|
||||
//
|
||||
// static readonly MethodInfo InvokeDelegateMI = GetLambdaParameterWrapperMethod("InvokeDelegate");
|
||||
//
|
||||
// static readonly MethodInfo InvokePropertyOrFieldMI = GetLambdaParameterWrapperMethod("InvokePropertyOrField");
|
||||
//
|
||||
// static readonly MethodInfo InvokeIndexerMI = GetLambdaParameterWrapperMethod("InvokeIndexer");
|
||||
//
|
||||
// static readonly MethodInfo CreateDictionaryMI = GetLambdaParameterWrapperMethod("CreateDictionary");
|
||||
//
|
||||
// protected ParseResult ParsePrimary(string expr, int start) {
|
||||
// var val = ParseValue(expr, start);
|
||||
// do {
|
||||
// var lexem = ReadLexem(expr, val.End);
|
||||
// if (lexem.Type==LexemType.Delimiter) {
|
||||
// if (lexem.GetValue() == ".") { // member or method
|
||||
// var memberLexem = ReadLexem(expr, lexem.End);
|
||||
// if (memberLexem.Type == LexemType.Name) {
|
||||
// var openCallLexem = ReadLexem(expr, memberLexem.End);
|
||||
// if (openCallLexem.Type == LexemType.Delimiter && openCallLexem.GetValue() == "(") {
|
||||
// var methodParams = new List<Expression>();
|
||||
// var paramsEnd = ReadCallArguments(expr, openCallLexem.End, ")", methodParams);
|
||||
// var paramsExpr = Expression.NewArrayInit(typeof(object), methodParams);
|
||||
// val = new ParseResult() {
|
||||
// End = paramsEnd,
|
||||
// Expr = Expression.Call(
|
||||
// Expression.Constant(new LambdaParameterWrapper(null,Comparer)),
|
||||
// InvokeMethodMI,
|
||||
// val.Expr,
|
||||
// Expression.Constant(memberLexem.GetValue()),
|
||||
// paramsExpr)
|
||||
// };
|
||||
// continue;
|
||||
// } else {
|
||||
// // member
|
||||
// val = new ParseResult() {
|
||||
// End = memberLexem.End,
|
||||
// Expr = Expression.Call(
|
||||
// Expression.Constant(new LambdaParameterWrapper(null, Comparer)),
|
||||
// InvokePropertyOrFieldMI,
|
||||
// val.Expr, Expression.Constant(memberLexem.GetValue()))
|
||||
// };
|
||||
// continue;
|
||||
// }
|
||||
// }
|
||||
// } else if (lexem.GetValue()=="[") {
|
||||
// var indexerParams = new List<Expression>();
|
||||
// var paramsEnd = ReadCallArguments(expr, lexem.End, "]", indexerParams);
|
||||
// val = new ParseResult() {
|
||||
// End = paramsEnd,
|
||||
// Expr = Expression.Call(
|
||||
// Expression.Constant(new LambdaParameterWrapper(null, Comparer)),
|
||||
// InvokeIndexerMI, val.Expr,
|
||||
// Expression.NewArrayInit(typeof(object), indexerParams)
|
||||
// )
|
||||
// };
|
||||
// continue;
|
||||
// } else if (lexem.GetValue()=="(") {
|
||||
// var methodParams = new List<Expression>();
|
||||
// var paramsEnd = ReadCallArguments(expr, lexem.End, ")", methodParams);
|
||||
// var paramsExpr = Expression.NewArrayInit(typeof(object), methodParams);
|
||||
// val = new ParseResult() {
|
||||
// End = paramsEnd,
|
||||
// Expr = Expression.Call(
|
||||
// Expression.Constant(new LambdaParameterWrapper(null, Comparer)),
|
||||
// InvokeDelegateMI,
|
||||
// val.Expr, paramsExpr)
|
||||
// };
|
||||
// continue;
|
||||
// }
|
||||
// }
|
||||
// break;
|
||||
// } while (true);
|
||||
// return val;
|
||||
// }
|
||||
//
|
||||
// protected int ReadCallArguments(string expr, int start, string endLexem, List<Expression> args) {
|
||||
// var end = start;
|
||||
// do {
|
||||
// var lexem = ReadLexem(expr, end);
|
||||
// if (lexem.Type == LexemType.Delimiter) {
|
||||
// if (lexem.GetValue() == endLexem) {
|
||||
// return lexem.End;
|
||||
// } else if (lexem.GetValue() == ",") {
|
||||
// if (args.Count == 0) {
|
||||
// throw new LambdaParserException(expr, lexem.Start, "Expected method call parameter");
|
||||
// }
|
||||
// end = lexem.End;
|
||||
// }
|
||||
// }
|
||||
// // read parameter
|
||||
// var paramExpr = ParseConditional(expr, end);
|
||||
// args.Add(paramExpr.Expr);
|
||||
// end = paramExpr.End;
|
||||
// } while (true);
|
||||
// }
|
||||
//
|
||||
// protected ParseResult ParseValue(string expr, int start) {
|
||||
// var lexem = ReadLexem(expr, start);
|
||||
//
|
||||
// if (lexem.Type == LexemType.Delimiter && lexem.GetValue() == "(") {
|
||||
// var groupRes = ParseConditional(expr, lexem.End);
|
||||
// var endLexem = ReadLexem(expr, groupRes.End);
|
||||
// if (endLexem.Type != LexemType.Delimiter || endLexem.GetValue() != ")")
|
||||
// throw new LambdaParserException(expr, endLexem.Start, "Expected ')'");
|
||||
// groupRes.End = endLexem.End;
|
||||
// return groupRes;
|
||||
// } else if (lexem.Type == LexemType.NumberConstant) {
|
||||
// decimal numConst;
|
||||
// if (!Decimal.TryParse(lexem.GetValue(), NumberStyles.Any, CultureInfo.InvariantCulture, out numConst)) {
|
||||
// throw new Exception(String.Format("Invalid number: {0}", lexem.GetValue()));
|
||||
// }
|
||||
// return new ParseResult() {
|
||||
// End = lexem.End,
|
||||
// Expr = Expression.Constant(new LambdaParameterWrapper( numConst, Comparer) ) };
|
||||
// } else if (lexem.Type == LexemType.StringConstant) {
|
||||
// return new ParseResult() {
|
||||
// End = lexem.End,
|
||||
// Expr = Expression.Constant( new LambdaParameterWrapper( lexem.GetValue(), Comparer) ) };
|
||||
// } else if (lexem.Type == LexemType.Name) {
|
||||
// // check for predefined constants
|
||||
// var val = lexem.GetValue();
|
||||
// switch (val) {
|
||||
// case "true":
|
||||
// return new ParseResult() { End = lexem.End, Expr = Expression.Constant(new LambdaParameterWrapper(true, Comparer) ) };
|
||||
// case "false":
|
||||
// return new ParseResult() { End = lexem.End, Expr = Expression.Constant(new LambdaParameterWrapper(false, Comparer) ) };
|
||||
// case "null":
|
||||
// return new ParseResult() { End = lexem.End, Expr = Expression.Constant(new LambdaParameterWrapper(null, Comparer)) };
|
||||
// case "new":
|
||||
// return ReadNewInstance(expr, lexem.End);
|
||||
// }
|
||||
//
|
||||
// // todo
|
||||
//
|
||||
// return new ParseResult() { End = lexem.End, Expr = Expression.Parameter(typeof(LambdaParameterWrapper), val) };
|
||||
// }
|
||||
// throw new LambdaParserException(expr, start, "Expected value");
|
||||
// }
|
||||
//
|
||||
// protected ParseResult ReadNewInstance(string expr, int start) {
|
||||
// var nextLexem = ReadLexem(expr, start);
|
||||
// if (nextLexem.Type == LexemType.Delimiter && nextLexem.GetValue() == "[") {
|
||||
// nextLexem = ReadLexem(expr, nextLexem.End);
|
||||
// if (!(nextLexem.Type == LexemType.Delimiter && nextLexem.GetValue() == "]"))
|
||||
// throw new LambdaParserException(expr, nextLexem.Start, "Expected ']'");
|
||||
//
|
||||
// nextLexem = ReadLexem(expr, nextLexem.End);
|
||||
// if (!(nextLexem.Type == LexemType.Delimiter && nextLexem.GetValue() == "{"))
|
||||
// throw new LambdaParserException(expr, nextLexem.Start, "Expected '{'");
|
||||
//
|
||||
// var arrayArgs = new List<Expression>();
|
||||
// var end = ReadCallArguments(expr, nextLexem.End, "}", arrayArgs);
|
||||
// var newArrExpr = Expression.NewArrayInit(typeof(object), arrayArgs );
|
||||
// return new ParseResult() {
|
||||
// End = end,
|
||||
// Expr = Expression.New(LambdaParameterWrapperConstructor,
|
||||
// Expression.Convert(newArrExpr, typeof(object)),
|
||||
// Expression.Constant(Comparer))
|
||||
// };
|
||||
// }
|
||||
// if (nextLexem.Type == LexemType.Name && nextLexem.GetValue().ToLower() == "dictionary") {
|
||||
// nextLexem = ReadLexem(expr, nextLexem.End);
|
||||
// if (!(nextLexem.Type == LexemType.Delimiter && nextLexem.GetValue() == "{"))
|
||||
// throw new LambdaParserException(expr, nextLexem.Start, "Expected '{'");
|
||||
//
|
||||
// var dictionaryKeys = new List<Expression>();
|
||||
// var dictionaryValues = new List<Expression>();
|
||||
// do {
|
||||
// nextLexem = ReadLexem(expr, nextLexem.End);
|
||||
// if (!(nextLexem.Type == LexemType.Delimiter && nextLexem.GetValue() == "{"))
|
||||
// throw new LambdaParserException(expr, nextLexem.Start, "Expected '{'");
|
||||
// var entryArgs = new List<Expression>();
|
||||
// var end = ReadCallArguments(expr, nextLexem.End, "}", entryArgs);
|
||||
// if (entryArgs.Count!=2)
|
||||
// throw new LambdaParserException(expr, nextLexem.Start, "Dictionary entry should have exactly 2 arguments");
|
||||
//
|
||||
// dictionaryKeys.Add( entryArgs[0] );
|
||||
// dictionaryValues.Add( entryArgs[1] );
|
||||
//
|
||||
// nextLexem = ReadLexem(expr, end);
|
||||
// } while (nextLexem.Type == LexemType.Delimiter && nextLexem.GetValue() == ",");
|
||||
//
|
||||
// if (!(nextLexem.Type == LexemType.Delimiter && nextLexem.GetValue() == "}"))
|
||||
// throw new LambdaParserException(expr, nextLexem.Start, "Expected '}'");
|
||||
//
|
||||
// var newKeysArrExpr = Expression.NewArrayInit(typeof(object), dictionaryKeys );
|
||||
// var newValuesArrExpr = Expression.NewArrayInit(typeof(object), dictionaryValues );
|
||||
//
|
||||
// return new ParseResult() {
|
||||
// End = nextLexem.End,
|
||||
// Expr = Expression.Call(
|
||||
// Expression.Constant(new LambdaParameterWrapper(null, Comparer)),
|
||||
// CreateDictionaryMI,
|
||||
// newKeysArrExpr, newValuesArrExpr)
|
||||
// };
|
||||
// }
|
||||
// throw new LambdaParserException(expr, start, "Unknown new instance initializer");
|
||||
// }
|
||||
//
|
||||
// protected enum LexemType {
|
||||
// Unknown,
|
||||
// Name,
|
||||
// Delimiter,
|
||||
// StringConstant,
|
||||
// NumberConstant,
|
||||
// Stop
|
||||
// }
|
||||
//
|
||||
// protected struct Lexem {
|
||||
// public LexemType Type;
|
||||
// public int Start;
|
||||
// public int End;
|
||||
// public string Expr;
|
||||
//
|
||||
// string rawValue;
|
||||
//
|
||||
// public string GetValue() {
|
||||
// if (rawValue==null) {
|
||||
// rawValue = Expr.Substring(Start, End-Start).Trim();
|
||||
// if (Type==LexemType.StringConstant) {
|
||||
// rawValue = rawValue.Substring(1, rawValue.Length-2).Replace( "\"\"", "\"" );
|
||||
// }
|
||||
// }
|
||||
// return rawValue;
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// protected struct ParseResult {
|
||||
// public Expression Expr;
|
||||
// public int End;
|
||||
// }
|
||||
//
|
||||
// public class CompiledExpression {
|
||||
// public Delegate Lambda;
|
||||
// public ParameterExpression[] Parameters;
|
||||
// }
|
||||
//
|
||||
//
|
||||
// }
|
||||
// }
|
||||
29
GameDAL/ExpressionsParser/LambdaParserException.cs
Normal file
29
GameDAL/ExpressionsParser/LambdaParserException.cs
Normal file
@ -0,0 +1,29 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
|
||||
namespace ExpressionsParser {
|
||||
|
||||
/// <summary>
|
||||
/// The exception that is thrown when lambda expression parse error occurs
|
||||
/// </summary>
|
||||
public class LambdaParserException : Exception {
|
||||
|
||||
/// <summary>
|
||||
/// Lambda expression
|
||||
/// </summary>
|
||||
public string Expression { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// Parser position where syntax error occurs
|
||||
/// </summary>
|
||||
public int Index { get; private set; }
|
||||
|
||||
public LambdaParserException(string expr, int idx, string msg)
|
||||
: base( string.Format("{0} at {1}: {2}", msg, idx, expr) ) {
|
||||
Expression = expr;
|
||||
Index = idx;
|
||||
}
|
||||
}
|
||||
}
|
||||
144
GameDAL/ExpressionsParser/ValueComparer.cs
Normal file
144
GameDAL/ExpressionsParser/ValueComparer.cs
Normal file
@ -0,0 +1,144 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Reflection;
|
||||
|
||||
namespace ExpressionsParser {
|
||||
|
||||
/// <summary>
|
||||
/// Generic "by value" comparer that uses IComparable and can compare arrays/lists.
|
||||
/// </summary>
|
||||
public class ValueComparer : IComparer, IComparer<object>, IValueComparer {
|
||||
|
||||
internal readonly static ValueComparer _Instance = new ValueComparer();
|
||||
|
||||
public static IValueComparer Instance {
|
||||
get {
|
||||
return _Instance;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Gets or sets format provider used for Convert.ChangeType (InvariantCulture by default).
|
||||
/// </summary>
|
||||
public IFormatProvider FormatProvider { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Determines how ValueComparer handles comparison exceptions (by default is false: convert exceptions are thrown).
|
||||
/// </summary>
|
||||
public bool SuppressErrors { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Determines how ValueComparer handles comparison with nulls (default is "MinValue" mode).
|
||||
/// </summary>
|
||||
public NullComparisonMode NullComparison { get; set; }
|
||||
|
||||
public ValueComparer() {
|
||||
FormatProvider = System.Globalization.CultureInfo.InvariantCulture;
|
||||
SuppressErrors = false;
|
||||
}
|
||||
|
||||
private bool IsAssignableFrom(Type a, Type b) {
|
||||
#if NET40
|
||||
return a.IsAssignableFrom(b);
|
||||
#else
|
||||
return a.GetTypeInfo().IsAssignableFrom(b.GetTypeInfo() );
|
||||
#endif
|
||||
}
|
||||
|
||||
int IComparer.Compare(object a, object b) {
|
||||
var res = CompareInternal(a, b);
|
||||
if (!res.HasValue)
|
||||
throw new ArgumentException(string.Format("Cannot compare {0} and {1}", a.GetType(), b.GetType()));
|
||||
return res.Value;
|
||||
}
|
||||
|
||||
int IComparer<object>.Compare(object a, object b) {
|
||||
return ((IComparer)this).Compare(a, b);
|
||||
}
|
||||
|
||||
public int? Compare(object a, object b) {
|
||||
try {
|
||||
if (NullComparison == NullComparisonMode.Sql)
|
||||
if (a == null || b == null)
|
||||
return null;
|
||||
return CompareInternal(a, b);
|
||||
} catch {
|
||||
if (SuppressErrors)
|
||||
return null;
|
||||
throw;
|
||||
}
|
||||
}
|
||||
|
||||
protected virtual int? CompareInternal(object a, object b) {
|
||||
if (a == null && b == null)
|
||||
return 0;
|
||||
if (a == null && b != null)
|
||||
return -1;
|
||||
if (a != null && b == null)
|
||||
return 1;
|
||||
|
||||
if ((a is IList) && (b is IList)) {
|
||||
IList aList = (IList)a;
|
||||
IList bList = (IList)b;
|
||||
if (aList.Count < bList.Count)
|
||||
return -1;
|
||||
if (aList.Count > bList.Count)
|
||||
return +1;
|
||||
for (int i = 0; i < aList.Count; i++) {
|
||||
int? r = Compare(aList[i], bList[i]);
|
||||
if (!r.HasValue || r != 0)
|
||||
return r;
|
||||
}
|
||||
// lists are equal
|
||||
return 0;
|
||||
}
|
||||
// test for quick compare if a type is assignable from b
|
||||
if (a is IComparable) {
|
||||
var aComp = (IComparable)a;
|
||||
// quick compare if types are fully compatible
|
||||
if (IsAssignableFrom( a.GetType(), b.GetType() ))
|
||||
return aComp.CompareTo(b);
|
||||
}
|
||||
if (b is IComparable) {
|
||||
var bComp = (IComparable)b;
|
||||
// quick compare if types are fully compatible
|
||||
if (IsAssignableFrom( b.GetType(), a.GetType() ))
|
||||
return -bComp.CompareTo(a);
|
||||
}
|
||||
|
||||
// try to convert b to a and then compare
|
||||
if (a is IComparable) {
|
||||
var aComp = (IComparable)a;
|
||||
var bConverted = Convert.ChangeType(b, a.GetType(), FormatProvider);
|
||||
return aComp.CompareTo(bConverted);
|
||||
}
|
||||
// try to convert a to b and then compare
|
||||
if (b is IComparable) {
|
||||
var bComp = (IComparable)b;
|
||||
var aConverted = Convert.ChangeType(a, b.GetType(), FormatProvider);
|
||||
return -bComp.CompareTo(aConverted);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public enum NullComparisonMode {
|
||||
|
||||
/// <summary>
|
||||
/// Null compared as "MinValue" (affects less-than and greater-than comparisons).
|
||||
/// </summary>
|
||||
/// <remarks>This is default behaviour expected for <see cref="IComparer"/> and described in MSDN.</remarks>
|
||||
MinValue = 0,
|
||||
|
||||
/// <summary>
|
||||
/// Null cannot be compared to any other value (even if it is null). This is SQL-like nulls handling.
|
||||
/// </summary>
|
||||
Sql = 1,
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
186
GameDAL/FriendRoom/FightDataManager.cs
Normal file
186
GameDAL/FriendRoom/FightDataManager.cs
Normal file
@ -0,0 +1,186 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.IO;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using MrWu.Debug;
|
||||
using Server.Core;
|
||||
using Server.DB.Redis;
|
||||
|
||||
namespace GameDAL.FriendRoom
|
||||
{
|
||||
public class FightDataManager : SingleInstance<FightDataManager>
|
||||
{
|
||||
private Thread thead;
|
||||
|
||||
private bool IsDispose = false;
|
||||
|
||||
private const string dirPath = "fightData";
|
||||
|
||||
private ConcurrentQueue<FightDataCommand> CommandQueue = new ConcurrentQueue<FightDataCommand>();
|
||||
|
||||
public FightDataManager()
|
||||
{
|
||||
if (!Directory.Exists(dirPath))
|
||||
{
|
||||
Directory.CreateDirectory(dirPath);
|
||||
}
|
||||
|
||||
thead = new Thread(Run);
|
||||
thead.Start();
|
||||
}
|
||||
|
||||
private string OldFileName(string weiyima)
|
||||
{
|
||||
return $"{dirPath}/{weiyima}";
|
||||
}
|
||||
|
||||
private string NewFileName(string weiyima)
|
||||
{
|
||||
return $"{dirPath}/{weiyima}.bytes";
|
||||
}
|
||||
|
||||
private string TempFileName(string weiyima)
|
||||
{
|
||||
return $"{dirPath}/{weiyima}.temp";
|
||||
}
|
||||
|
||||
public byte[] LoadFightData(string weiyima,out bool isOld)
|
||||
{
|
||||
byte[] result = null;
|
||||
try
|
||||
{
|
||||
isOld = false;
|
||||
string fileName = NewFileName(weiyima);
|
||||
if (File.Exists(fileName))
|
||||
{
|
||||
result = File.ReadAllBytes(fileName);
|
||||
Debug.Info("加载战斗数据!" + weiyima);
|
||||
}else
|
||||
{
|
||||
//旧文件
|
||||
fileName = OldFileName(weiyima);
|
||||
if (File.Exists(fileName))
|
||||
{
|
||||
string jsonData = File.ReadAllText(fileName);
|
||||
isOld = true;
|
||||
return Encoding.UTF8.GetBytes(jsonData);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error($"读取战绩还能报错?? {e.Message}");
|
||||
throw;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
public void SaveFightData(string weiyima,byte[] data)
|
||||
{
|
||||
CommandQueue.Enqueue(FightDataCommand.Create(Command.Save, weiyima, data));
|
||||
}
|
||||
|
||||
public void DelFightData(string weiyima)
|
||||
{
|
||||
CommandQueue.Enqueue(FightDataCommand.Create(Command.Del, weiyima));
|
||||
}
|
||||
|
||||
private void Run()
|
||||
{
|
||||
#if DEBUG
|
||||
uint threadId = ThreadHelper.GetOSThreadId();
|
||||
Debug.Info($"ThreadStart FightDataManager {threadId}");
|
||||
#endif
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (CommandQueue.TryDequeue(out FightDataCommand command))
|
||||
{
|
||||
try
|
||||
{
|
||||
string fileName = NewFileName(command.WeiYiMa);
|
||||
string tempFileName = TempFileName(command.WeiYiMa);
|
||||
|
||||
switch (command.Command)
|
||||
{
|
||||
case Command.Save:
|
||||
//保证文件的原子性,存到临时文件,再移动到正式文件
|
||||
File.WriteAllBytes(tempFileName,command.Data);
|
||||
if (File.Exists(fileName))
|
||||
{
|
||||
File.Delete(fileName);
|
||||
}
|
||||
File.Move(tempFileName,fileName);
|
||||
break;
|
||||
case Command.Del:
|
||||
File.Delete(fileName);
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error($"执行战斗数据指令报错:{command.Command} {command.WeiYiMa} {e.Message}");
|
||||
}
|
||||
|
||||
ReferencePool.Recycle(command);
|
||||
}
|
||||
else
|
||||
{
|
||||
//如果关闭了,就退出
|
||||
if (IsDispose)
|
||||
{
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
IsDispose = true;
|
||||
thead.Join();
|
||||
}
|
||||
|
||||
public class FightDataCommand : Reference
|
||||
{
|
||||
public string WeiYiMa;
|
||||
public byte[] Data;
|
||||
public Command Command;
|
||||
|
||||
|
||||
|
||||
public static FightDataCommand Create(Command command,string weiyima,byte[] data= null)
|
||||
{
|
||||
FightDataCommand fightDataCommand = ReferencePool.Fetch<FightDataCommand>();
|
||||
fightDataCommand.WeiYiMa = weiyima;
|
||||
fightDataCommand.Data = data;
|
||||
fightDataCommand.Command = command;
|
||||
return fightDataCommand;
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
WeiYiMa = null;
|
||||
Data = null;
|
||||
ReferencePool.Recycle(this);
|
||||
}
|
||||
}
|
||||
|
||||
public enum Command
|
||||
{
|
||||
/// <summary>
|
||||
/// 保存
|
||||
/// </summary>
|
||||
Save,
|
||||
/// <summary>
|
||||
/// 加载
|
||||
/// </summary>
|
||||
Del,
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
352
GameDAL/FriendRoom/FightRecordManager.cs
Normal file
352
GameDAL/FriendRoom/FightRecordManager.cs
Normal file
@ -0,0 +1,352 @@
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Runtime.InteropServices.ComTypes;
|
||||
using System.Threading;
|
||||
using Cloud.Alibaba.Oss;
|
||||
using GameData;
|
||||
using MrWu.Debug;
|
||||
using ObjectModel.Game;
|
||||
using Server.Core;
|
||||
|
||||
namespace Server
|
||||
{
|
||||
public class FightRecordManager : SingleInstance<FightRecordManager>
|
||||
{
|
||||
private Thread thread;
|
||||
|
||||
private bool IsDispose = false;
|
||||
|
||||
private const string dirPath = "RoomFightPath";
|
||||
|
||||
private ConcurrentQueue<FightRecordCommand> CommandQueue = new ConcurrentQueue<FightRecordCommand>();
|
||||
|
||||
private UpLoadTask Current;
|
||||
|
||||
/// <summary>
|
||||
/// 等待处理的文件
|
||||
/// </summary>
|
||||
private HashSet<string> waitDeal = new HashSet<string>();
|
||||
|
||||
private ConcurrentQueue<UpLoadTask> _upLoadTasks = new ConcurrentQueue<UpLoadTask>();
|
||||
|
||||
private long nextUploadOss;
|
||||
|
||||
/// <summary>
|
||||
/// 10 秒钟检查一次上传
|
||||
/// </summary>
|
||||
private const long checkInterval = 10 * 1000;
|
||||
|
||||
private int GameId;
|
||||
|
||||
/// <summary>
|
||||
/// 最大只允许上传10M文件
|
||||
/// </summary>
|
||||
private const int MaxFileSize = 1024 * 1024 * 10;
|
||||
|
||||
/// <summary>
|
||||
/// 当前的存储的回放版本数据
|
||||
/// </summary>
|
||||
private const int FightRecordVer = 2;
|
||||
|
||||
public void Init(int gameId)
|
||||
{
|
||||
this.GameId = gameId;
|
||||
}
|
||||
|
||||
public FightRecordManager()
|
||||
{
|
||||
if (!Directory.Exists(dirPath))
|
||||
{
|
||||
Directory.CreateDirectory(dirPath);
|
||||
}
|
||||
|
||||
thread = new Thread(Run);
|
||||
thread.Start();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存房间信息
|
||||
/// </summary>
|
||||
/// <param name="weiyima"></param>
|
||||
/// <param name="info"></param>
|
||||
public void SaveRoomInfo(string weiyima, FriendRoomFightFileInfo info)
|
||||
{
|
||||
CommandQueue.Enqueue(FightRecordCommand.Create(Command.SaveRoomInfo, weiyima, info));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存战绩回放信息
|
||||
/// </summary>
|
||||
public void SaveFightInfo(string weiyima, RoomFightData info, int index)
|
||||
{
|
||||
CommandQueue.Enqueue(FightRecordCommand.Create(Command.SaveFightInfo, weiyima, info, index));
|
||||
}
|
||||
|
||||
private void Run()
|
||||
{
|
||||
#if DEBUG
|
||||
uint threadId = ThreadHelper.GetOSThreadId();
|
||||
Debug.Info($"ThreadStart FightRecordManager {threadId}");
|
||||
#endif
|
||||
|
||||
while (true)
|
||||
{
|
||||
if (CommandQueue.TryDequeue(out FightRecordCommand command))
|
||||
{
|
||||
try
|
||||
{
|
||||
switch (command.Command)
|
||||
{
|
||||
case Command.SaveFightInfo:
|
||||
{
|
||||
string fileName = $"{dirPath}/{GetOssPath.GetFileName(command.WeiYiMa, command.Index)}";
|
||||
string content = JsonPack.GetJson(command.Data);
|
||||
File.WriteAllText(fileName, content);
|
||||
}
|
||||
break;
|
||||
case Command.SaveRoomInfo:
|
||||
{
|
||||
string fileName = $"{dirPath}/FriendRoomFightFileInfo_{command.WeiYiMa}.txt";
|
||||
string content = JsonPack.GetJson(command.Data);
|
||||
File.WriteAllText(fileName, content);
|
||||
|
||||
nextUploadOss = TimeInfo.Instance.FrameTime; //下一帧开始上传,保证SaveFightInfo全部先保存
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error($"执行保存回放数据指令报错:{command.Command} {command.WeiYiMa} {e.Message}");
|
||||
}
|
||||
|
||||
ReferencePool.Recycle(command);
|
||||
}
|
||||
else if (IsDispose)
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
if (TimeInfo.Instance.FrameTime > nextUploadOss)
|
||||
{
|
||||
try
|
||||
{
|
||||
//检查上传Oss
|
||||
string[] files = Directory.GetFiles(dirPath, "FriendRoomFightFileInfo_*.txt");
|
||||
for (int i = 0; i < files.Length; i++)
|
||||
{
|
||||
if (waitDeal.Contains(files[i]))
|
||||
continue;
|
||||
|
||||
UpLoadTask loadTask = UpLoadTask.Create(files[i]);
|
||||
if (loadTask == null)
|
||||
{
|
||||
Debug.Error($"这个文件有问题:{files[i]}");
|
||||
File.Delete(files[i]);
|
||||
}
|
||||
else
|
||||
{
|
||||
waitDeal.Add(files[i]);
|
||||
_upLoadTasks.Enqueue(loadTask);
|
||||
Debug.Info("添加到上传任务!");
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error($"处理出错:{e.Message}");
|
||||
}
|
||||
|
||||
nextUploadOss = TimeInfo.Instance.FrameTime + checkInterval;
|
||||
}
|
||||
|
||||
while (Current == null && _upLoadTasks.TryDequeue(out UpLoadTask loadTask))
|
||||
{
|
||||
Current = loadTask;
|
||||
}
|
||||
|
||||
if (Current != null && TimeInfo.Instance.FrameTime > Current.NextTryTime)
|
||||
{
|
||||
try
|
||||
{
|
||||
//执行文件上传
|
||||
string filePath =
|
||||
$"{dirPath}/{GetOssPath.GetFileName(Current.RoomInfo.weiyima, Current.Current)}";
|
||||
|
||||
if (!File.Exists(filePath))
|
||||
{
|
||||
Debug.Error($"未找打要上传的文件:{filePath}");
|
||||
Current.Current++;
|
||||
}
|
||||
else
|
||||
{
|
||||
// if (!ServerConst.IsTest)
|
||||
// {
|
||||
Debug.Info("开始上传!");
|
||||
var ossPath = GetOssPath.GetKey(Path.GetFileName(filePath), GameId,
|
||||
Current.RoomInfo.endTime);
|
||||
FileInfo fileInfo = new FileInfo(filePath);
|
||||
bool isUpLoad = false;
|
||||
if (fileInfo.Length > MaxFileSize)
|
||||
{
|
||||
isUpLoad = true;
|
||||
Debug.Fatal($"上传的文件超10M 不合理:{fileInfo.FullName}");
|
||||
}
|
||||
|
||||
var b = isUpLoad || OSSHelper.PutObject(Bucket.B8880666s,ossPath, File.ReadAllText(filePath));
|
||||
if (!b)
|
||||
{
|
||||
Debug.Error($"上传文件到OSS失败:{filePath},等待重试!");
|
||||
Current.TryCnt++;
|
||||
Current.NextTryTime = TimeInfo.Instance.FrameTime + Current.TryCnt * 1000;
|
||||
}
|
||||
else
|
||||
{
|
||||
Debug.Info($"上传成功:{filePath}");
|
||||
Current.Current++;
|
||||
}
|
||||
// }
|
||||
// else
|
||||
// {
|
||||
// Current.Current++;
|
||||
// }
|
||||
}
|
||||
|
||||
if (Current.Current > Current.AllCount)
|
||||
{
|
||||
//全部上传完毕,删除文件
|
||||
for (int i = 1; i <= Current.AllCount; i++)
|
||||
{
|
||||
string delPath = $"{dirPath}/{GetOssPath.GetFileName(Current.RoomInfo.weiyima, i)}";
|
||||
File.Delete(delPath);
|
||||
Debug.Info($"删除文件:{delPath}");
|
||||
}
|
||||
|
||||
File.Delete(Current.filaName);
|
||||
waitDeal.Remove(Current.filaName);
|
||||
Current.Dispose();
|
||||
Current = null;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error($"执行上传任务报错:{e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}
|
||||
|
||||
public void Dispose()
|
||||
{
|
||||
IsDispose = true;
|
||||
thread.Join();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 上传任务
|
||||
/// </summary>
|
||||
public class UpLoadTask : Reference
|
||||
{
|
||||
public string filaName;
|
||||
public FriendRoomFightFileInfo RoomInfo;
|
||||
|
||||
/// <summary>
|
||||
/// 当前在处理那一个
|
||||
/// </summary>
|
||||
public int Current;
|
||||
|
||||
/// <summary>
|
||||
/// 总共几个
|
||||
/// </summary>
|
||||
public int AllCount;
|
||||
|
||||
/// <summary>
|
||||
/// 下次尝试时间
|
||||
/// </summary>
|
||||
public long NextTryTime;
|
||||
|
||||
/// <summary>
|
||||
/// 尝试次数 最多重试10次
|
||||
/// </summary>
|
||||
public long TryCnt;
|
||||
|
||||
public static UpLoadTask Create(string fileName)
|
||||
{
|
||||
if (!File.Exists(fileName))
|
||||
{
|
||||
Debug.Error($"没找到要上传的战斗文件信息:{fileName}");
|
||||
return null;
|
||||
}
|
||||
|
||||
string jsonData = File.ReadAllText(fileName);
|
||||
if (string.IsNullOrEmpty(jsonData))
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
UpLoadTask task = ReferencePool.Fetch<UpLoadTask>();
|
||||
task.RoomInfo = JsonPack.GetData<FriendRoomFightFileInfo>(jsonData);
|
||||
if (task.RoomInfo == null || task.RoomInfo.overCnt <= 0)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
task.filaName = fileName;
|
||||
task.NextTryTime = 0;
|
||||
task.TryCnt = 0;
|
||||
task.Current = 1;
|
||||
task.AllCount = task.RoomInfo.overCnt;
|
||||
return task;
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
RoomInfo = null;
|
||||
filaName = null;
|
||||
ReferencePool.Recycle(this);
|
||||
}
|
||||
}
|
||||
|
||||
public class FightRecordCommand : Reference
|
||||
{
|
||||
public string WeiYiMa;
|
||||
public int Index;
|
||||
public object Data;
|
||||
public Command Command;
|
||||
|
||||
public static FightRecordCommand Create(Command command, string weiyima, object data, int index = 0)
|
||||
{
|
||||
FightRecordCommand fightRecordCommand = ReferencePool.Fetch<FightRecordCommand>();
|
||||
fightRecordCommand.WeiYiMa = weiyima;
|
||||
fightRecordCommand.Data = data;
|
||||
fightRecordCommand.Command = command;
|
||||
fightRecordCommand.Index = index;
|
||||
return fightRecordCommand;
|
||||
}
|
||||
|
||||
public override void Dispose()
|
||||
{
|
||||
WeiYiMa = null;
|
||||
Data = null;
|
||||
ReferencePool.Recycle(this);
|
||||
}
|
||||
}
|
||||
|
||||
public enum Command
|
||||
{
|
||||
/// <summary>
|
||||
/// 保存房间信息
|
||||
/// </summary>
|
||||
SaveRoomInfo,
|
||||
|
||||
/// <summary>
|
||||
/// 保存战绩信息
|
||||
/// </summary>
|
||||
SaveFightInfo,
|
||||
}
|
||||
}
|
||||
}
|
||||
1199
GameDAL/FriendRoom/Room.cs
Normal file
1199
GameDAL/FriendRoom/Room.cs
Normal file
@ -0,0 +1,1199 @@
|
||||
/*
|
||||
* 作者:吴隆健
|
||||
* 日期: 2019-04-22
|
||||
* 时间: 13:20
|
||||
*
|
||||
*/
|
||||
|
||||
using System;
|
||||
using Server.DB.Redis;
|
||||
using StackExchange.Redis;
|
||||
using MrWu.Debug;
|
||||
using GameData;
|
||||
using Server.Data;
|
||||
using System.Data;
|
||||
using Server.DB.Sql;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Data.SqlClient;
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
using GameMessage;
|
||||
using Newtonsoft.Json;
|
||||
using Server;
|
||||
|
||||
namespace GameDAL.FriendRoom
|
||||
{
|
||||
/// <summary>
|
||||
/// 房间管理
|
||||
/// </summary>
|
||||
public static class Room
|
||||
{
|
||||
/// <summary>
|
||||
/// 战斗数据保存的文件夹 --服务器目录
|
||||
/// </summary>
|
||||
public const string RoomFightPath = "RoomFightPath";
|
||||
|
||||
/// <summary>
|
||||
/// 密码
|
||||
/// </summary>
|
||||
public const string pwdField = "pwd";
|
||||
|
||||
/// <summary>
|
||||
/// 最大玩家数量
|
||||
/// </summary>
|
||||
public const string maxCntField = "maxCnt";
|
||||
|
||||
/// <summary>
|
||||
/// 最小玩家数量
|
||||
/// </summary>
|
||||
public const string minCntField = "minCnt";
|
||||
|
||||
/// <summary>
|
||||
/// 朋友房多少局
|
||||
/// </summary>
|
||||
public const string warCntField = "warCnt";
|
||||
|
||||
/// <summary>
|
||||
/// 当前开战的是第几场
|
||||
/// </summary>
|
||||
public const string nowCntField = "nowCnt";
|
||||
|
||||
/// <summary>
|
||||
/// 结束的局数
|
||||
/// </summary>
|
||||
public const string overCntField = "overCnt";
|
||||
|
||||
/// <summary>
|
||||
/// 房间所属游戏
|
||||
/// </summary>
|
||||
public const string gameidField = "gameid";
|
||||
|
||||
/// <summary>
|
||||
/// 服务器版本
|
||||
/// </summary>
|
||||
public const string serverVerField = "serVer";
|
||||
|
||||
/// <summary>
|
||||
/// 0普通开 1代开房间 5竞技比赛创建房间
|
||||
/// </summary>
|
||||
public const string CreateStyleField = "createStyle";
|
||||
|
||||
/// <summary>
|
||||
/// 创建房间id 如果是普通创建房间 则此id为玩家userid 竞技比赛创建则为竞技比赛id
|
||||
/// </summary>
|
||||
public const string CreateIdField = "CreateId";
|
||||
|
||||
/// <summary>
|
||||
/// 创建房间的房卡数量
|
||||
/// </summary>
|
||||
public const string fangkaField = "Fangka";
|
||||
|
||||
/// <summary>
|
||||
/// 座位标记
|
||||
/// </summary>
|
||||
public const string seatTagField = "seatTag";
|
||||
|
||||
/// <summary>
|
||||
/// 房间规则
|
||||
/// </summary>
|
||||
public const string roomRuleField = "RoomRule";
|
||||
|
||||
/// <summary>
|
||||
/// 创建时间
|
||||
/// </summary>
|
||||
public const string CreateTimeField = "CreateTime";
|
||||
|
||||
/// <summary>
|
||||
/// userid
|
||||
/// </summary>
|
||||
public const string useridField = "Userid";
|
||||
|
||||
/// <summary>
|
||||
/// 昵称
|
||||
/// </summary>
|
||||
public const string nickNameField = "nickName";
|
||||
|
||||
/// <summary>
|
||||
/// 性别
|
||||
/// </summary>
|
||||
public const string sexField = "sex";
|
||||
|
||||
/// <summary>
|
||||
/// 头像
|
||||
/// </summary>
|
||||
public const string photoField = "photo";
|
||||
|
||||
/// <summary>
|
||||
/// 房主
|
||||
/// </summary>
|
||||
public const string fangzhuField = "fangzhu";
|
||||
|
||||
/// <summary>
|
||||
/// 战斗id
|
||||
/// </summary>
|
||||
public const string fightField = "fightid";
|
||||
|
||||
/// <summary>
|
||||
/// 玩家的分值
|
||||
/// </summary>
|
||||
public const string scorejsonField = "playerScore";
|
||||
|
||||
/// <summary>
|
||||
/// 战斗座位
|
||||
/// </summary>
|
||||
public const string fightseatField = "seat";
|
||||
|
||||
/// <summary>
|
||||
/// 是否拦截ip
|
||||
/// </summary>
|
||||
public const string interceptIpField = "interceptIp";
|
||||
|
||||
/// <summary>
|
||||
/// 是否拦截不是微信的账号
|
||||
/// </summary>
|
||||
public const string interceptWeChatField = "interceptWeChat";
|
||||
|
||||
/// <summary>
|
||||
/// 是否关闭
|
||||
/// </summary>
|
||||
public const string isCloseField = "closeField";
|
||||
|
||||
/// <summary>
|
||||
/// 关闭时间
|
||||
/// </summary>
|
||||
public const string closeTimeField = "closeTime";
|
||||
|
||||
/// <summary>
|
||||
/// 房间号
|
||||
/// </summary>
|
||||
public const string roomNumField = "roomNum";
|
||||
|
||||
/// <summary>
|
||||
/// 战斗超时时间
|
||||
/// </summary>
|
||||
public const string wartimeOutField = "warTimeOut";
|
||||
|
||||
/// <summary>
|
||||
/// 加入超时时间
|
||||
/// </summary>
|
||||
public const string jointimeOutField = "jointimeOut";
|
||||
|
||||
/// <summary>
|
||||
/// 玩法的id
|
||||
/// </summary>
|
||||
public const string wayidField = "wayid";
|
||||
|
||||
/// <summary>
|
||||
/// 拓展字段
|
||||
/// </summary>
|
||||
public const string exField = "ex";
|
||||
|
||||
/// <summary>
|
||||
/// 拓展字段
|
||||
/// </summary>
|
||||
public const string ruleexField = "ruleEx";
|
||||
|
||||
/// <summary>
|
||||
/// 房间的最大数量
|
||||
/// </summary>
|
||||
public const int MaxCnt = 1000000;
|
||||
|
||||
/// <summary>
|
||||
/// 是否保存战斗数据到数据库
|
||||
/// </summary>
|
||||
//public static bool IsSaveFightToDB = false;
|
||||
|
||||
/// <summary>
|
||||
/// 房间分布式锁
|
||||
/// </summary>
|
||||
public static DistributedLock roomlock = new DistributedLock(100);
|
||||
|
||||
/// <summary>
|
||||
/// 获的一个房间号
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static int GetRoomNum()
|
||||
{
|
||||
DateTime lastCreateTime = DateTime.Now;
|
||||
string lastCreateNum = "000000";
|
||||
|
||||
try
|
||||
{
|
||||
var hes = redisManager.db.HashGetAll(RedisDictionary.lastRoomNum);
|
||||
|
||||
if (hes != null && hes.Length > 0)
|
||||
{
|
||||
foreach (var he in hes)
|
||||
{
|
||||
switch (he.Name)
|
||||
{
|
||||
case RedisDictionary.lastCreatRoomTime: //上次创建的时间
|
||||
lastCreateTime = DateTime.Parse(he.Value);
|
||||
break;
|
||||
case RedisDictionary.lastRoomNum:
|
||||
lastCreateNum = he.Value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error("7B69BB45-9B1A-49DF-BC81-3370D8CEDE59:" + e.ToString());
|
||||
}
|
||||
|
||||
int lastCreateNum_ = int.Parse(lastCreateNum);
|
||||
|
||||
//时间差值,秒钟
|
||||
int betweenTime = (int)(DateTime.Now - lastCreateTime).TotalSeconds;
|
||||
|
||||
//房间增量
|
||||
int deltanum = betweenTime / 10 % 1000;
|
||||
|
||||
int roomNum_ = (lastCreateNum_ + deltanum) % MaxCnt;
|
||||
|
||||
while (roomNum_ == lastCreateNum_ || roomNum_ == 0)
|
||||
{
|
||||
roomNum_++;
|
||||
roomNum_ = roomNum_ % MaxCnt;
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
HashEntry[] hhe = new HashEntry[2];
|
||||
hhe[0] = new HashEntry(RedisDictionary.lastCreatRoomTime, DateTime.Now.ToString());
|
||||
hhe[1] = new HashEntry(RedisDictionary.lastRoomNum, roomNum_);
|
||||
redisManager.db.HashSetAsync(RedisDictionary.lastRoomNum, hhe, CommandFlags.FireAndForget);
|
||||
}
|
||||
finally
|
||||
{
|
||||
}
|
||||
|
||||
return roomNum_;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取朋友房数据的key
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static string GetWeiYiMaKey(string weiyima)
|
||||
{
|
||||
return RedisDictionary.friendRoomField + weiyima;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取朋友房中玩家数据key
|
||||
/// </summary>
|
||||
/// <param name="weiyima"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetPlayerKey(string weiyima, int index)
|
||||
{
|
||||
return RedisDictionary.friendRoomField + weiyima + ":" + index;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 存储玩家所在的房间号以及唯一码
|
||||
/// </summary>
|
||||
/// <param name="userid"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetPlayerNumKey(int userid)
|
||||
{
|
||||
return "Game:FriendRoom:Player:" + userid;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取每局详情key
|
||||
/// </summary>
|
||||
/// <param name="weiyima"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <returns></returns>
|
||||
public static string GetBureauKey(string weiyima, int index)
|
||||
{
|
||||
return RedisDictionary.friendRoomField + weiyima + "." + index;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置当前开战次数
|
||||
/// </summary>
|
||||
/// <param name="deskinfo"></param>
|
||||
public static void SetNowCnt(DeskInfo deskinfo)
|
||||
{
|
||||
string key = GetWeiYiMaKey(deskinfo.weiyima);
|
||||
redisManager.db.HashSet(key, nowCntField, deskinfo.nowCnt);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置结束次数
|
||||
/// </summary>
|
||||
/// <param name="deskinfo"></param>
|
||||
public static void SetOverCnt(DeskInfo deskinfo)
|
||||
{
|
||||
string key = GetWeiYiMaKey(deskinfo.weiyima);
|
||||
redisManager.db.HashSet(key, overCntField, deskinfo.overCnt);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加载房间号
|
||||
/// </summary>
|
||||
/// <param name="roomnum">房间号</param>
|
||||
/// <param name="weiyima">唯一码</param>
|
||||
/// <returns></returns>
|
||||
public static bool LoadPlayerNum(int userid, ref string roomnum, ref string weiyima)
|
||||
{
|
||||
string plNumKey = GetPlayerNumKey(userid);
|
||||
var hes = redisManager.db.HashGetAll(plNumKey);
|
||||
|
||||
if (hes == null || hes.Length == 0)
|
||||
return false;
|
||||
|
||||
int len = hes.Length;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
switch (hes[i].Name)
|
||||
{
|
||||
case "num":
|
||||
roomnum = hes[i].Value;
|
||||
break;
|
||||
case "weiyima":
|
||||
weiyima = hes[i].Value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 清楚玩家所在的房间号
|
||||
/// </summary>
|
||||
public static void ClearPlayerNum(int userid)
|
||||
{
|
||||
string plNumkey = GetPlayerNumKey(userid);
|
||||
redisManager.db.KeyDelete(plNumkey);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取房间的唯一码
|
||||
/// </summary>
|
||||
/// <param name="roomnum"></param>
|
||||
/// <returns></returns>
|
||||
public static bool GetWeiyima(int roomnum, ref string weiyima, ref ServerNode node)
|
||||
{
|
||||
string key = Roomkey(roomnum.ToString());
|
||||
|
||||
var hes = redisManager.db.HashGetAll(key);
|
||||
if (hes == null || hes.Length == 0)
|
||||
return false;
|
||||
|
||||
int len = hes.Length;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
switch (hes[i].Name)
|
||||
{
|
||||
case "weiyima":
|
||||
weiyima = hes[i].Value;
|
||||
break;
|
||||
case "server":
|
||||
node = JsonPack.GetData<ServerNode>(hes[i].Value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存玩家数据到redis中
|
||||
/// </summary>
|
||||
/// <param name="dskinfo"></param>
|
||||
/// <param name="index"></param>
|
||||
public static bool SavePlayerToRedis(DeskInfo dskinfo, int index)
|
||||
{
|
||||
DeskInfo.PlayerData pl = dskinfo.pls[index];
|
||||
if (pl == null)
|
||||
{
|
||||
Debug.Error("程序错误....playerdata is null index:{0}", index);
|
||||
return false;
|
||||
}
|
||||
|
||||
string plNumKey = GetPlayerNumKey(pl.userid);
|
||||
string key = GetPlayerKey(dskinfo.weiyima, index);
|
||||
|
||||
IDatabase db = redisManager.GetDataBase();
|
||||
|
||||
var tran = db.CreateTransaction();
|
||||
|
||||
tran.AddCondition(Condition.KeyNotExists(plNumKey));
|
||||
tran.AddCondition(Condition.KeyNotExists(key));
|
||||
|
||||
var numhes = new HashEntry[2];
|
||||
numhes[0] = new HashEntry("num", dskinfo.roomNum); //房间号
|
||||
numhes[1] = new HashEntry("weiyima", dskinfo.weiyima); //唯一码
|
||||
tran.HashSetAsync(plNumKey, numhes); //保存玩家的房间号以及唯一码
|
||||
|
||||
HashEntry[] hes = new HashEntry[6];
|
||||
hes[0] = new HashEntry(useridField, pl.userid);
|
||||
hes[1] = new HashEntry(fangzhuField, pl.fangzhu);
|
||||
if (pl.nickName == null)
|
||||
pl.nickName = string.Empty;
|
||||
hes[2] = new HashEntry(nickNameField, pl.nickName);
|
||||
if (pl.photo == null)
|
||||
pl.photo = string.Empty;
|
||||
hes[3] = new HashEntry(photoField, pl.photo);
|
||||
hes[4] = new HashEntry(sexField, pl.sex);
|
||||
hes[5] = new HashEntry("clubid", pl.ClubId);
|
||||
tran.HashSetAsync(key, hes); //保存玩家数据
|
||||
|
||||
|
||||
key = GetWeiYiMaKey(dskinfo.weiyima);
|
||||
Debug.Info("key1:" + key + "," + plNumKey);
|
||||
tran.AddCondition(Condition.KeyExists(key));
|
||||
tran.HashSetAsync(key, seatTagField, JsonPack.GetJson(dskinfo.seat)); //保存房间数据中的座位信息
|
||||
|
||||
Debug.Log("key2:" + key);
|
||||
|
||||
return tran.Execute();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从redis中清楚玩家数据
|
||||
/// </summary>
|
||||
/// <param name="dskinfo"></param>
|
||||
/// <param name="index"></param>
|
||||
public static bool ClearPlayerToRedis(DeskInfo dskinfo, int index, int userid)
|
||||
{
|
||||
string key = GetPlayerKey(dskinfo.weiyima, index);
|
||||
|
||||
var db = redisManager.GetDataBase();
|
||||
|
||||
var tran = db.CreateTransaction();
|
||||
|
||||
tran.KeyDeleteAsync(key); //清空玩家数据
|
||||
|
||||
key = GetPlayerNumKey(userid);
|
||||
tran.KeyDeleteAsync(key);
|
||||
|
||||
key = GetWeiYiMaKey(dskinfo.weiyima);
|
||||
tran.AddCondition(Condition.KeyExists(key));
|
||||
tran.HashSetAsync(key, seatTagField, JsonPack.GetJson(dskinfo.seat));
|
||||
|
||||
return tran.Execute();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存单局详情_修改及保存
|
||||
/// </summary>
|
||||
/// <param name="deskinfo">桌子信息</param>
|
||||
/// <param name="index"></param>
|
||||
public static void SaveBureau(DeskInfo deskinfo, int index)
|
||||
{
|
||||
string key = GetBureauKey(deskinfo.weiyima, index);
|
||||
|
||||
redisManager.db.StringSet(key, JsonPack.GetJson(deskinfo.burs[index]));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存牌局数据包
|
||||
/// </summary>
|
||||
/// <param name="weiyima"></param>
|
||||
/// <param name="data"></param>
|
||||
public static void SaveFightData(string weiyima, byte[] data)
|
||||
{
|
||||
FightDataManager.Instance.SaveFightData(weiyima,data);
|
||||
}
|
||||
|
||||
public static void DelFightData(string weiyima)
|
||||
{
|
||||
FightDataManager.Instance.DelFightData(weiyima);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加载牌局数据包
|
||||
/// </summary>
|
||||
/// <param name="weiyima"></param>
|
||||
/// <returns></returns>
|
||||
public static byte[] LoadFightData(string weiyima,out bool isOld)
|
||||
{
|
||||
byte[] data = FightDataManager.Instance.LoadFightData(weiyima,out isOld);
|
||||
return data;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加载战斗记录-回放用 --- todo 改成二进制存储
|
||||
/// </summary>
|
||||
/// <param name="weiyima">朋友房唯一码</param>
|
||||
/// <param name="playCnt">玩的场次</param>
|
||||
/// <param name="data">战斗数据</param>
|
||||
public static void LoadFightRecord(string weiyima, int playCnt, out FightData data)
|
||||
{
|
||||
string key = RedisDictionary.friendRoomfightRecord + playCnt + ":" + weiyima;
|
||||
|
||||
//先找文本
|
||||
string fileName = $"fightRecord/{key}";
|
||||
fileName = fileName.Replace(":", "");
|
||||
if (File.Exists(fileName))
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
string jsonData = File.ReadAllText(fileName);
|
||||
data = JsonConvert.DeserializeObject<FightData>(jsonData);
|
||||
File.Delete(fileName);
|
||||
Debug.Info("读取回放数据!!");
|
||||
return;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error($"加载战绩报错!{weiyima},{playCnt}" + e.Message);
|
||||
}
|
||||
}
|
||||
|
||||
var values = redisManager.db.ListRange(key);
|
||||
if (values == null || values.Length == 0)
|
||||
{
|
||||
data = new FightData();
|
||||
return;
|
||||
}
|
||||
else
|
||||
{
|
||||
data = new FightData();
|
||||
try
|
||||
{
|
||||
int len = values.Length;
|
||||
for (int i = 1; i < len; i++)
|
||||
{
|
||||
var dataone = JsonPack.GetData<fightdataone>(values[i]);
|
||||
data.fightPack.Add(dataone);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error($"加载战斗数据-出现错误!!! {e.Message}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 设置总结算
|
||||
/// </summary>
|
||||
public static void SetSumBurs(DeskInfo deskinfo)
|
||||
{
|
||||
if (deskinfo == null) return;
|
||||
//if (!deskinfo.isAllOver) return;
|
||||
if (deskinfo.seat == null || deskinfo.seat.Length <= 0 || deskinfo.burs == null ||
|
||||
deskinfo.burs.Count <= 0) return;
|
||||
try
|
||||
{
|
||||
deskinfo.SumBurs.Clear();
|
||||
int[] seat = new int[deskinfo.seat.Length];
|
||||
decimal[] score = new decimal[seat.Length];
|
||||
for (int i = 0; i < deskinfo.seat.Length; i++)
|
||||
{
|
||||
seat[i] = deskinfo.seat[i];
|
||||
var num = deskinfo.GetTotalScore(seat[i]);
|
||||
score[i] = num * (decimal)deskinfo.rule.peilv;
|
||||
}
|
||||
|
||||
score = CalcCapping(score, deskinfo.rule.Capping);
|
||||
for (int i = 0; i < seat.Length; i++)
|
||||
{
|
||||
DeskInfo.SummaryBureau temp = new DeskInfo.SummaryBureau { seat = seat[i], Score = score[i] };
|
||||
deskinfo.SumBurs.Add(temp);
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error($"SetSumBurs error:{e.Message},code:{e.StackTrace},Data info");
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 计算超过封顶的玩家,让赢的玩家均摊
|
||||
/// </summary>
|
||||
/// <param name="playScore"></param>
|
||||
/// <param name="capping"></param>
|
||||
/// <returns></returns>
|
||||
public static decimal[] CalcCapping(decimal[] playScore, int capping)
|
||||
{
|
||||
if (capping <= 0) return playScore;
|
||||
int len = playScore.Length;
|
||||
decimal zongDuo = 0; //输的多出来的总数
|
||||
decimal zongShu = 0; //超过封顶的玩家 输的总数
|
||||
List<int> winIdx = new List<int>(); //赢钱人的下标
|
||||
List<decimal> winJian = new List<decimal>(); //存储赢钱人平均摊的数值
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
var temp = Math.Abs(playScore[i]);
|
||||
if (playScore[i] < 0 && temp > capping)
|
||||
{
|
||||
zongDuo += temp - capping;
|
||||
playScore[i] = 0 - capping;
|
||||
}
|
||||
|
||||
if (playScore[i] > 0)
|
||||
{
|
||||
zongShu += playScore[i];
|
||||
winIdx.Add(i);
|
||||
}
|
||||
}
|
||||
|
||||
for (int i = 0; i < winIdx.Count - 1; i++)
|
||||
{
|
||||
var temp = zongDuo * playScore[winIdx[i]] / zongShu;
|
||||
winJian.Add(Math.Round(temp, 2));
|
||||
}
|
||||
|
||||
var temp1 = zongDuo - winJian.Sum();
|
||||
winJian.Add(temp1);
|
||||
for (int i = 0; i < winIdx.Count; i++)
|
||||
{
|
||||
playScore[winIdx[i]] = playScore[winIdx[i]] - winJian[i];
|
||||
}
|
||||
|
||||
return playScore;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据唯一码获取房间号
|
||||
/// </summary>
|
||||
/// <param name="weiyima">唯一码</param>
|
||||
/// <returns>房间号</returns>
|
||||
public static string GetRoomNum(string weiyima)
|
||||
{
|
||||
string key = GetWeiYiMaKey(weiyima);
|
||||
|
||||
return redisManager.db.HashGet(key, roomNumField);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加载房间数据_当前房间
|
||||
/// </summary>
|
||||
/// <param name="weiyima">唯一码</param>
|
||||
/// <param name="data">房间数据</param>
|
||||
/// <returns>是否加载成功</returns>
|
||||
public static bool LoadRoom(string weiyima, out DeskInfo data)
|
||||
{
|
||||
string key = GetWeiYiMaKey(weiyima);
|
||||
|
||||
data = new DeskInfo();
|
||||
|
||||
DeskInfo dt = data;
|
||||
dt.rule = new DeskRule();
|
||||
DeskRule rule = dt.rule;
|
||||
|
||||
Func<bool> func = () =>
|
||||
{
|
||||
dt.weiyima = weiyima;
|
||||
try
|
||||
{
|
||||
//获取朋友房数据 //朋友房基本数据
|
||||
HashEntry[] hes = redisManager.db.HashGetAll(key);
|
||||
if (hes == null || hes.Length <= 0)
|
||||
return false;
|
||||
foreach (var he in hes)
|
||||
{
|
||||
switch (he.Name)
|
||||
{
|
||||
case roomNumField:
|
||||
dt.roomNum = he.Value;
|
||||
break;
|
||||
case pwdField:
|
||||
rule.pwd = he.Value;
|
||||
break;
|
||||
case maxCntField:
|
||||
rule.maxCnt = int.Parse(he.Value);
|
||||
break;
|
||||
case minCntField:
|
||||
rule.minCnt = int.Parse(he.Value);
|
||||
break;
|
||||
case warCntField:
|
||||
rule.warCnt = int.Parse(he.Value);
|
||||
break;
|
||||
case exField:
|
||||
var ex = JsonPack.GetData<string[]>(he.Value);
|
||||
rule.ex = ex;
|
||||
break;
|
||||
case ruleexField:
|
||||
var exstr = he.value;
|
||||
rule.RuleEx = string.IsNullOrEmpty(exstr)
|
||||
? new DeskRuleEx()
|
||||
: JsonPack.GetData<DeskRuleEx>(exstr);
|
||||
break;
|
||||
case "peilv":
|
||||
rule.peilv = float.Parse(he.Value);
|
||||
break;
|
||||
case "Capping":
|
||||
rule.Capping = int.Parse(he.value);
|
||||
break;
|
||||
case "Remarks":
|
||||
rule.Remarks = he.value;
|
||||
break;
|
||||
case overCntField:
|
||||
dt.overCnt = int.Parse(he.Value);
|
||||
break;
|
||||
case gameidField:
|
||||
rule.game_serid = int.Parse(he.Value);
|
||||
break;
|
||||
case serverVerField:
|
||||
dt.serverVer = int.Parse(he.Value);
|
||||
break;
|
||||
case CreateStyleField:
|
||||
dt.creatStyle = int.Parse(he.Value);
|
||||
break;
|
||||
case CreateIdField:
|
||||
dt.creatUserid = int.Parse(he.Value);
|
||||
break;
|
||||
case fangkaField:
|
||||
dt.fangka = int.Parse(he.Value);
|
||||
break;
|
||||
|
||||
case seatTagField:
|
||||
dt.seat = JsonPack.GetData<int[]>(he.Value);
|
||||
Debug.Info("座位号:" + he.Value);
|
||||
break;
|
||||
case roomRuleField:
|
||||
dt.rule.roomrule = he.Value;
|
||||
break;
|
||||
case CreateTimeField:
|
||||
dt.CreateTime = DateTime.Parse(he.Value);
|
||||
break;
|
||||
case nowCntField:
|
||||
dt.nowCnt = int.Parse(he.Value);
|
||||
break;
|
||||
case interceptIpField:
|
||||
rule.interceptIp = int.Parse(he.Value);
|
||||
break;
|
||||
case interceptWeChatField:
|
||||
rule.interceptWeChat = int.Parse(he.Value);
|
||||
break;
|
||||
case isCloseField:
|
||||
dt.isClose = int.Parse(he.Value);
|
||||
break;
|
||||
case closeTimeField:
|
||||
dt.closeTime = DateTime.Parse(he.Value);
|
||||
break;
|
||||
case jointimeOutField:
|
||||
dt.jointimeOutDis = DateTime.Parse(he.Value);
|
||||
break;
|
||||
case wartimeOutField:
|
||||
dt.wartimeOutDis = DateTime.Parse(he.Value);
|
||||
break;
|
||||
case wayidField:
|
||||
dt.wayid = he.Value;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
//RedisDictionary.friendRoomPlayerField+
|
||||
|
||||
dt.pls = new DeskInfo.PlayerData[rule.maxCnt];
|
||||
dt.OnceFight = new int[rule.maxCnt];
|
||||
for (int i = 0; i < rule.maxCnt; i++)
|
||||
{
|
||||
//加载玩家数据
|
||||
string
|
||||
plkey = GetPlayerKey(weiyima, i); // RedisDictionary.friendRoomPlayerField + weiyima+"."+i;
|
||||
|
||||
HashEntry[] plhes = redisManager.db.HashGetAll(plkey);
|
||||
|
||||
if (plhes == null || plhes.Length <= 0)
|
||||
{
|
||||
dt.pls[i] = null;
|
||||
}
|
||||
else
|
||||
{
|
||||
dt.pls[i] = new DeskInfo.PlayerData();
|
||||
foreach (HashEntry he in plhes)
|
||||
{
|
||||
switch (he.Name)
|
||||
{
|
||||
case useridField:
|
||||
dt.pls[i].userid = int.Parse(he.Value);
|
||||
break;
|
||||
case nickNameField:
|
||||
dt.pls[i].nickName = he.Value;
|
||||
break;
|
||||
case sexField:
|
||||
dt.pls[i].sex = int.Parse(he.Value);
|
||||
break;
|
||||
case photoField:
|
||||
dt.pls[i].photo = he.Value;
|
||||
break;
|
||||
case fangzhuField:
|
||||
dt.pls[i].fangzhu = int.Parse(he.Value);
|
||||
break;
|
||||
case "clubid":
|
||||
dt.pls[i].ClubId = int.Parse(he.Value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
//加载战斗记录
|
||||
int cnt = dt.nowCnt != 0 ? dt.nowCnt : dt.overCnt;
|
||||
for (int i = 0; i < cnt; i++)
|
||||
{
|
||||
string fightkey = GetBureauKey(weiyima, i); // RedisDictionary.friendRoomField+weiyima+i;
|
||||
|
||||
DeskInfo.Bureau bru = new DeskInfo.Bureau();
|
||||
bru.id = i;
|
||||
|
||||
string jsonfihtrecord = redisManager.db.StringGet(fightkey);
|
||||
if (jsonfihtrecord != null)
|
||||
bru = JsonPack.GetData<DeskInfo.Bureau>(jsonfihtrecord);
|
||||
|
||||
dt.burs.Add(bru);
|
||||
}
|
||||
|
||||
Debug.Info("桌子加载成功!");
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error("加载房间号错误:" + e.ToString());
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
bool r = roomlock.LockRun(key, func, 5);
|
||||
data.plsDis = new int[data.rule.maxCnt];
|
||||
Room.SetSumBurs(data);
|
||||
return r;
|
||||
}
|
||||
|
||||
//创建房间移除房间修改房间只能又一个程序处理 其他程序只能读数据,不能改数据
|
||||
|
||||
/// <summary>
|
||||
/// 创建房间 只负责redis数据
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
public static bool CreateRoom(DeskInfo data, ServerNode node)
|
||||
{
|
||||
//房间号-> 唯一码 - 管理的模块
|
||||
//朋友房的房间信息
|
||||
|
||||
//保证数据一致性
|
||||
|
||||
//先写房间号 - 唯一码 - 管理模块
|
||||
|
||||
string roomnum = data.roomNum;
|
||||
string weiyima = data.weiyima;
|
||||
|
||||
//不存在才可以改,存在,不能改
|
||||
var db = redisManager.GetDataBase();
|
||||
|
||||
string key = Roomkey(roomnum);
|
||||
string datakey = RedisDictionary.friendRoomField + data.weiyima;
|
||||
|
||||
var tran = db.CreateTransaction();
|
||||
tran.AddCondition(Condition.KeyNotExists(key)); //不存在才能执行事务
|
||||
tran.AddCondition(Condition.KeyNotExists(datakey));
|
||||
|
||||
HashEntry[] hes = new HashEntry[2];
|
||||
hes[0] = new HashEntry("weiyima", weiyima);
|
||||
hes[1] = new HashEntry("server", JsonPack.GetJson(node));
|
||||
tran.HashSetAsync(key, hes);
|
||||
|
||||
var datahes = GetDeskInfoHashEntry(data);
|
||||
|
||||
|
||||
tran.HashSetAsync(datakey, datahes.ToArray()); //保存朋友房数据
|
||||
|
||||
Debug.Info("创建朋友房:" + key + "," + datakey);
|
||||
|
||||
return tran.Execute();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取桌子信息
|
||||
/// </summary>
|
||||
private static List<HashEntry> GetDeskInfoHashEntry(DeskInfo data)
|
||||
{
|
||||
List<HashEntry> datahes = new List<HashEntry>();
|
||||
datahes.Add(new HashEntry(roomNumField, data.roomNum));
|
||||
DeskRule rule = data.rule;
|
||||
if (rule.pwd == null)
|
||||
rule.pwd = string.Empty;
|
||||
datahes.Add(new HashEntry(pwdField, rule.pwd));
|
||||
datahes.Add(new HashEntry(maxCntField, rule.maxCnt));
|
||||
datahes.Add(new HashEntry(minCntField, rule.minCnt));
|
||||
datahes.Add(new HashEntry(warCntField, rule.warCnt));
|
||||
datahes.Add(new HashEntry(nowCntField, data.nowCnt));
|
||||
datahes.Add(new HashEntry(overCntField, data.overCnt));
|
||||
datahes.Add(new HashEntry(gameidField, rule.game_serid));
|
||||
datahes.Add(new HashEntry(serverVerField, data.serverVer));
|
||||
datahes.Add(new HashEntry(CreateStyleField, data.creatStyle));
|
||||
datahes.Add(new HashEntry(CreateIdField, data.creatUserid));
|
||||
datahes.Add(new HashEntry(fangkaField, data.fangka));
|
||||
datahes.Add(new HashEntry(seatTagField, JsonPack.GetJson(data.seat)));
|
||||
datahes.Add(new HashEntry(roomRuleField, data.rule.roomrule));
|
||||
datahes.Add(new HashEntry(CreateTimeField, data.CreateTime.ToString()));
|
||||
datahes.Add(new HashEntry(interceptIpField, rule.interceptIp));
|
||||
datahes.Add(new HashEntry(interceptWeChatField, rule.interceptWeChat));
|
||||
datahes.Add(new HashEntry(isCloseField, data.isClose));
|
||||
datahes.Add(new HashEntry(closeTimeField, data.closeTime.ToString()));
|
||||
datahes.Add(new HashEntry(exField, JsonPack.GetJson(data.rule.ex)));
|
||||
datahes.Add(new HashEntry(ruleexField, data.rule.RuleExStr));
|
||||
datahes.Add(new HashEntry("peilv", rule.peilv));
|
||||
datahes.Add(new HashEntry("Capping", rule.Capping));
|
||||
datahes.Add(new HashEntry("Remarks", rule.Remarks == null ? "" : rule.Remarks.ToString()));
|
||||
datahes.Add(new HashEntry(wartimeOutField, data.wartimeOutDis.ToString()));
|
||||
datahes.Add(new HashEntry(jointimeOutField, data.jointimeOutDis.ToString()));
|
||||
if (data.wayid != null)
|
||||
datahes.Add(new HashEntry(wayidField, data.wayid.ToString()));
|
||||
return datahes;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重新写入房间
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <returns></returns>
|
||||
public static bool RenewRoom(DeskInfo data)
|
||||
{
|
||||
string roomnum = data.roomNum;
|
||||
string weiyima = data.weiyima;
|
||||
|
||||
//不存在才可以改,存在,不能改
|
||||
var db = redisManager.GetDataBase();
|
||||
string key = Roomkey(roomnum);
|
||||
string datakey = RedisDictionary.friendRoomField + data.weiyima;
|
||||
|
||||
var datahes = GetDeskInfoHashEntry(data);
|
||||
db.HashSetAsync(datakey, datahes.ToArray()); //保存朋友房数据
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除房间 ->先删房间主体->删除房间玩家数据->玩家详情
|
||||
/// </summary>
|
||||
/// <param name="data"></param>
|
||||
/// <returns></returns>
|
||||
public static bool DeleteRoom(DeskInfo data)
|
||||
{
|
||||
if (!data.noWar)
|
||||
{
|
||||
//开战过保存到数据库
|
||||
Task.Factory.StartNew(() =>
|
||||
{
|
||||
SaveRoomData(data);
|
||||
SaveRoomPlayerData(data);
|
||||
});
|
||||
}
|
||||
|
||||
var db = redisManager.GetDataBase();
|
||||
|
||||
var tran = db.CreateTransaction();
|
||||
|
||||
//删除玩家的被锁的 房间号-对应的唯一码
|
||||
//删除房间号-被锁的唯一码
|
||||
//删除房间详细数据
|
||||
//删除玩家数据
|
||||
//删除每局详情,删除玩家详情
|
||||
|
||||
string key = Roomkey(data.roomNum);
|
||||
tran.KeyDeleteAsync(key); //房间号-对应的唯一码
|
||||
|
||||
int len = data.pls.Length;
|
||||
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
if (data.pls[i] == null) continue;
|
||||
string plkey = GetPlayerNumKey(data.pls[i].userid);
|
||||
tran.KeyDeleteAsync(plkey); //清楚玩家所在的房间号以及对应的唯一码
|
||||
int index = -1;
|
||||
int count = data.seat.Length; //玩家玩家详细数据
|
||||
for (int j = 0; j < count; j++)
|
||||
{
|
||||
if (data.seat[j] == i)
|
||||
{
|
||||
index = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (index < 0)
|
||||
{
|
||||
Debug.Error("未找到玩家位置!");
|
||||
continue;
|
||||
}
|
||||
|
||||
string pldatakey = GetPlayerKey(data.weiyima, index);
|
||||
tran.KeyDeleteAsync(pldatakey);
|
||||
}
|
||||
|
||||
//删除房间详细数据
|
||||
|
||||
string datakey = RedisDictionary.friendRoomField + data.weiyima;
|
||||
tran.KeyDeleteAsync(datakey);
|
||||
|
||||
DelFightData(data.weiyima);
|
||||
// string fightdatakey = GetFightDataKey(data.weiyima);
|
||||
// tran.KeyDeleteAsync(fightdatakey);
|
||||
|
||||
//Debug.Error("解散游戏数据!" + data.overCnt + "," + fightdatakey);
|
||||
|
||||
for (int i = 0; i < data.overCnt + 1; i++)
|
||||
{
|
||||
string bureaukey = GetBureauKey(data.weiyima, i);
|
||||
tran.KeyDeleteAsync(bureaukey);
|
||||
}
|
||||
|
||||
return tran.Execute();
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存房间基本数据
|
||||
/// </summary>
|
||||
static void SaveRoomData(DeskInfo data)
|
||||
{
|
||||
DeskRule rule = data.rule;
|
||||
var sql = GameDB.Instance.BeginSetProcedureParameter(dbbase.game2018, "SaveRoomData202408");
|
||||
GameDB.Instance.AddProdureParameters(sql, "@weiyima", SqlDbType.Char, data.weiyima);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@roomnum", SqlDbType.Char, data.roomNum);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@maxcnt", SqlDbType.Int, rule.maxCnt);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@mincnt", SqlDbType.Int, rule.minCnt);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@warcnt", SqlDbType.Int, rule.warCnt);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@nowcnt", SqlDbType.Int, data.nowCnt);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@overcnt", SqlDbType.Int, data.overCnt);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@gameid", SqlDbType.Int, rule.game_serid);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@serverVer", SqlDbType.Int, data.serverVer);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@createStyle", SqlDbType.Int, data.creatStyle);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@createid", SqlDbType.Int, data.creatUserid);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@fangka", SqlDbType.Int, data.fangka);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@interceptIp", SqlDbType.Int, rule.interceptIp);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@interceptWeChat", SqlDbType.Int, rule.interceptWeChat);
|
||||
|
||||
byte[] bts = System.Text.Encoding.UTF8.GetBytes(data.rule.roomrule);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@roomrule", SqlDbType.Image, bts); //json的base64数据
|
||||
|
||||
GameDB.Instance.AddProdureParameters(sql, "@createTime", SqlDbType.DateTime, data.CreateTime);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@closeTime", SqlDbType.DateTime, data.closeTime);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@ex", SqlDbType.Text, JsonPack.GetJson(data.rule.ex));
|
||||
|
||||
GameDB.Instance.AddProdureParameters(sql, "@ruleEx", SqlDbType.Text, data.rule.RuleExStr);
|
||||
|
||||
GameDB.Instance.AddProdureParameters(sql, "@peilv", SqlDbType.Float, rule.peilv);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@Capping", SqlDbType.Int, rule.Capping);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@Remarks", SqlDbType.VarChar,
|
||||
rule.Remarks == null ? "" : rule.Remarks);
|
||||
GameDB.Instance.EndAddProdureParameters(sql);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存玩家数据
|
||||
/// </summary>
|
||||
static void SaveRoomPlayerData(DeskInfo data)
|
||||
{
|
||||
int len = data.pls.Length;
|
||||
for (int i = 0; i < len; i++)
|
||||
{
|
||||
if (data.pls[i] == null) continue; //这个位置没人
|
||||
|
||||
var sql = GameDB.Instance.BeginSetProcedureParameter(dbbase.game2018, "SaveRoom_PlayerData2024");
|
||||
GameDB.Instance.AddProdureParameters(sql, "@weiyima", SqlDbType.Char, data.weiyima);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@playeridx", SqlDbType.Int, i);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@userid", SqlDbType.Int, data.pls[i].userid);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@nickName", SqlDbType.NChar, data.pls[i].nickName);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@sex", SqlDbType.Int, data.pls[i].sex);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@clubid", SqlDbType.Int, data.pls[i].ClubId);
|
||||
|
||||
byte[] bts = Encoding.UTF8.GetBytes(data.pls[i].photo);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@photo", SqlDbType.Image, bts);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@fangzhu", SqlDbType.Int, data.pls[i].fangzhu);
|
||||
|
||||
long allScore = 0;
|
||||
foreach (var item in data.burs)
|
||||
{
|
||||
allScore += item.playScore[i];
|
||||
}
|
||||
|
||||
GameDB.Instance.AddProdureParameters(sql, "@allScore", SqlDbType.Int, allScore);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@gameid", SqlDbType.Int, data.rule.game_serid);
|
||||
GameDB.Instance.EndAddProdureParameters(sql);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存战斗数据
|
||||
/// </summary>
|
||||
/// <param name="deskinfo"></param>
|
||||
/// <param name="data"></param>
|
||||
/// <param name="style">结束类型</param>
|
||||
public static void SaveFightRecord(DeskInfo deskinfo, FightData data, int style = -1)
|
||||
{
|
||||
//ClearFightRecord(deskinfo.weiyima, deskinfo.burs.Count);
|
||||
if (data == null)
|
||||
return;
|
||||
Debug.Info("保存战斗记录到数据库!");
|
||||
//string jsondata = JsonPack.GetJson(data);
|
||||
int idx = deskinfo.burs.Count;
|
||||
int index = idx - 1;
|
||||
if (index < 0)
|
||||
{
|
||||
Debug.Warning("未开战过,无需保存!");
|
||||
return;
|
||||
}
|
||||
|
||||
int lx = deskinfo.creatStyle;
|
||||
var playScore = deskinfo.burs[index].playScore;
|
||||
//string score = JsonPack.GetJson(playScore);
|
||||
var seatd = deskinfo.burs[index].seat;
|
||||
//string seat = JsonPack.GetJson(seatd);
|
||||
string weiyima = deskinfo.weiyima;
|
||||
|
||||
if (lx == 5 || lx == 0)
|
||||
{
|
||||
RoomFightData temp = new RoomFightData { playScore = playScore, seat = seatd, data = data, style = style };
|
||||
FightRecordManager.Instance.SaveFightInfo(weiyima, temp, idx);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 房间号key 里面保存着,管理房间的模块以及房间号对应的唯一码
|
||||
/// </summary>
|
||||
/// <param name="roomnum">房间号</param>
|
||||
/// <returns>返回值</returns>
|
||||
public static string Roomkey(string roomnum)
|
||||
{
|
||||
return "Game:FriendRoom:RoomNum:" + roomnum;
|
||||
}
|
||||
|
||||
public static string GetClubFightKey(int userId)
|
||||
{
|
||||
return $"ClubFightLock:{userId}";
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 锁住俱乐部玩家
|
||||
/// </summary>
|
||||
/// <param name="userid"></param>
|
||||
/// <param name="serId"></param>
|
||||
public static void LockClubFightPlayer(List<int> userid, int serId)
|
||||
{
|
||||
try
|
||||
{
|
||||
var ts = TimeSpan.FromHours(1);
|
||||
IBatch batch = redisManager.db.CreateBatch();
|
||||
for (int i = 0; i < userid.Count; i++)
|
||||
{
|
||||
batch.StringSetAsync(GetClubFightKey(userid[i]), serId, ts);
|
||||
}
|
||||
batch.Execute();
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error($"LockClubFightPlayer Error:{e.Message}");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
52
GameDAL/Game/GoldStyle.cs
Normal file
52
GameDAL/Game/GoldStyle.cs
Normal file
@ -0,0 +1,52 @@
|
||||
/********************************
|
||||
*
|
||||
* 作者:吴隆健
|
||||
* 创建时间: 2019/7/3 15:00:59
|
||||
*
|
||||
********************************/
|
||||
|
||||
using System;
|
||||
using System.ComponentModel;
|
||||
|
||||
namespace GameDAL.Game {
|
||||
[Flags]
|
||||
public enum GoldStyle {
|
||||
/// <summary>
|
||||
/// None
|
||||
/// </summary>
|
||||
//[Description("None")]
|
||||
None =0,
|
||||
/// <summary>
|
||||
/// 赠送
|
||||
/// </summary>
|
||||
[Description("赠送")]
|
||||
GiveAway = 1,
|
||||
/// <summary>
|
||||
/// 购买
|
||||
/// </summary>
|
||||
[Description("购买")]
|
||||
Buy = 2,
|
||||
/// <summary>
|
||||
/// 回收
|
||||
/// </summary>
|
||||
[Description("回收")]
|
||||
Recycle = 4,
|
||||
|
||||
/// <summary>
|
||||
/// 存取
|
||||
/// </summary>
|
||||
[Description("存取")]
|
||||
access = 8,
|
||||
/// <summary>
|
||||
/// 其他
|
||||
/// </summary>
|
||||
[Description("其他")]
|
||||
Other = 1024,
|
||||
/// <summary>
|
||||
/// ALL
|
||||
/// </summary>
|
||||
[Description("全部")]
|
||||
All = GiveAway | Buy | Recycle | access | Other
|
||||
}
|
||||
|
||||
}
|
||||
59
GameDAL/Game/PlayerDB.cs
Normal file
59
GameDAL/Game/PlayerDB.cs
Normal file
@ -0,0 +1,59 @@
|
||||
/********************************
|
||||
*
|
||||
* 作者:吴隆健
|
||||
* 创建时间: 2019/7/3 15:00:59
|
||||
*
|
||||
********************************/
|
||||
|
||||
using System;
|
||||
using System.Data;
|
||||
using Server.DB.Sql;
|
||||
using GameData;
|
||||
using MrWu.Debug;
|
||||
using System.Threading.Tasks;
|
||||
using MrWu.Basic;
|
||||
using System.Data.SqlClient;
|
||||
|
||||
namespace GameDAL.Game {
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
public static class PlayerDB {
|
||||
|
||||
/// <summary>
|
||||
/// 读取玩家数据——存储过程
|
||||
/// </summary>
|
||||
private static string Fun_ReeadPlayerData2025 = "ReadPlayerData2025";
|
||||
|
||||
/// <summary>
|
||||
/// 保存玩家数据——存储过程
|
||||
/// 增加比赛卷逻辑 2021年6月8日11:15:15
|
||||
/// </summary>
|
||||
private static string Fun_SavePlayerData = "SavePlayerData_Roll2023";//"SavePlayerData";
|
||||
|
||||
/// <summary>
|
||||
/// 读取玩家数据
|
||||
/// </summary>
|
||||
public static DataSet ReadPlayerData(int userid, bool hasPi) {
|
||||
var sql = GameDB.Instance.BeginSetProcedureParameter(dbbase.gamedb, Fun_ReeadPlayerData2025);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@userid", SqlDbType.Int, userid);
|
||||
GameDB.Instance.AddProdureParameters(sql, "@hasPi", SqlDbType.Int, hasPi ? 1 : 0);
|
||||
|
||||
DataSet ds = new DataSet();
|
||||
GameDB.Instance.EndAddProdureParameters(sql, ds);
|
||||
return ds;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 保存玩家数据
|
||||
/// </summary>
|
||||
/// <param name="pdc">玩家变化的数据</param>
|
||||
/// <returns>返回值</returns>
|
||||
public static bool SavePlayerData(PlayerDataChange pdc)
|
||||
{
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
44
GameDAL/Game/SessionUUID.cs
Normal file
44
GameDAL/Game/SessionUUID.cs
Normal file
@ -0,0 +1,44 @@
|
||||
using System;
|
||||
using Server.DB.Redis;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace GameDAL.Game
|
||||
{
|
||||
public static class SessionUUID
|
||||
{
|
||||
private const string key = "SessionUUID";
|
||||
|
||||
/// <summary>
|
||||
/// 一天时间再过期
|
||||
/// </summary>
|
||||
private const int ExpireTime = 24 * 60;
|
||||
|
||||
public static string GetSessionUUIDKey(string sessionUUID)
|
||||
{
|
||||
return $"{key}:{sessionUUID}";
|
||||
}
|
||||
|
||||
public static void UpdateExpiredTime(string sessionUUID)
|
||||
{
|
||||
redisManager.db.KeyExpire(GetSessionUUIDKey(sessionUUID), TimeSpan.FromMinutes(ExpireTime));
|
||||
}
|
||||
|
||||
public static string CreateSessionUUID(int userid)
|
||||
{
|
||||
string sessionUUID = Guid.NewGuid().ToString().Replace("-", "");
|
||||
redisManager.db.StringSet(GetSessionUUIDKey(sessionUUID), userid, TimeSpan.FromMinutes(ExpireTime));
|
||||
return sessionUUID;
|
||||
}
|
||||
|
||||
public static int GetUserIdBySessionUUID(string sessionUUID)
|
||||
{
|
||||
RedisValue value = redisManager.db.StringGet(GetSessionUUIDKey(sessionUUID));
|
||||
if (value.HasValue && int.TryParse(value, out int userid) && userid > 0)
|
||||
{
|
||||
return userid;
|
||||
}
|
||||
|
||||
return -1;
|
||||
}
|
||||
}
|
||||
}
|
||||
69
GameDAL/Game/UserWarDataDal.cs
Normal file
69
GameDAL/Game/UserWarDataDal.cs
Normal file
@ -0,0 +1,69 @@
|
||||
using MrWu.Debug;
|
||||
using ObjectModel.Game;
|
||||
using Server.DB.Sql;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using MrWu.DB;
|
||||
|
||||
namespace GameDAL.Game
|
||||
{
|
||||
/// <summary>
|
||||
/// 玩家对战统计
|
||||
/// </summary>
|
||||
public class UserWarDataDal
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据库
|
||||
/// </summary>
|
||||
const dbbase SQLDB = dbbase.game2018;
|
||||
|
||||
private const string Fun_SaveUserWarData = "SaveUserWarData";
|
||||
|
||||
public static Task<bool> SaveUserWarDataAsync(UserWarDataModel model)
|
||||
{
|
||||
return Task.Run(() => SaveUserWarData(model));
|
||||
}
|
||||
|
||||
public static bool SaveUserWarData(UserWarDataModel model)
|
||||
{
|
||||
try
|
||||
{
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error($"出错:{e.Message}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public static Task<UserWarDataModel> GetUserWarDataAsync(int userid,int gameid)
|
||||
{
|
||||
return Task.Run(() => GetUserWarData(userid, gameid));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取玩家的对战数据
|
||||
/// </summary>
|
||||
/// <param name="userid">userid</param>
|
||||
/// <param name="gameId">游戏ID</param>
|
||||
/// <returns></returns>
|
||||
public static UserWarDataModel GetUserWarData(int userid, int gameId) {
|
||||
//UserWarDataModel result = null;
|
||||
try
|
||||
{
|
||||
return UserWarDataModel.Create(userid,gameId);
|
||||
}
|
||||
catch (Exception e) {
|
||||
Debug.Error($"获取玩家的对战数据出错 msg:{e.Message},code:{e.StackTrace}");
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
77
GameDAL/GameDAL.csproj
Normal file
77
GameDAL/GameDAL.csproj
Normal file
@ -0,0 +1,77 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup>
|
||||
<TargetFramework>net48</TargetFramework>
|
||||
<OutputType>Library</OutputType>
|
||||
<RootNamespace>GameDAL</RootNamespace>
|
||||
<AssemblyName>GameDAL</AssemblyName>
|
||||
<LangVersion>8.0</LangVersion>
|
||||
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
<Configurations>Debug;Release</Configurations>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)' == 'Debug'">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<CheckForOverflowUnderflow>true</CheckForOverflowUnderflow>
|
||||
<DefineConstants>DEBUG;TRACE;Server</DefineConstants>
|
||||
</PropertyGroup>
|
||||
|
||||
<PropertyGroup Condition="'$(Configuration)' == 'Release'">
|
||||
<DebugSymbols>false</DebugSymbols>
|
||||
<DebugType>none</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<CheckForOverflowUnderflow>false</CheckForOverflowUnderflow>
|
||||
<DefineConstants>TRACE;Server</DefineConstants>
|
||||
</PropertyGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<PackageReference Include="Dapper" />
|
||||
<PackageReference Include="System.Data.SQLite.Core" />
|
||||
<PackageReference Include="Microsoft.Bcl.AsyncInterfaces" />
|
||||
<PackageReference Include="Newtonsoft.Json" />
|
||||
<PackageReference Include="System.Runtime.CompilerServices.Unsafe" />
|
||||
<PackageReference Include="System.Threading.Tasks.Extensions" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Reference Include="StackExchange.Redis">
|
||||
<HintPath>..\dll\StackExchange.Redis.dll</HintPath>
|
||||
<Private>true</Private>
|
||||
</Reference>
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\CloudAPI\CloudAPI.csproj" />
|
||||
<ProjectReference Include="..\Core\Core.csproj" />
|
||||
<ProjectReference Include="..\NetWorkMessage\NetWorkMessage.csproj" />
|
||||
<ProjectReference Include="..\ObjectModel\ObjectModel.csproj" />
|
||||
<ProjectReference Include="..\ServerCore\ServerCore.csproj" />
|
||||
<ProjectReference Include="..\ServerData\ServerData.csproj" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<None Update="db\redis\RedisTable.txt">
|
||||
<LastGenOutput>RedisTable.txt</LastGenOutput>
|
||||
</None>
|
||||
<None Remove="Club\**" />
|
||||
<None Remove="Eml\**" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Folder Include="DBCore\DB\" />
|
||||
<Folder Include="Game\Promoter\" />
|
||||
<Folder Include="Web\" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<Compile Remove="Club\**" />
|
||||
<Compile Remove="Eml\**" />
|
||||
</ItemGroup>
|
||||
|
||||
<ItemGroup>
|
||||
<EmbeddedResource Remove="Club\**" />
|
||||
<EmbeddedResource Remove="Eml\**" />
|
||||
</ItemGroup>
|
||||
</Project>
|
||||
31
GameDAL/Properties/AssemblyInfo.cs
Normal file
31
GameDAL/Properties/AssemblyInfo.cs
Normal file
@ -0,0 +1,31 @@
|
||||
#region Using directives
|
||||
|
||||
using System;
|
||||
using System.Reflection;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
#endregion
|
||||
|
||||
// General Information about an assembly is controlled through the following
|
||||
// set of attributes. Change these attribute values to modify the information
|
||||
// associated with an assembly.
|
||||
[assembly: AssemblyTitle("GameDAL")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("GameDAL")]
|
||||
[assembly: AssemblyCopyright("Copyright 2019")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// This sets the default COM visibility of types in the assembly to invisible.
|
||||
// If you need to expose a type to COM, use [ComVisible(true)] on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The assembly version has following format :
|
||||
//
|
||||
// Major.Minor.Build.Revision
|
||||
//
|
||||
// You can specify all the values or you can use the default the Revision and
|
||||
// Build Numbers by using the '*' as shown below:
|
||||
[assembly: AssemblyVersion("1.0.0")]
|
||||
47
GameDAL/ServerInfo/GameSeridDic.cs
Normal file
47
GameDAL/ServerInfo/GameSeridDic.cs
Normal file
@ -0,0 +1,47 @@
|
||||
/*
|
||||
* 作者:吴隆健
|
||||
* 日期: 2019-04-18
|
||||
* 时间: 15:48
|
||||
*
|
||||
*/
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using Server.DB.Redis;
|
||||
using MrWu.Debug;
|
||||
|
||||
namespace GameDAL.ServerInfo
|
||||
{
|
||||
/// <summary>
|
||||
/// 游戏模块id 与其对应的serid 字典
|
||||
/// </summary>
|
||||
public class GameSeridDic
|
||||
{
|
||||
private GameSeridDic(){}
|
||||
|
||||
static GameSeridDic(){
|
||||
instance = new GameSeridDic();
|
||||
}
|
||||
|
||||
public static GameSeridDic instance{
|
||||
get;
|
||||
private set;
|
||||
}
|
||||
|
||||
private const string headKey = "Game:NodeInfo:GameSerId";
|
||||
|
||||
/// <summary>
|
||||
/// 游戏服务器对应的id key 为 模块id value 为gameid
|
||||
/// </summary>
|
||||
private ConcurrentDictionary<int,int> GameSers = new ConcurrentDictionary<int, int>();
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// 添加
|
||||
/// </summary>
|
||||
/// <param name="moduleId"></param>
|
||||
/// <param name="serverId"></param>
|
||||
public void Add(int moduleId,int serverId){
|
||||
redisManager.db.HashSet(headKey,moduleId.ToString(),serverId.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
1199
GameDAL/db/RedisCachingHelper.cs
Normal file
1199
GameDAL/db/RedisCachingHelper.cs
Normal file
@ -0,0 +1,1199 @@
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using MrWu.Debug;
|
||||
using Newtonsoft.Json;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Server.DB.Redis {
|
||||
public static class RedisCachingHelper {
|
||||
|
||||
/// <summary>
|
||||
/// 默认缓存过期时间,单位:秒
|
||||
/// </summary>
|
||||
public static int ExpireBySecond { get; set; } = 3600;// 86400;
|
||||
|
||||
/*
|
||||
*
|
||||
* 主要用法 GetOrAdd
|
||||
* RedisType 参数表示 Redis 存储类型,当前支持,String/Hash/List
|
||||
* 泛型类型支持
|
||||
* String 全部JSON支持的类型
|
||||
* Hash 除简单类型外,所有有无参构造方法的类型, 注意:实现IDictionary的类型只支持IDictionary成员,不支持继承扩展属性/字段;
|
||||
* List 数组 以及 实现 IList 接口类型有无参构造的类型;
|
||||
*
|
||||
* acquire Redis 未命中时获取对象的委托方法, 必须返回一个有效对象,以避免缓存穿透
|
||||
* key Redis 标识关键字
|
||||
* dbIdx Redis Database Id
|
||||
* throwIfKeyTypeWrong 在从Redis获取对象时 Redis Key类型错误或对象成员类型错误时是否抛异常, 无此参数的重载默认为 true。
|
||||
* 注意:所有操作redis的网络异常将被屏蔽,所有由类型不匹配和不支持类型将会抛 ArgumentOutOfRangeException 异常
|
||||
*
|
||||
* 缓存过期时间指定,可以使用有expire参数的重载以固定值指定,也可以使用 acquire 参数类型为 Func<Tuple<T, int>> 的重载以灵活方式指定
|
||||
*
|
||||
* 其他:使用本扩展方法,将会对象及对象成员的类型保持强类型特性,存储在redis上的数据是经过JSON格式包装,修改数据必须注意格式。
|
||||
**/
|
||||
|
||||
|
||||
#region 扩展方法
|
||||
|
||||
#region GetOrAdd Generic Sync
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<T> acquire) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, -1, TimeSpan.FromSeconds(ExpireBySecond), true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<T> acquire, int dbIdx) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, dbIdx, TimeSpan.FromSeconds(ExpireBySecond), true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<T> acquire, TimeSpan expire) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, -1, expire, true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<T> acquire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, -1, TimeSpan.FromSeconds(ExpireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<T> acquire, int dbIdx, int expireBySecond) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, dbIdx, TimeSpan.FromSeconds(expireBySecond), true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<T> acquire, int dbIdx, TimeSpan expire) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, dbIdx, expire, true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<T> acquire, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, dbIdx, TimeSpan.FromSeconds(ExpireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<T> acquire, int dbIdx, int expireBySecond, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, dbIdx, TimeSpan.FromSeconds(expireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<T> acquire, TimeSpan expire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, -1, expire, throwIfKeyTypeWrong);
|
||||
}
|
||||
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<T> acquire, int dbIdx, TimeSpan expire, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
if (db.TryGet<T>(redisType, key, out var outValue, throwIfKeyTypeWrong)) {
|
||||
return outValue;
|
||||
}
|
||||
var value = acquire();
|
||||
db.AddToRedis(redisType, key, value, expire);
|
||||
return value;
|
||||
}
|
||||
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Tuple<T, int>> acquire) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, -1, true);
|
||||
}
|
||||
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Tuple<T, int>> acquire, int dbIdx) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, dbIdx, true);
|
||||
}
|
||||
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Tuple<T, int>> acquire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, -1, throwIfKeyTypeWrong);
|
||||
}
|
||||
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Tuple<T, int>> acquire, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
if (db.TryGet<T>(redisType, key, out var outValue, throwIfKeyTypeWrong)) {
|
||||
return outValue;
|
||||
}
|
||||
var value = acquire();
|
||||
db.AddToRedis(redisType, key, value.Item1, TimeSpan.FromSeconds(value.Item2));
|
||||
return value.Item1;
|
||||
}
|
||||
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Tuple<T, TimeSpan>> acquire) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, -1, true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Tuple<T, TimeSpan>> acquire, int dbIdx) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, dbIdx, true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Tuple<T, TimeSpan>> acquire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(redisType, key, acquire, -1, throwIfKeyTypeWrong);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Tuple<T, TimeSpan>> acquire, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
if (db.TryGet<T>(redisType, key, out var outValue, throwIfKeyTypeWrong)) {
|
||||
return outValue;
|
||||
}
|
||||
var value = acquire();
|
||||
db.AddToRedis(redisType, key, value.Item1, value.Item2);
|
||||
return value.Item1;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region GetOrAdd Generic Async
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<T>> acquire) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, -1, TimeSpan.FromSeconds(ExpireBySecond), true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<T>> acquire, int dbIdx) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, dbIdx, TimeSpan.FromSeconds(ExpireBySecond), true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<T>> acquire, TimeSpan expire) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, -1, expire, true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<T>> acquire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, -1, TimeSpan.FromSeconds(ExpireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<T>> acquire, int dbIdx, int expireBySecond) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, dbIdx, TimeSpan.FromSeconds(expireBySecond), true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<T>> acquire, int dbIdx, TimeSpan expire) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, dbIdx, expire, true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<T>> acquire, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, dbIdx, TimeSpan.FromSeconds(ExpireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<T>> acquire, int dbIdx, int expireBySecond, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, dbIdx, TimeSpan.FromSeconds(expireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<T>> acquire, TimeSpan expire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, -1, expire, throwIfKeyTypeWrong);
|
||||
}
|
||||
|
||||
public static async Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<T>> acquire, int dbIdx, TimeSpan expire, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
if (db.TryGet<T>(redisType, key, out var outValue, throwIfKeyTypeWrong)) {
|
||||
return outValue;
|
||||
}
|
||||
var value = await acquire.Invoke();
|
||||
db.AddToRedis(redisType, key, value, expire);
|
||||
return value;
|
||||
}
|
||||
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<Tuple<T, int>>> acquire) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, -1, true);
|
||||
}
|
||||
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<Tuple<T, int>>> acquire, int dbIdx) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, dbIdx, true);
|
||||
}
|
||||
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<Tuple<T, int>>> acquire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, -1, throwIfKeyTypeWrong);
|
||||
}
|
||||
|
||||
public static async Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<Tuple<T, int>>> acquire, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
if (db.TryGet<T>(redisType, key, out var outValue, throwIfKeyTypeWrong)) {
|
||||
return outValue;
|
||||
}
|
||||
var value = await acquire();
|
||||
db.AddToRedis(redisType, key, value.Item1, TimeSpan.FromSeconds(value.Item2));
|
||||
return value.Item1;
|
||||
}
|
||||
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<Tuple<T, TimeSpan>>> acquire) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, -1, true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<Tuple<T, TimeSpan>>> acquire, int dbIdx) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, dbIdx, true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<Tuple<T, TimeSpan>>> acquire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAddAsync(redisType, key, acquire, -1, throwIfKeyTypeWrong);
|
||||
}
|
||||
public static async Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, Func<Task<Tuple<T, TimeSpan>>> acquire, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
if (db.TryGet<T>(redisType, key, out var outValue, throwIfKeyTypeWrong)) {
|
||||
return outValue;
|
||||
}
|
||||
var value = await acquire();
|
||||
db.AddToRedis(redisType, key, value.Item1, value.Item2);
|
||||
return value.Item1;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region GetOrAdd RedisHash Sync
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<T> acquire) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, -1, TimeSpan.FromSeconds(ExpireBySecond), true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<T> acquire, int dbIdx) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, dbIdx, TimeSpan.FromSeconds(ExpireBySecond), true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<T> acquire, TimeSpan expire) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, -1, expire, true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<T> acquire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, -1, TimeSpan.FromSeconds(ExpireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<T> acquire, int dbIdx, int expireBySecond) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, dbIdx, TimeSpan.FromSeconds(expireBySecond), true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<T> acquire, int dbIdx, TimeSpan expire) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, dbIdx, expire, true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<T> acquire, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, dbIdx, TimeSpan.FromSeconds(ExpireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<T> acquire, int dbIdx, int expireBySecond, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, dbIdx, TimeSpan.FromSeconds(expireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<T> acquire, TimeSpan expire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, -1, expire, throwIfKeyTypeWrong);
|
||||
}
|
||||
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<T> acquire, int dbIdx, TimeSpan expire, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
if (db.TryGet<T>(key, field, out var keyExists, out var outValue, throwIfKeyTypeWrong)) {
|
||||
return outValue;
|
||||
}
|
||||
var value = acquire();
|
||||
db.AddToRedis(key, field, keyExists, value, expire);
|
||||
return value;
|
||||
}
|
||||
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Tuple<T, int>> acquire) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, -1, true);
|
||||
}
|
||||
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Tuple<T, int>> acquire, int dbIdx) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, dbIdx, true);
|
||||
}
|
||||
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Tuple<T, int>> acquire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, -1, throwIfKeyTypeWrong);
|
||||
}
|
||||
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Tuple<T, int>> acquire, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
if (db.TryGet<T>(key, field, out var keyExists, out var outValue, throwIfKeyTypeWrong)) {
|
||||
return outValue;
|
||||
}
|
||||
var value = acquire();
|
||||
db.AddToRedis(key, field, keyExists, value.Item1, TimeSpan.FromSeconds(value.Item2));
|
||||
return value.Item1;
|
||||
}
|
||||
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Tuple<T, TimeSpan>> acquire) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, -1, true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Tuple<T, TimeSpan>> acquire, int dbIdx) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, dbIdx, true);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Tuple<T, TimeSpan>> acquire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, -1, throwIfKeyTypeWrong);
|
||||
}
|
||||
public static T GetOrAdd<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Tuple<T, TimeSpan>> acquire, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
if (db.TryGet<T>(key, field, out var keyExists, out var outValue, throwIfKeyTypeWrong)) {
|
||||
return outValue;
|
||||
}
|
||||
var value = acquire();
|
||||
db.AddToRedis(key, field, keyExists, value.Item1, value.Item2);
|
||||
return value.Item1;
|
||||
}
|
||||
|
||||
public static bool TryGet<T>(this IDatabase db, RedisKey key, RedisValue field, out bool keyExists, out T outValue, bool throwIfKeyTypeWrong) {
|
||||
outValue = default(T);
|
||||
keyExists = false;
|
||||
try {
|
||||
var transaction = db.CreateTransaction();
|
||||
var task1 = transaction.KeyTimeToLiveAsync(key);
|
||||
var task2 = transaction.HashGetAsync(key, field);
|
||||
if (transaction.Execute()) {
|
||||
var task1Result = task1.Result;
|
||||
keyExists = task1Result.HasValue && task1Result.Value > TimeSpan.Zero;
|
||||
var redisValue = task2.Result;
|
||||
if (!keyExists || redisValue.IsNullOrEmpty) {
|
||||
return false;
|
||||
}
|
||||
return GetObjectFromJsonWrapper(redisValue, out outValue, throwIfKeyTypeWrong, true, throwIfKeyTypeWrong);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
public static bool AddToRedis(this IDatabase db, RedisKey key, RedisValue field, bool keyExists, object value, TimeSpan timeSpan) {
|
||||
try {
|
||||
var transaction = db.CreateTransaction();
|
||||
transaction.HashSetAsync(key, field, GetStringOfJsonWrapper(value));
|
||||
if (!keyExists) {
|
||||
transaction.KeyExpireAsync(key, timeSpan);
|
||||
}
|
||||
return transaction.Execute();
|
||||
} catch (Exception ex) {
|
||||
Console.WriteLine(ex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
#region GetOrAdd RedisHash Async
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<T>> acquire) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, -1, TimeSpan.FromSeconds(ExpireBySecond), true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<T>> acquire, int dbIdx) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, dbIdx, TimeSpan.FromSeconds(ExpireBySecond), true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<T>> acquire, TimeSpan expire) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, -1, expire, true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<T>> acquire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, -1, TimeSpan.FromSeconds(ExpireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<T>> acquire, int dbIdx, int expireBySecond) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, dbIdx, TimeSpan.FromSeconds(expireBySecond), true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<T>> acquire, int dbIdx, TimeSpan expire) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, dbIdx, expire, true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<T>> acquire, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, dbIdx, TimeSpan.FromSeconds(ExpireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<T>> acquire, int dbIdx, int expireBySecond, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAdd(key, field, acquire, dbIdx, TimeSpan.FromSeconds(expireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<T>> acquire, TimeSpan expire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, -1, expire, throwIfKeyTypeWrong);
|
||||
}
|
||||
|
||||
public static async Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<T>> acquire, int dbIdx, TimeSpan expire, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
if (db.TryGet<T>(key, field, out var keyExists, out var outValue, throwIfKeyTypeWrong)) {
|
||||
return outValue;
|
||||
}
|
||||
var value = await acquire();
|
||||
db.AddToRedis(key, field, keyExists, value, expire);
|
||||
return value;
|
||||
}
|
||||
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<Tuple<T, int>>> acquire) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, -1, true);
|
||||
}
|
||||
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<Tuple<T, int>>> acquire, int dbIdx) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, dbIdx, true);
|
||||
}
|
||||
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<Tuple<T, int>>> acquire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, -1, throwIfKeyTypeWrong);
|
||||
}
|
||||
|
||||
public static async Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<Tuple<T, int>>> acquire, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
if (db.TryGet<T>(key, field, out var keyExists, out var outValue, throwIfKeyTypeWrong)) {
|
||||
return outValue;
|
||||
}
|
||||
var value = await acquire();
|
||||
db.AddToRedis(key, field, keyExists, value.Item1, TimeSpan.FromSeconds(value.Item2));
|
||||
return value.Item1;
|
||||
}
|
||||
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<Tuple<T, TimeSpan>>> acquire) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, -1, true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<Tuple<T, TimeSpan>>> acquire, int dbIdx) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, dbIdx, true);
|
||||
}
|
||||
public static Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<Tuple<T, TimeSpan>>> acquire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.GetOrAddAsync(key, field, acquire, -1, throwIfKeyTypeWrong);
|
||||
}
|
||||
public static async Task<T> GetOrAddAsync<T>(this DbStyle dbStyle, RedisKey key, RedisValue field, Func<Task<Tuple<T, TimeSpan>>> acquire, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
if (db.TryGet<T>(key, field, out var keyExists, out var outValue, throwIfKeyTypeWrong)) {
|
||||
return outValue;
|
||||
}
|
||||
var value = await acquire();
|
||||
db.AddToRedis(key, field, keyExists, value.Item1, value.Item2);
|
||||
return value.Item1;
|
||||
}
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
#region UpdateOrAdd
|
||||
public static T UpdateOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value) {
|
||||
return dbStyle.UpdateOrAdd(redisType, key, value, -1, TimeSpan.FromSeconds(ExpireBySecond), true);
|
||||
}
|
||||
public static T UpdateOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int dbIdx) {
|
||||
return dbStyle.UpdateOrAdd(redisType, key, value, dbIdx, TimeSpan.FromSeconds(ExpireBySecond), true);
|
||||
}
|
||||
public static T UpdateOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, TimeSpan expire) {
|
||||
return dbStyle.UpdateOrAdd(redisType, key, value, -1, expire, true);
|
||||
}
|
||||
public static T UpdateOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.UpdateOrAdd(redisType, key, value, -1, TimeSpan.FromSeconds(ExpireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static T UpdateOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int dbIdx, int expireBySecond) {
|
||||
return dbStyle.UpdateOrAdd(redisType, key, value, dbIdx, TimeSpan.FromSeconds(expireBySecond), true);
|
||||
}
|
||||
public static T UpdateOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int dbIdx, TimeSpan expire) {
|
||||
return dbStyle.UpdateOrAdd(redisType, key, value, dbIdx, expire, true);
|
||||
}
|
||||
public static T UpdateOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.UpdateOrAdd(redisType, key, value, dbIdx, TimeSpan.FromSeconds(ExpireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static T UpdateOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int dbIdx, int expireBySecond, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.UpdateOrAdd(redisType, key, value, dbIdx, TimeSpan.FromSeconds(expireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static T UpdateOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, TimeSpan expire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.UpdateOrAdd(redisType, key, value, -1, expire, throwIfKeyTypeWrong);
|
||||
}
|
||||
public static T UpdateOrAdd<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int dbIdx, TimeSpan expire, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
var existRedisKeyType = RedisType.None;
|
||||
try {
|
||||
//获取原有数据类型
|
||||
existRedisKeyType = db.KeyType(key);
|
||||
} catch (Exception ex) {
|
||||
Debug.Error($"RedisCachingHelper UpdateOrAdd db.KeyType fail, key: {key}, ex: {ex}");
|
||||
}
|
||||
//检查原有key数据类型
|
||||
if (existRedisKeyType != RedisType.None && existRedisKeyType != redisType && throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"redis key 当前存储的数据类型为:{existRedisKeyType}, 新类型为:{redisType}");
|
||||
}
|
||||
|
||||
db.AddToRedis(redisType, key, value, expire);
|
||||
return value;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region UpdateOrAdd Async
|
||||
|
||||
public static Task<T> UpdateOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value) {
|
||||
return dbStyle.UpdateOrAddAsync(redisType, key, value, -1, TimeSpan.FromSeconds(ExpireBySecond), true);
|
||||
}
|
||||
public static Task<T> UpdateOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int dbIdx) {
|
||||
return dbStyle.UpdateOrAddAsync(redisType, key, value, dbIdx, TimeSpan.FromSeconds(ExpireBySecond), true);
|
||||
}
|
||||
public static Task<T> UpdateOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, TimeSpan expire) {
|
||||
return dbStyle.UpdateOrAddAsync(redisType, key, value, -1, expire, true);
|
||||
}
|
||||
public static Task<T> UpdateOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.UpdateOrAddAsync(redisType, key, value, -1, TimeSpan.FromSeconds(ExpireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static Task<T> UpdateOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int dbIdx, int expireBySecond) {
|
||||
return dbStyle.UpdateOrAddAsync(redisType, key, value, dbIdx, TimeSpan.FromSeconds(expireBySecond), true);
|
||||
}
|
||||
public static Task<T> UpdateOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int dbIdx, TimeSpan expire) {
|
||||
return dbStyle.UpdateOrAddAsync(redisType, key, value, dbIdx, expire, true);
|
||||
}
|
||||
public static Task<T> UpdateOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.UpdateOrAddAsync(redisType, key, value, dbIdx, TimeSpan.FromSeconds(ExpireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static Task<T> UpdateOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int dbIdx, int expireBySecond, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.UpdateOrAddAsync(redisType, key, value, dbIdx, TimeSpan.FromSeconds(expireBySecond), throwIfKeyTypeWrong);
|
||||
}
|
||||
public static Task<T> UpdateOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, TimeSpan expire, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.UpdateOrAddAsync(redisType, key, value, -1, expire, throwIfKeyTypeWrong);
|
||||
}
|
||||
public static async Task<T> UpdateOrAddAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int dbIdx, TimeSpan expire, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
var existRedisKeyType = RedisType.None;
|
||||
try {
|
||||
//获取原有数据类型
|
||||
existRedisKeyType = await db.KeyTypeAsync(key);
|
||||
} catch (Exception ex) {
|
||||
Debug.Error($"RedisCachingHelper UpdateOrAdd db.KeyType fail, key: {key}, ex: {ex}");
|
||||
}
|
||||
//检查原有key数据类型
|
||||
if (existRedisKeyType != RedisType.None && existRedisKeyType != redisType && throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"redis key 当前存储的数据类型为:{existRedisKeyType}, 新类型为:{redisType}");
|
||||
}
|
||||
|
||||
db.AddToRedis(redisType, key, value, expire);
|
||||
return value;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Delete
|
||||
|
||||
public static bool Delete(this DbStyle dbStyle, int dbIdx = -1, params RedisKey[] keys) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
return db.KeyDelete(keys) == keys.Length;
|
||||
}
|
||||
public static async Task<bool> DeleteAsync(this DbStyle dbStyle, int dbIdx = -1, params RedisKey[] keys) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
var count = await db.KeyDeleteAsync(keys);
|
||||
return count == keys.Length;
|
||||
}
|
||||
|
||||
public static IDatabase GetDataBase(this DbStyle dbStyle, int dbIdx) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
return db;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region TryGet
|
||||
public static bool TryGet<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, out T outValue) {
|
||||
return dbStyle.TryGet(redisType, key, out outValue, -1, true);
|
||||
}
|
||||
|
||||
public static bool TryGet<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, out T outValue, int dbIdx) {
|
||||
return dbStyle.TryGet(redisType, key, out outValue, dbIdx, true);
|
||||
}
|
||||
public static bool TryGet<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, out T outValue, bool throwIfKeyTypeWrong) {
|
||||
return dbStyle.TryGet(redisType, key, out outValue, -1, throwIfKeyTypeWrong);
|
||||
}
|
||||
public static bool TryGet<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, out T outValue, int dbIdx, bool throwIfKeyTypeWrong) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
return db.TryGet(redisType, key, out outValue, throwIfKeyTypeWrong);
|
||||
}
|
||||
|
||||
public static bool TryGet<T>(this IDatabase db, RedisType redisType, RedisKey key, out T outValue, bool throwIfKeyTypeWrong) {
|
||||
EnsureKeyNotEmptyOrNULL(key);
|
||||
switch (redisType) {
|
||||
case RedisType.String:
|
||||
return db.TryGetString(key, out outValue, throwIfKeyTypeWrong);
|
||||
case RedisType.Hash:
|
||||
return db.TryGetHash(key, out outValue, throwIfKeyTypeWrong);
|
||||
case RedisType.List:
|
||||
return db.TryGetList(key, out outValue, throwIfKeyTypeWrong);
|
||||
case RedisType.Set:
|
||||
case RedisType.SortedSet:
|
||||
throw new NotSupportedException(); //return db.TryGetSet(key, out outValue, throwIfKeyTypeWrong);
|
||||
case RedisType.None:
|
||||
//case RedisType.Stream:
|
||||
case RedisType.Unknown:
|
||||
default:
|
||||
throw new NotSupportedException($"key: {key}, redisType: {redisType}");
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region AddToRedis
|
||||
public static bool AddToRedis<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value) {
|
||||
return dbStyle.AddToRedis(redisType, key, value, TimeSpan.FromSeconds(ExpireBySecond), -1);
|
||||
}
|
||||
public static bool AddToRedis<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int expire) {
|
||||
return dbStyle.AddToRedis(redisType, key, value, TimeSpan.FromSeconds(expire), -1);
|
||||
}
|
||||
public static bool AddToRedis<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int expire, int dbIdx) {
|
||||
return dbStyle.AddToRedis(redisType, key, value, TimeSpan.FromSeconds(expire), dbIdx);
|
||||
}
|
||||
public static bool AddToRedis<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, TimeSpan expire) {
|
||||
return dbStyle.AddToRedis(redisType, key, value, expire, -1);
|
||||
}
|
||||
public static bool AddToRedis<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, TimeSpan expire, int dbIdx) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
return db.AddToRedis(redisType, key, value, expire);
|
||||
}
|
||||
|
||||
public static bool AddToRedis<T>(this IDatabase db, RedisType redisType, RedisKey key, T value, TimeSpan expire) {
|
||||
EnsureKeyNotEmptyOrNULL(key);
|
||||
switch (redisType) {
|
||||
case RedisType.String:
|
||||
return db.AddStringToRedis(key, value, expire);
|
||||
case RedisType.Hash:
|
||||
return db.AddHashToRedis(key, value, expire);
|
||||
case RedisType.List:
|
||||
return db.AddListToRedis(key, value as IEnumerable, expire);
|
||||
case RedisType.Set:
|
||||
case RedisType.SortedSet:
|
||||
throw new NotSupportedException(); //return db.AddSetToRedis(key, value, expire);
|
||||
case RedisType.None:
|
||||
//case RedisType.Stream:
|
||||
case RedisType.Unknown:
|
||||
default:
|
||||
throw new NotSupportedException($"key: {key}, redisType: {redisType}");
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region AddToRedis Async
|
||||
public static Task<bool> AddToRedisAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value) {
|
||||
return dbStyle.AddToRedisAsync(redisType, key, value, TimeSpan.FromSeconds(ExpireBySecond), -1);
|
||||
}
|
||||
public static Task<bool> AddToRedisAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int expire) {
|
||||
return dbStyle.AddToRedisAsync(redisType, key, value, TimeSpan.FromSeconds(expire), -1);
|
||||
}
|
||||
public static Task<bool> AddToRedisAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, int expire, int dbIdx) {
|
||||
return dbStyle.AddToRedisAsync(redisType, key, value, TimeSpan.FromSeconds(expire), dbIdx);
|
||||
}
|
||||
public static Task<bool> AddToRedisAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, TimeSpan expire) {
|
||||
return dbStyle.AddToRedisAsync(redisType, key, value, expire, -1);
|
||||
}
|
||||
public static Task<bool> AddToRedisAsync<T>(this DbStyle dbStyle, RedisType redisType, RedisKey key, T value, TimeSpan expire, int dbIdx) {
|
||||
var db = redisManager.GetDataBase(dbStyle, dbIdx);
|
||||
return db.AddToRedisAsync(redisType, key, value, expire);
|
||||
}
|
||||
|
||||
public static Task<bool> AddToRedisAsync<T>(this IDatabase db, RedisType redisType, RedisKey key, T value, TimeSpan expire) {
|
||||
EnsureKeyNotEmptyOrNULL(key);
|
||||
switch (redisType) {
|
||||
case RedisType.String:
|
||||
return db.AddStringToRedisAsync(key, value, expire);
|
||||
case RedisType.Hash:
|
||||
return db.AddHashToRedisAsync(key, value, expire);
|
||||
case RedisType.List:
|
||||
return db.AddListToRedisAsync(key, value as IEnumerable, expire);
|
||||
case RedisType.Set:
|
||||
case RedisType.SortedSet:
|
||||
throw new NotSupportedException(); //return db.AddSetToRedis(key, value, expire);
|
||||
case RedisType.None:
|
||||
//case RedisType.Stream:
|
||||
case RedisType.Unknown:
|
||||
default:
|
||||
throw new NotSupportedException($"key: {key}, redisType: {redisType}");
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
|
||||
public static IDatabase GetRedisDataBase(this DbStyle style, int dbIdx = -1) => redisManager.GetDataBase(style, dbIdx);
|
||||
#endregion
|
||||
|
||||
#region 扩展功能实现
|
||||
|
||||
#region 以 Redis String 类型存储
|
||||
static bool TryGetString<T>(this IDatabase db, RedisKey key, out T outValue, bool throwIfKeyTypeWrong) {
|
||||
outValue = default(T);
|
||||
if (!db.GetFromRedis(key, throwIfKeyTypeWrong, p => p.StringGet(key), out var redisValue)) {
|
||||
return false;
|
||||
}
|
||||
//检查原始类型与目标类型是否一致
|
||||
return !redisValue.IsNullOrEmpty && GetObjectFromJsonWrapper(redisValue, out outValue, throwIfKeyTypeWrong, true, throwIfKeyTypeWrong);
|
||||
}
|
||||
|
||||
static bool AddStringToRedis<T>(this IDatabase db, RedisKey key, T value, TimeSpan expire) {
|
||||
var stringValue = GetStringOfJsonWrapper(value);
|
||||
return db.ExecuctRedisTransaction(key, expire, false, transaction => transaction.StringSetAsync(key, stringValue));
|
||||
}
|
||||
|
||||
static Task<bool> AddStringToRedisAsync<T>(this IDatabase db, RedisKey key, T value, TimeSpan expire) {
|
||||
var stringValue = GetStringOfJsonWrapper(value);
|
||||
return db.ExecuctRedisTransactionAsync(key, expire, false, transaction => transaction.StringSetAsync(key, stringValue));
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region 以 Redis Hash 类型存储
|
||||
public readonly static string hash_type_field_name = "_@_type_@_name_@_";
|
||||
static bool TryGetHash<T>(this IDatabase db, RedisKey key, out T outValue, bool throwIfKeyTypeWrong) {
|
||||
outValue = default(T);
|
||||
|
||||
if (!db.GetFromRedis(key, throwIfKeyTypeWrong, p => p.HashGetAll(key), out var hashEntries)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
|
||||
if (hashEntries.Length == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
var targetType = typeof(T);
|
||||
var item = hashEntries.SingleOrDefault(p => hash_type_field_name.Equals(p.Name)).Value;
|
||||
if (item.IsNullOrEmpty) {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"Hash 原始类型描述为空:目标类型:{ targetType.FullName}");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
Type originType = null;
|
||||
try {
|
||||
originType = Type.GetType(item);
|
||||
} catch (Exception ex) {
|
||||
Debug.Error($"TryGetHash Type.GetType fail, type: {item}, ex: {ex}");
|
||||
}
|
||||
if (originType == null) {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"无法获取原始类型:{originType}");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
hashEntries = hashEntries.Where(p => !string.Equals(p.Name, hash_type_field_name)).ToArray();
|
||||
|
||||
//检查原始类型与目标类型是否一致
|
||||
if (!originType.Equals(targetType)) {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"无效的目标类型:原始类型:{originType.FullName}, 目标类型:{targetType.FullName}");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
outValue = Activator.CreateInstance<T>();
|
||||
var dictionaryGeneric = targetType.GetInterface(typeOfIDictionaryGeneric.Name);
|
||||
if (dictionaryGeneric != null) {
|
||||
//目标类型是 IDictionary<,>
|
||||
var genericArgs = dictionaryGeneric.GetGenericArguments();
|
||||
var method = TryGetIDictionaryGenericMethod.MakeGenericMethod(genericArgs);
|
||||
var succ = (bool)method.Invoke(null, new object[] { outValue, hashEntries });
|
||||
if (!succ) {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"TryGetHash 解释元素类型不未成功!");
|
||||
}
|
||||
}
|
||||
return succ;
|
||||
} else if (outValue is IDictionary dictionary) {
|
||||
//目标类型是 IDictionary
|
||||
return LoadDictionaryMembersFromHashEntries(hashEntries, dictionary, targetType, throwIfKeyTypeWrong);
|
||||
} else {
|
||||
//目标类型是非 IDictionary 类型
|
||||
return LoadObjectMembersFromHashEntries(hashEntries, outValue, targetType, throwIfKeyTypeWrong);
|
||||
}
|
||||
}
|
||||
static readonly Type typeOfRedisCachingHelper = typeof(RedisCachingHelper);
|
||||
static Type typeOfObject { get; } = typeof(object);
|
||||
static Type typeOfCollectionGeneric { get; } = typeof(Collection<>);
|
||||
static Type typeOfIListGeneric { get; } = typeof(IList<>);
|
||||
static Type typeOfIList { get; } = typeof(IList);
|
||||
static Type typeOfIDictionaryGeneric { get; } = typeof(IDictionary<,>);
|
||||
|
||||
static bool LoadDictionaryMembersFromHashEntries(HashEntry[] hashEntries, IDictionary dictionary, Type targetType, bool throwIfKeyTypeWrong) {
|
||||
foreach (var item in hashEntries) {
|
||||
if (!item.Name.IsNullOrEmpty) {
|
||||
try {
|
||||
if (GetObjectFromJsonWrapper(item.Name, out var dictionaryKeyname) && GetObjectFromJsonWrapper(item.Value, out var dictValue)) {
|
||||
dictionary.Add(dictionaryKeyname, dictValue);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Debug.Error($"StaticCachingHelper LoadDictionaryMembersFromHashEntries fail, ex: {ex}");
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"解析数据发生异常,目标类型:{targetType.FullName}!", ex);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"无效的原始成员名称, Name:{item.Name}, Value:{targetType.FullName}");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool LoadObjectMembersFromHashEntries(HashEntry[] hashEntries, object instance, Type targetType, bool throwIfKeyTypeWrong) {
|
||||
var fields = targetType.GetFields(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.IsInitOnly).ToArray();
|
||||
var props = targetType.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0).ToArray();
|
||||
|
||||
if (fields.Length == 0 && props.Length == 0) {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"类型:{targetType} 没有公开的可读写字段或属性");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
foreach (var item in hashEntries) {
|
||||
if (!item.Value.IsNullOrEmpty) {
|
||||
Action<object, object> valueSetAction = null;
|
||||
Type memberType = null;
|
||||
var fieldInfo = fields.SingleOrDefault(p => p.Name == item.Name);
|
||||
if (fieldInfo != null) {
|
||||
valueSetAction = fieldInfo.SetValue;
|
||||
memberType = fieldInfo.FieldType;
|
||||
} else {
|
||||
var propInfo = props.SingleOrDefault(p => p.Name == item.Name);
|
||||
if (propInfo != null) {
|
||||
valueSetAction = propInfo.SetValue;
|
||||
memberType = propInfo.PropertyType;
|
||||
} else {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"无效的原始成员名称, Name:{item.Name}, Value:{item.Value}");
|
||||
}
|
||||
//缓存的数据对象成员与当前的类型的成员不一致,放弃当前缓存数据
|
||||
return false;
|
||||
}
|
||||
}
|
||||
if (GetObjectFromJsonWrapper(item.Value, out var memberValue, out var memberOriginType, throwIfKeyTypeWrong, false) && memberType.IsAssignableFrom(memberOriginType)) {
|
||||
valueSetAction.Invoke(instance, memberValue);
|
||||
} else {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"无效的原始成员类型与当前成员类型匹配,当前成员类型:{item}, 原始成员类型:{memberOriginType}");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"无效的原始数据, Name:{item.Name}, Value:{item.Value}");
|
||||
}
|
||||
//缓存的数据对象成员与当前的类型的成员不一致,放弃当前缓存数据
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static MethodInfo TryGetIDictionaryGenericMethod { get; } = typeOfRedisCachingHelper.GetMethod(nameof(TryGetIDictionaryGeneric), BindingFlags.Static | BindingFlags.NonPublic);
|
||||
static bool TryGetIDictionaryGeneric<TKey, TValue>(IDictionary<TKey, TValue> dictionary, HashEntry[] hashEntries) {
|
||||
var keyType = typeof(TKey);
|
||||
var valueType = typeof(TValue);
|
||||
foreach (var hashEntry in hashEntries) {
|
||||
if (hashEntry.Name.IsNullOrEmpty || hashEntry.Value.IsNullOrEmpty) {
|
||||
return false;
|
||||
} else if (GetObjectFromJsonWrapper(hashEntry.Name, out var key, out var originKeyType, false, false) && GetObjectFromJsonWrapper(hashEntry.Value, out var value, out var originValueType, false, false)) {
|
||||
if (!(keyType.IsAssignableFrom(originKeyType) || (key == null && (keyType.IsClass || keyType.IsInterface)))) {//反序列化成员数据失败,有可能成员类型已改变
|
||||
Debug.Error($"StaticCachingHelper TryGetIDictionaryGeneric fail, hashEntry.Name: {hashEntry.Name}, 类型不正确: 要求元素类型:{keyType}, 原始数据元素类型:{originKeyType}");
|
||||
return false;
|
||||
}
|
||||
if (!(valueType.IsAssignableFrom(originValueType) || (value == null && (valueType.IsClass || valueType.IsInterface)))) {
|
||||
Debug.Error($"StaticCachingHelper TryGetIDictionaryGeneric fail, hashEntry.Value: {hashEntry.Value}, 类型不正确: 要求元素类型:{valueType}, 原始数据元素类型:{originValueType}");
|
||||
return false;
|
||||
}
|
||||
dictionary.Add((TKey)key, (TValue)value);//反序列化成员数据失败,有可能成员类型已改变
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool AddHashToRedis<T>(this IDatabase db, RedisKey key, T value, TimeSpan expire) {
|
||||
if (value == null) {
|
||||
throw new ArgumentNullException("value is null!");
|
||||
}
|
||||
var type = value.GetType();
|
||||
//为了保持缓存对象强类型特性,将泛型类型一并写入,以便取出时检查
|
||||
var entrys = new Collection<HashEntry>();
|
||||
entrys.Add(new HashEntry(hash_type_field_name, type.AssemblyQualifiedName));
|
||||
var dictionary = value as IDictionary;
|
||||
if (dictionary != null) {
|
||||
if (dictionary.IsReadOnly) {
|
||||
throw new ArgumentOutOfRangeException("无法使用只读类型对象!");
|
||||
}
|
||||
//IDictionary 类型
|
||||
foreach (DictionaryEntry item in dictionary) {
|
||||
entrys.Add(new HashEntry(GetStringOfJsonWrapper(item.Key), GetStringOfJsonWrapper(item.Value)));
|
||||
}
|
||||
} else {
|
||||
//class 或 struct
|
||||
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.IsInitOnly).ToArray();
|
||||
var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0).ToArray();
|
||||
|
||||
if (fields.Length == 0 && props.Length == 0) {
|
||||
throw new ArgumentOutOfRangeException("Redis Hash 不支持简单类型和无成员类型, 必须有公开的可读写内部成员!");
|
||||
}
|
||||
foreach (var fieldInfo in fields) {
|
||||
var name = fieldInfo.Name;
|
||||
var fieldValue = fieldInfo.GetValue(value);
|
||||
entrys.Add(new HashEntry(name, GetStringOfJsonWrapper(fieldValue)));
|
||||
}
|
||||
foreach (var propInfo in props) {
|
||||
var name = propInfo.Name;
|
||||
var propValue = propInfo.GetValue(value);
|
||||
entrys.Add(new HashEntry(name, GetStringOfJsonWrapper(propValue)));
|
||||
}
|
||||
}
|
||||
return db.ExecuctRedisTransaction(key, expire, true, transaction => transaction.HashSetAsync(key, entrys.ToArray()));
|
||||
}
|
||||
|
||||
static Task<bool> AddHashToRedisAsync<T>(this IDatabase db, RedisKey key, T value, TimeSpan expire) {
|
||||
if (value == null) {
|
||||
throw new ArgumentNullException("value is null!");
|
||||
}
|
||||
var type = value.GetType();
|
||||
//为了保持缓存对象强类型特性,将泛型类型一并写入,以便取出时检查
|
||||
var entrys = new Collection<HashEntry>();
|
||||
entrys.Add(new HashEntry(hash_type_field_name, type.AssemblyQualifiedName));
|
||||
var dictionary = value as IDictionary;
|
||||
if (dictionary != null) {
|
||||
if (dictionary.IsReadOnly) {
|
||||
throw new ArgumentOutOfRangeException("无法使用只读类型对象!");
|
||||
}
|
||||
//IDictionary 类型
|
||||
foreach (DictionaryEntry item in dictionary) {
|
||||
entrys.Add(new HashEntry(GetStringOfJsonWrapper(item.Key), GetStringOfJsonWrapper(item.Value)));
|
||||
}
|
||||
} else {
|
||||
//class 或 struct
|
||||
var fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance).Where(p => !p.IsInitOnly).ToArray();
|
||||
var props = type.GetProperties(BindingFlags.Public | BindingFlags.Instance).Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0).ToArray();
|
||||
|
||||
if (fields.Length == 0 && props.Length == 0) {
|
||||
throw new ArgumentOutOfRangeException("Redis Hash 不支持简单类型和无成员类型, 必须有公开的可读写内部成员!");
|
||||
}
|
||||
foreach (var fieldInfo in fields) {
|
||||
var name = fieldInfo.Name;
|
||||
var fieldValue = fieldInfo.GetValue(value);
|
||||
entrys.Add(new HashEntry(name, GetStringOfJsonWrapper(fieldValue)));
|
||||
}
|
||||
foreach (var propInfo in props) {
|
||||
var name = propInfo.Name;
|
||||
var propValue = propInfo.GetValue(value);
|
||||
entrys.Add(new HashEntry(name, GetStringOfJsonWrapper(propValue)));
|
||||
}
|
||||
}
|
||||
return db.ExecuctRedisTransactionAsync(key, expire, true, transaction => { transaction.HashSetAsync(key, entrys.ToArray()); return Task.FromResult(true); });
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 以 Redis List 类型存储
|
||||
static bool TryGetList<T>(this IDatabase db, RedisKey key, out T outValue, bool throwIfKeyTypeWrong) {
|
||||
outValue = default(T);
|
||||
|
||||
if (!db.GetFromRedis(key, throwIfKeyTypeWrong, p => p.ListRange(key), out var redisValues)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (redisValues.Length == 0) {
|
||||
return false;
|
||||
}
|
||||
//获取第一个元素
|
||||
var typeString = redisValues.First();
|
||||
if (typeString.IsNullOrEmpty) {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"无效的目标类型:typeString is empty");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
Type originType = null;
|
||||
try {
|
||||
//获取原始数据类型
|
||||
originType = Type.GetType(typeString);
|
||||
} catch (Exception ex) {
|
||||
Debug.Error($"TryGetList Type.GetType fail, type: {typeString}, ex: {ex}");
|
||||
}
|
||||
if (originType == null) {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"无法获取原始类型:{originType}");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
redisValues = redisValues.Skip(1).ToArray();
|
||||
|
||||
var targetType = typeof(T);
|
||||
if (!originType.Equals(targetType)) {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"无效的目标类型:原始类型:{originType.FullName}, 目标类型:{targetType.FullName}");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//检查原始类型与目标类型是否一致
|
||||
var listInterface = targetType.GetInterface(typeOfIListGeneric.Name);
|
||||
if (listInterface != null) {
|
||||
var genericArgs = listInterface.GenericTypeArguments[0];
|
||||
//如果目标类型是数组,先准备一个通用集合接收数组成员,
|
||||
var collectionType = targetType.IsArray ? typeOfCollectionGeneric.MakeGenericType(genericArgs) : targetType;
|
||||
//创建目标对象或接收集合
|
||||
var list = Activator.CreateInstance(collectionType);
|
||||
//创建泛型方法
|
||||
var method = TryGetListGenericMethodInfo.MakeGenericMethod(collectionType, genericArgs);
|
||||
//执行泛型方法
|
||||
var succ = (bool)method.Invoke(null, new object[] { list, redisValues });
|
||||
if (!succ) {
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"TryGetList 解释成员类型不未成功!");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
//处理目标类型或接收集合结果
|
||||
outValue = !targetType.IsArray ? (T)list : (T)ListToArrayMethodInfo.MakeGenericMethod(genericArgs).Invoke(null, new[] { list });
|
||||
return succ;
|
||||
} else {
|
||||
outValue = Activator.CreateInstance<T>();
|
||||
if (outValue is IList list) {
|
||||
return TryGetList(list, redisValues, throwIfKeyTypeWrong);
|
||||
}
|
||||
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"无效的目标类型:原始类型:{originType.FullName}, 目标类型:{targetType.FullName}, 目标类型必须实现 {typeOfIList.FullName} 或 {typeOfIListGeneric.FullName}");
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static MethodInfo ListToArrayMethodInfo { get; } = typeOfRedisCachingHelper.GetMethod(nameof(ListToArray), BindingFlags.Static | BindingFlags.NonPublic);
|
||||
static T[] ListToArray<T>(IList<T> list) {
|
||||
return list.ToArray();
|
||||
}
|
||||
|
||||
static MethodInfo TryGetListGenericMethodInfo { get; } = typeOfRedisCachingHelper.GetMethod(nameof(TryGetListGeneric), BindingFlags.Static | BindingFlags.NonPublic);
|
||||
|
||||
static bool TryGetListGeneric<TCollection, TElement>(TCollection list, RedisValue[] redisValues) where TCollection : IList<TElement> {
|
||||
var elementType = typeof(TElement);
|
||||
foreach (var redisValue in redisValues) {
|
||||
if (!redisValue.IsNullOrEmpty) {
|
||||
if (GetObjectFromJsonWrapper(redisValue, out var value, out var originelementType, false, false)) {
|
||||
if (elementType.IsAssignableFrom(originelementType) || (value == null && (elementType.IsClass || elementType.IsInterface))) {//反序列化成员数据失败,有可能成员类型已改变
|
||||
list.Add((TElement)value);
|
||||
continue;
|
||||
} else {
|
||||
Debug.Error($"StaticCachingHelper TryGetListGeneric fail, redisValue: {redisValue}, 元素类型不正确: 要求元素类型:{elementType}, 数据元素类型:{originelementType}");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool TryGetList(IList list, RedisValue[] redisValues, bool throwIfKeyTypeWrong) {
|
||||
foreach (var redisValue in redisValues) {
|
||||
if (GetObjectFromJsonWrapper(redisValue, out var value, throwIfKeyTypeWrong, throwIfKeyTypeWrong)) {
|
||||
list.Add(value);
|
||||
} else {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool AddListToRedis<T>(this IDatabase db, RedisKey key, T obj, TimeSpan expire) where T : IEnumerable {
|
||||
if (obj == null) {
|
||||
throw new ArgumentOutOfRangeException("list is null or not is IList or IList<> type!");
|
||||
}
|
||||
if (!(obj is IList list)) {
|
||||
throw new ArgumentOutOfRangeException("list is null or not is IList or IList<> type!");
|
||||
}
|
||||
var valueList = new Collection<RedisValue>();
|
||||
valueList.Add(list.GetType().AssemblyQualifiedName);
|
||||
foreach (var item in list) {
|
||||
valueList.Add(GetStringOfJsonWrapper(item));
|
||||
}
|
||||
return db.ExecuctRedisTransaction(key, expire, true, transaction => transaction.ListRightPushAsync(key, valueList.ToArray()));
|
||||
}
|
||||
|
||||
static Task<bool> AddListToRedisAsync<T>(this IDatabase db, RedisKey key, T obj, TimeSpan expire) where T : IEnumerable {
|
||||
if (obj == null) {
|
||||
throw new ArgumentOutOfRangeException("list is null or not is IList or IList<> type!");
|
||||
}
|
||||
if (!(obj is IList list)) {
|
||||
throw new ArgumentOutOfRangeException("list is null or not is IList or IList<> type!");
|
||||
}
|
||||
var valueList = new Collection<RedisValue>();
|
||||
valueList.Add(list.GetType().AssemblyQualifiedName);
|
||||
foreach (var item in list) {
|
||||
valueList.Add(GetStringOfJsonWrapper(item));
|
||||
}
|
||||
return db.ExecuctRedisTransactionAsync(key, expire, true, async transaction => (await transaction.ListRightPushAsync(key, valueList.ToArray())) > 0);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 以 Redis Set 类型存储
|
||||
|
||||
#endregion
|
||||
|
||||
#region JSON 数据包装
|
||||
public static string GetStringOfJsonWrapper(object value) {
|
||||
return JToken.FromObject(new { type = (value == null ? typeOfObject : value.GetType()).AssemblyQualifiedName, value }).ToString(Formatting.None);
|
||||
}
|
||||
|
||||
static bool GetObjectFromJsonWrapper(string jsonString, out object value, bool throwIfEmpty = true, bool throwIfJsonStringWrong = true) {
|
||||
if (GetObjectFromJsonWrapper(jsonString, out value, out var t, throwIfEmpty, throwIfJsonStringWrong)) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool GetObjectFromJsonWrapper<T>(string jsonString, out T value, bool throwIfKeyTypeWrong, bool throwIfEmpty, bool throwIfJsonStringWrong) {
|
||||
if (GetObjectFromJsonWrapper(jsonString, out var obj, out var originelementType, throwIfEmpty, throwIfJsonStringWrong)) {
|
||||
var targetType = typeof(T);
|
||||
if (targetType.IsAssignableFrom(originelementType)) {
|
||||
value = (T)obj;
|
||||
return true;
|
||||
} else if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"无效的目标类型:原始数据类型:{originelementType.FullName},目标类型:{targetType.FullName}");
|
||||
}
|
||||
}
|
||||
value = default(T);
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool GetObjectFromJsonWrapper(string jsonString, out object value, out Type type, bool throwIfEmpty, bool throwIfJsonStringWrong) {
|
||||
value = null;
|
||||
type = null;
|
||||
if (string.IsNullOrEmpty(jsonString)) {
|
||||
if (throwIfEmpty) {
|
||||
throw new ArgumentOutOfRangeException("GetObjectFromJsonWrapper jsonString is empty or null!");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
try {
|
||||
var json = JObject.Parse(jsonString);
|
||||
if (json.TryGetValue("type", out var jType) && json.TryGetValue("value", out var jvalue)) {
|
||||
type = Type.GetType(jType.ToObject<string>());
|
||||
if (type != null) {
|
||||
value = jvalue.ToObject(type);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Debug.Error("GetObjectFromJsonWrapper fail, ex: " + ex);
|
||||
}
|
||||
if (throwIfJsonStringWrong) {
|
||||
throw new ArgumentOutOfRangeException("GetObjectFromJsonWrapper jsonString: " + jsonString);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#region common
|
||||
static void EnsureKeyNotEmptyOrNULL(RedisKey key) {
|
||||
if (string.IsNullOrEmpty(key)) {
|
||||
throw new ArgumentOutOfRangeException("key is null or empty!");
|
||||
}
|
||||
}
|
||||
|
||||
static bool GetFromRedis<T>(this IDatabase db, RedisKey key, bool throwIfKeyTypeWrong, Func<IDatabase, T> acquire, out T value) {
|
||||
value = default(T);
|
||||
try {
|
||||
//获取List对象
|
||||
value = acquire(db);
|
||||
return true;
|
||||
} catch (RedisServerException rse) {
|
||||
Debug.Error($"StaticCachingHelper GetFromRedis fail, key: {key}, rse: {rse}");
|
||||
if (throwIfKeyTypeWrong) {
|
||||
throw new ArgumentOutOfRangeException($"redis key type wrong, key: {key}", rse);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
Debug.Error($"StaticCachingHelper GetFromRedis fail, key: {key}, ex: {ex}");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static bool ExecuctRedisTransaction(this IDatabase db, RedisKey key, TimeSpan expire, bool deleteKey, Action<ITransaction> action) {
|
||||
try {
|
||||
var transaction = db.CreateTransaction();
|
||||
if (deleteKey) {
|
||||
transaction.KeyDeleteAsync(key);
|
||||
}
|
||||
//为了保持缓存对象强类型特性,将泛型类型一并写入,以便取出时检查
|
||||
action.Invoke(transaction);
|
||||
if (expire > TimeSpan.Zero) {
|
||||
transaction.KeyExpireAsync(key, expire);
|
||||
}
|
||||
var succ = transaction.Execute();
|
||||
if (!succ) {
|
||||
Debug.Error($"StaticCachingHelper ExecuctRedisTransaction fail 1, key: {key}, expire: {expire}");
|
||||
}
|
||||
return succ;
|
||||
} catch (Exception ex) {
|
||||
Debug.Error($"StaticCachingHelper ExecuctRedisTransaction fail 2, key: {key}, expire: {expire}, ex: {ex}");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
static async Task<bool> ExecuctRedisTransactionAsync(this IDatabase db, RedisKey key, TimeSpan expire, bool deleteKey, Func<ITransaction, Task<bool>> action) {
|
||||
try {
|
||||
var transaction = db.CreateTransaction();
|
||||
|
||||
var deleteOldTask = deleteKey ? transaction.KeyDeleteAsync(key) : null;
|
||||
|
||||
//为了保持缓存对象强类型特性,将泛型类型一并写入,以便取出时检查
|
||||
var result = action.Invoke(transaction);
|
||||
var setExpireTask = (expire > TimeSpan.Zero) ? transaction.KeyExpireAsync(key, expire) : null;
|
||||
|
||||
var succ = transaction.Execute();
|
||||
if (!succ) {
|
||||
Debug.Error($"StaticCachingHelper ExecuctRedisTransaction fail 1, key: {key}, expire: {expire}");
|
||||
}
|
||||
|
||||
if (deleteOldTask != null) {
|
||||
await deleteOldTask;
|
||||
}
|
||||
|
||||
if (setExpireTask != null) {
|
||||
await setExpireTask;
|
||||
}
|
||||
return succ && await result;
|
||||
} catch (Exception ex) {
|
||||
Debug.Error($"StaticCachingHelper ExecuctRedisTransaction fail 2, key: {key}, expire: {expire}, ex: {ex}");
|
||||
}
|
||||
return false;
|
||||
}
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
614
GameDAL/db/Sql/ADOExtensions.cs
Normal file
614
GameDAL/db/Sql/ADOExtensions.cs
Normal file
@ -0,0 +1,614 @@
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections;
|
||||
using System.Reflection;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Data.SqlClient;
|
||||
using System.Threading.Tasks;
|
||||
using System.Collections.Concurrent;
|
||||
using MrWu.Debug;
|
||||
|
||||
/// <summary>
|
||||
/// ADOExtensions
|
||||
/// </summary>
|
||||
public static partial class ADOExtensions {
|
||||
|
||||
|
||||
static MethodInfo GetColumeValueMethod { get; }
|
||||
|
||||
|
||||
#region DataTable Extensions
|
||||
|
||||
/// <summary>
|
||||
/// TryGetValue from DataTable
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue"></typeparam>
|
||||
/// <param name="table"></param>
|
||||
/// <param name="columnName"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="rowNumber"></param>
|
||||
/// <returns></returns>
|
||||
public static bool TryGetValue<TValue>(this DataTable table, string columnName, out TValue value, int rowNumber = 0) {
|
||||
if (table.Rows.Count > rowNumber) {
|
||||
value = table.Rows[rowNumber].GetValue<TValue>(columnName);
|
||||
return true;
|
||||
}
|
||||
value = default(TValue);
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// GetValue from DataTable
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue"></typeparam>
|
||||
/// <param name="table"></param>
|
||||
/// <param name="columnName"></param>
|
||||
/// <param name="rowNumber"></param>
|
||||
/// <param name="defaultValue"></param>
|
||||
/// <returns></returns>
|
||||
public static TValue GetValue<TValue>(this DataTable table, string columnName, int rowNumber = 0, TValue defaultValue = default(TValue)) {
|
||||
return table.TryGetValue<TValue>(columnName, out var outValue, rowNumber) ? outValue : defaultValue;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Select
|
||||
/// </summary>
|
||||
/// <typeparam name="TObject"></typeparam>
|
||||
/// <param name="table"></param>
|
||||
/// <param name="selector"></param>
|
||||
/// <returns></returns>
|
||||
public static IEnumerable<TObject> Select<TObject>(this DataTable table, Func<DataRow, TObject> selector) {
|
||||
foreach (DataRow row in table.Rows) {
|
||||
yield return selector.Invoke(row);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ToObjects
|
||||
/// </summary>
|
||||
/// <typeparam name="TObject"></typeparam>
|
||||
/// <param name="table"></param>
|
||||
/// <returns></returns>
|
||||
public static IEnumerable<TObject> ToObjects<TObject>(this DataTable table) where TObject : new() {
|
||||
foreach (DataRow row in table.Rows) {
|
||||
yield return row.ToObject<TObject>();
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region DataRow Extensions
|
||||
|
||||
#region 泛型方法
|
||||
|
||||
#region 单列解析方法
|
||||
|
||||
/// <summary>
|
||||
/// GetValue
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue"></typeparam>
|
||||
/// <param name="row">DataRow</param>
|
||||
/// <param name="column">DataColumn</param>
|
||||
/// <returns></returns>
|
||||
public static TValue GetColumeValue<TValue>(this DataRow row, DataColumn column) {
|
||||
var columnValue = row[column];
|
||||
if (columnValue is TValue value) {
|
||||
return value;
|
||||
}
|
||||
if (columnValue is DBNull && column.AllowDBNull) {
|
||||
return default(TValue);
|
||||
}
|
||||
throw new ArgumentOutOfRangeException($"无效的泛型类型,列名:{column.ColumnName},泛型类型为:{typeof(TValue)},数据列类型为:{GetColumnDataType(column)}");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// GetValue from DataRow
|
||||
/// </summary>
|
||||
/// <typeparam name="TValue"></typeparam>
|
||||
/// <param name="row"></param>
|
||||
/// <param name="columnName"></param>
|
||||
/// <returns></returns>
|
||||
public static TValue GetValue<TValue>(this DataRow row, string columnName) {
|
||||
if (row.TryGetColumn(columnName, out var column)) {
|
||||
return row.GetColumeValue<TValue>(column);
|
||||
}
|
||||
throw new ArgumentOutOfRangeException("未找到字段:" + columnName);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 整行解析方法
|
||||
|
||||
static ConcurrentDictionary<Type, ICollection<MemberInfo>> memberInfoOfType = new ConcurrentDictionary<Type, ICollection<MemberInfo>>();
|
||||
|
||||
/// <summary>
|
||||
/// ToObject from DataRow
|
||||
/// </summary>
|
||||
/// <typeparam name="TObject"></typeparam>
|
||||
/// <param name="row"></param>
|
||||
/// <returns></returns>
|
||||
public static TObject ToObject<TObject>(this DataRow row) where TObject : new() {
|
||||
var type = typeof(TObject);
|
||||
var objectMembers = memberInfoOfType.GetOrAdd(type, t => {
|
||||
var collection = new Collection<MemberInfo>();
|
||||
foreach (var item in type.GetProperties().Where(p => p.CanRead && p.CanWrite && p.GetIndexParameters().Length == 0)) {
|
||||
collection.Add(item);
|
||||
}
|
||||
foreach (var item in type.GetFields().Where(p => !p.IsInitOnly && p.IsPublic)) {
|
||||
collection.Add(item);
|
||||
}
|
||||
return collection;
|
||||
});
|
||||
var obj = new TObject();
|
||||
foreach (var item in objectMembers) {
|
||||
if (item is FieldInfo fieldInfo) {
|
||||
row.TrySetMemberValue(obj, fieldInfo.Name, fieldInfo.FieldType, fieldInfo.SetValue);
|
||||
} else if (item is PropertyInfo propertyInfo) {
|
||||
row.TrySetMemberValue(obj, propertyInfo.Name, propertyInfo.PropertyType, propertyInfo.SetValue);
|
||||
}
|
||||
}
|
||||
return obj;
|
||||
}
|
||||
|
||||
static void TrySetMemberValue(this DataRow row, object parent, string memberName, Type memberType, Action<object, object> valueSetMethod) {
|
||||
var column = row.Table.Columns[memberName];
|
||||
if (column != null) {
|
||||
var value = row[column];
|
||||
try {
|
||||
if (value != null && !(value is DBNull)) {
|
||||
var sourceType = value.GetType();
|
||||
if (memberType.IsEnum) {
|
||||
value = Enum.ToObject(memberType, value);
|
||||
} else if (memberType.IsGenericType && memberType.GetGenericTypeDefinition() == typeof(Nullable<>)) {
|
||||
//目标类型为 Nullable<>,无需转换,可直接赋值
|
||||
} else if (!sourceType.IsAssignableFrom(memberType) && value is IConvertible convert) {
|
||||
value = convert.ToType(memberType, null);
|
||||
}
|
||||
valueSetMethod.Invoke(parent, value);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
throw new ArgumentException($"TrySetMemberValue 数据类型定义错误, 定义类型与数据库类型不一致, 成员名:{memberName}, 当前泛型参数类型为: {memberType}, 实际数据类型:{ GetColumnDataType(row.Table.Columns[memberName])}, data: {value}", ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ToDictionary from DataRow
|
||||
/// </summary>
|
||||
/// <param name="row"></param>
|
||||
/// <returns></returns>
|
||||
public static IDictionary<string, object> ToDictionary(this DataRow row) {
|
||||
var columns = row.Table.Columns;
|
||||
var dict = new Dictionary<string, object>();
|
||||
foreach (DataColumn column in columns) {
|
||||
var value = row.GetValue(column);
|
||||
dict.Add(column.ColumnName, value);
|
||||
}
|
||||
return dict;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
#region 非泛型方法
|
||||
|
||||
/// <summary>
|
||||
/// TryGetValue
|
||||
/// </summary>
|
||||
/// <param name="row"></param>
|
||||
/// <param name="columnName"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <returns></returns>
|
||||
public static bool TryGetValue(this DataRow row, string columnName, out object value) {
|
||||
if (row.TryGetColumn(columnName, out var column)) {
|
||||
value = row.GetValue(column);
|
||||
return true;
|
||||
}
|
||||
value = null;
|
||||
return false;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="row"></param>
|
||||
/// <param name="column"></param>
|
||||
/// <returns></returns>
|
||||
public static object GetValue(this DataRow row, DataColumn column) {
|
||||
var columnType = GetColumnDataType(column);
|
||||
var value = row[column];
|
||||
return value is DBNull ? null : value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="column"></param>
|
||||
/// <returns></returns>
|
||||
public static Type GetColumnDataType(this DataColumn column) => column.AllowDBNull && column.DataType.IsValueType ? typeof(Nullable<>).MakeGenericType(column.DataType) : column.DataType;
|
||||
|
||||
/// <summary>
|
||||
/// TryGetColumn from DataRow
|
||||
/// </summary>
|
||||
/// <param name="row"></param>
|
||||
/// <param name="columnName"></param>
|
||||
/// <param name="column"></param>
|
||||
/// <returns></returns>
|
||||
public static bool TryGetColumn(this DataRow row, string columnName, out DataColumn column) {
|
||||
column = row.Table.Columns[columnName];
|
||||
return column != null;
|
||||
}
|
||||
|
||||
internal static int SQLValue(this bool value) => value ? 1 : 0;
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
#region SQL命令扩展
|
||||
|
||||
#region 构造与内部成员
|
||||
|
||||
private static string connectionString { get; }
|
||||
|
||||
|
||||
#endregion
|
||||
|
||||
#region 单结果集查询
|
||||
|
||||
public static DataTable ExecuteTable(this dbbase db, string sqlText, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, cmd => cmd.FillTable(), parameters);
|
||||
}
|
||||
|
||||
public static DataTable ExecuteTable(this dbbase db, string sqlText, CommandType type, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, cmd => cmd.FillTable(), type, parameters);
|
||||
}
|
||||
|
||||
public static Task<DataTable> ExecuteTableAsync(this dbbase db, string sqlText, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, async cmd => await cmd.FillTableAsync(), parameters);
|
||||
}
|
||||
|
||||
public static Task<DataTable> ExecuteTableAsync(this dbbase db, string sqlText, CommandType type, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, async cmd => await cmd.FillTableAsync(), type, parameters);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 多结果集查询
|
||||
|
||||
public static DataTable[] ExecuteTables(this dbbase db, string sqlText, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, cmd => cmd.FillTables(), parameters);
|
||||
}
|
||||
|
||||
public static DataTable[] ExecuteTables(this dbbase db, string sqlText, CommandType type, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, cmd => cmd.FillTables(), type, parameters);
|
||||
}
|
||||
|
||||
public static Task<DataTable[]> ExecuteTablesAsync(this dbbase db, string sqlText, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, async cmd => await cmd.FillTablesAsync(), parameters);
|
||||
}
|
||||
|
||||
public static Task<DataTable[]> ExecuteTablesAsync(this dbbase db, string sqlText, CommandType type, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, async cmd => await cmd.FillTablesAsync(), type, parameters);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
#region 执行无结果集SQL
|
||||
|
||||
public static int ExecuteNonQuery(this dbbase db, string sqlText, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, cmd => cmd.ExecuteNonQuery(), parameters);
|
||||
}
|
||||
|
||||
public static int ExecuteNonQuery(this dbbase db, string sqlText, CommandType type, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, cmd => cmd.ExecuteNonQuery(), type, parameters);
|
||||
}
|
||||
|
||||
public static Task<int> ExecuteNonQueryAsync(this dbbase db, string sqlText, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, cmd => cmd.ExecuteNonQueryAsync(), parameters);
|
||||
}
|
||||
|
||||
public static Task<int> ExecuteNonQueryAsync(this dbbase db, string sqlText, CommandType type, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, cmd => cmd.ExecuteNonQueryAsync(), type, parameters);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 执行首行首列查询
|
||||
|
||||
public static object ExecuteScalar(this dbbase db, string sqlText, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, cmd => cmd.ExecuteScalar(), parameters);
|
||||
}
|
||||
|
||||
public static object ExecuteScalar(this dbbase db, string sqlText, CommandType type, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, cmd => cmd.ExecuteScalar(), type, parameters);
|
||||
}
|
||||
|
||||
public static Task<object> ExecuteScalarAsync(this dbbase db, string sqlText, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, cmd => cmd.ExecuteScalarAsync(), parameters);
|
||||
}
|
||||
|
||||
public static Task<object> ExecuteScalarAsync(this dbbase db, string sqlText, CommandType type, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, cmd => cmd.ExecuteScalarAsync(), type, parameters);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 泛型方法
|
||||
|
||||
#region 单表实体集查询
|
||||
|
||||
public static IEnumerable<TResult> ExecuteEntities<TResult>(this dbbase db, string sqlText, Func<DataRow, TResult> resultSelector, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, cmd => cmd.FillTable().Select(p => resultSelector.Invoke(p)), parameters);
|
||||
}
|
||||
|
||||
public static IEnumerable<TResult> ExecuteEntities<TResult>(this dbbase db, string sqlText, Func<DataRow, TResult> resultSelector, CommandType type, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, cmd => cmd.FillTable().Select(p => resultSelector.Invoke(p)), type, parameters);
|
||||
}
|
||||
|
||||
public static Task<IEnumerable<TResult>> ExecuteEntitiesAsync<TResult>(this dbbase db, string sqlText, Func<DataRow, TResult> resultSelector, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, async cmd => (await cmd.FillTableAsync()).Select(p => resultSelector.Invoke(p)), parameters);
|
||||
}
|
||||
|
||||
public static Task<IEnumerable<TResult>> ExecuteEntitiesAsync<TResult>(this dbbase db, string sqlText, Func<DataRow, TResult> resultSelector, CommandType type, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, async cmd => (await cmd.FillTableAsync()).Select(p => resultSelector.Invoke(p)), type, parameters);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 多表实体集查询
|
||||
|
||||
public static TResult ExecuteEntities2<TResult>(this dbbase db, string sqlText, Func<DataTable[], TResult> resultSelector, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, cmd => resultSelector.Invoke(cmd.FillTables()), parameters);
|
||||
}
|
||||
|
||||
public static TResult ExecuteEntities2<TResult>(this dbbase db, string sqlText, Func<DataTable[], TResult> resultSelector, CommandType type, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, cmd => resultSelector.Invoke(cmd.FillTables()), type, parameters);
|
||||
}
|
||||
|
||||
public static Task<TResult> ExecuteEntities2Async<TResult>(this dbbase db, string sqlText, Func<DataTable[], TResult> resultSelector, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, async cmd => resultSelector.Invoke(await cmd.FillTablesAsync()), parameters);
|
||||
}
|
||||
|
||||
public static Task<TResult> ExecuteEntities2Async<TResult>(this dbbase db, string sqlText, Func<DataTable[], TResult> resultSelector, CommandType type, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, async cmd => resultSelector.Invoke(await cmd.FillTablesAsync()), type, parameters);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region
|
||||
|
||||
public static TResult ExecuteCommand<TResult>(this dbbase db, string sqlText, Func<SqlCommand, TResult> resultSelector, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommand(sqlText, resultSelector, CommandType.Text, parameters);
|
||||
}
|
||||
|
||||
public static TResult ExecuteCommand<TResult>(this dbbase db, string sqlText, Func<SqlCommand, TResult> resultSelector, CommandType type, params SqlParameter[] parameters) {
|
||||
using (SqlConnection conn = new SqlConnection(connectionString)) {
|
||||
conn.Open();
|
||||
conn.ChangeDatabase(GetDataBaseName(db));
|
||||
using (var cmd = conn.CreateCommand()) {
|
||||
cmd.CommandText = sqlText;
|
||||
cmd.CommandType = type;
|
||||
if (parameters != null && parameters.Length > 0) {
|
||||
cmd.Parameters.AddRange(parameters);
|
||||
}
|
||||
return resultSelector.Invoke(cmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static Task<TResult> ExecuteCommandAsync<TResult>(this dbbase db, string sqlText, Func<SqlCommand, Task<TResult>> resultSelector, params SqlParameter[] parameters) {
|
||||
return db.ExecuteCommandAsync(sqlText, resultSelector, CommandType.Text, parameters);
|
||||
}
|
||||
|
||||
public static async Task<TResult> ExecuteCommandAsync<TResult>(this dbbase db, string sqlText, Func<SqlCommand, Task<TResult>> resultSelector, CommandType type, params SqlParameter[] parameters) {
|
||||
using (SqlConnection conn = new SqlConnection(connectionString)) {
|
||||
await conn.OpenAsync();
|
||||
conn.ChangeDatabase(GetDataBaseName(db));
|
||||
using (var cmd = conn.CreateCommand()) {
|
||||
cmd.CommandText = sqlText;
|
||||
cmd.CommandType = type;
|
||||
if (parameters != null && parameters.Length > 0) {
|
||||
cmd.Parameters.AddRange(parameters);
|
||||
}
|
||||
return await resultSelector.Invoke(cmd);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
|
||||
#region 事务
|
||||
|
||||
public static TResult ExecuteTransaction<TResult>(this dbbase db, Func<SqlTransaction, TResult> transactionAction) {
|
||||
return db.ExecuteTransaction(true, transactionAction);
|
||||
}
|
||||
|
||||
public static TResult ExecuteTransaction<TResult>(this dbbase db, bool throwIfException, Func<SqlTransaction, TResult> transactionAction) {
|
||||
var result = default(TResult);
|
||||
using (var conn = new SqlConnection(connectionString)) {
|
||||
conn.Open();
|
||||
conn.ChangeDatabase(GetDataBaseName(db));
|
||||
using (var transaction = conn.BeginTransaction()) {
|
||||
try {
|
||||
result = transactionAction.Invoke(transaction);
|
||||
transaction.Commit();
|
||||
} catch (Exception ex) {
|
||||
Debug.Error("ExecuteTransaction " + ex);
|
||||
transaction.SafeRollback();
|
||||
if (throwIfException) {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static Task<TResult> ExecuteTransactionAsync<TResult>(this dbbase db, Func<SqlTransaction, Task<TResult>> transactionAction) {
|
||||
return db.ExecuteTransactionAsync(true, transactionAction);
|
||||
}
|
||||
|
||||
public static async Task<TResult> ExecuteTransactionAsync<TResult>(this dbbase db, bool throwIfException, Func<SqlTransaction, Task<TResult>> transactionAction) {
|
||||
var result = default(TResult);
|
||||
using (var conn = new SqlConnection(connectionString)) {
|
||||
await conn.OpenAsync();
|
||||
conn.ChangeDatabase(GetDataBaseName(db));
|
||||
using (var transaction = conn.BeginTransaction()) {
|
||||
try {
|
||||
result = await transactionAction.Invoke(transaction);
|
||||
transaction.Commit();
|
||||
} catch (Exception ex) {
|
||||
Debug.Error("ExecuteTransaction " + ex);
|
||||
transaction.SafeRollback();
|
||||
if (throwIfException) {
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="transaction"></param>
|
||||
/// <param name="sqlText"></param>
|
||||
/// <param name="parameters"></param>
|
||||
/// <returns></returns>
|
||||
public static TResult ExecuteQuery<TResult>(this SqlTransaction transaction, string sqlText, Func<SqlCommand, TResult> resultSelector, params SqlParameter[] parameters) {
|
||||
return transaction.ExecuteQuery(sqlText, resultSelector, CommandType.Text, parameters);
|
||||
}
|
||||
|
||||
public static TResult ExecuteQuery<TResult>(this SqlTransaction transaction, string sqlText, Func<SqlCommand, TResult> resultSelector, CommandType type, params SqlParameter[] parameters) {
|
||||
using (var cmd = new SqlCommand(sqlText, transaction.Connection, transaction) { CommandType = type }) {
|
||||
if (parameters != null && parameters.Length > 0) {
|
||||
cmd.Parameters.AddRange(parameters);
|
||||
}
|
||||
var result = resultSelector.Invoke(cmd);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
public static int ExecuteNonQuery(this SqlTransaction transaction, string sqlText, params SqlParameter[] parameters) {
|
||||
return transaction.ExecuteNonQuery(sqlText, CommandType.Text, parameters);
|
||||
}
|
||||
|
||||
public static int ExecuteNonQuery(this SqlTransaction transaction, string sqlText, CommandType type, params SqlParameter[] parameters) {
|
||||
return transaction.ExecuteQuery(sqlText, cmd => cmd.ExecuteNonQuery(), type, parameters);
|
||||
}
|
||||
|
||||
public static Task<int> ExecuteNonQueryAsync(this SqlTransaction transaction, string sqlText, params SqlParameter[] parameters) {
|
||||
return transaction.ExecuteNonQueryAsync(sqlText, CommandType.Text, parameters);
|
||||
}
|
||||
|
||||
public static Task<int> ExecuteNonQueryAsync(this SqlTransaction transaction, string sqlText, CommandType type, params SqlParameter[] parameters) {
|
||||
return transaction.ExecuteQuery(sqlText, cmd => cmd.ExecuteNonQueryAsync(), type, parameters);
|
||||
}
|
||||
|
||||
public static object ExecuteScalar(this SqlTransaction transaction, string sqlText, params SqlParameter[] parameters) {
|
||||
return transaction.ExecuteScalar(sqlText, CommandType.Text, parameters);
|
||||
}
|
||||
|
||||
public static object ExecuteScalar(this SqlTransaction transaction, string sqlText, CommandType type, params SqlParameter[] parameters) {
|
||||
return transaction.ExecuteQuery(sqlText, cmd => cmd.ExecuteScalar(), type, parameters);
|
||||
}
|
||||
|
||||
public static Task<object> ExecuteScalarAsync(this SqlTransaction transaction, string sqlText, params SqlParameter[] parameters) {
|
||||
return transaction.ExecuteScalarAsync(sqlText, CommandType.Text, parameters);
|
||||
}
|
||||
|
||||
public static Task<object> ExecuteScalarAsync(this SqlTransaction transaction, string sqlText, CommandType type, params SqlParameter[] parameters) {
|
||||
return transaction.ExecuteQuery(sqlText, cmd => cmd.ExecuteScalarAsync(), type, parameters);
|
||||
}
|
||||
|
||||
public static void SafeRollback(this SqlTransaction transaction) {
|
||||
try {
|
||||
transaction.Rollback();
|
||||
} catch (Exception ex) {
|
||||
Debug.Error("SafeRollback:" + ex);
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Common
|
||||
|
||||
private static string GetDataBaseName(dbbase db) {
|
||||
switch (db) {
|
||||
case dbbase.gamedb:
|
||||
return "jnxdgame";
|
||||
case dbbase.game2018:
|
||||
return "game2018";
|
||||
default:
|
||||
throw new NotSupportedException(nameof(db));
|
||||
}
|
||||
}
|
||||
|
||||
public static DataTable FillTable(this SqlCommand cmd) {
|
||||
return cmd.FillTables().FirstOrDefault() ?? new DataTable();
|
||||
}
|
||||
|
||||
public static DataTable[] FillTables(this SqlCommand cmd) {
|
||||
using (var adapter = new SqlDataAdapter(cmd)) {
|
||||
using (var dataSet = new DataSet()) {
|
||||
adapter.Fill(dataSet);
|
||||
var tabs = new DataTable[dataSet.Tables.Count];
|
||||
for (int i = 0; i < dataSet.Tables.Count; i++) {
|
||||
tabs[i] = dataSet.Tables[i];
|
||||
}
|
||||
return tabs;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<DataTable> FillTableAsync(this SqlCommand cmd) {
|
||||
using (var reader = await cmd.ExecuteReaderAsync()) {
|
||||
return await reader.FillTableInternal();
|
||||
}
|
||||
}
|
||||
|
||||
public static async Task<DataTable[]> FillTablesAsync(this SqlCommand cmd) {
|
||||
using (var reader = await cmd.ExecuteReaderAsync()) {
|
||||
var tables = new Collection<DataTable>();
|
||||
do {
|
||||
var datatable = await reader.FillTableInternal();
|
||||
if (datatable != null) {
|
||||
tables.Add(datatable);
|
||||
}
|
||||
} while (await reader.NextResultAsync());
|
||||
return tables.ToArray();
|
||||
}
|
||||
}
|
||||
|
||||
static async Task<DataTable> FillTableInternal(this SqlDataReader reader) {
|
||||
var datatable = new DataTable();
|
||||
if (reader.FieldCount > 0) {
|
||||
datatable.Columns.AddRange(Enumerable.Range(0, reader.FieldCount)
|
||||
.Select(i => new DataColumn(reader.GetName(i), reader.GetFieldType(i)))
|
||||
.ToArray());
|
||||
|
||||
///添加行数据
|
||||
while (await reader.ReadAsync()) {
|
||||
var myDataRow = datatable.NewRow();
|
||||
for (int i = 0; i < reader.FieldCount; i++) {
|
||||
myDataRow[i] = reader[i];
|
||||
}
|
||||
datatable.Rows.Add(myDataRow);
|
||||
}
|
||||
}
|
||||
return datatable;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#endregion
|
||||
}
|
||||
24
GameDAL/db/Sql/ADOExtensions_Initize.cs
Normal file
24
GameDAL/db/Sql/ADOExtensions_Initize.cs
Normal file
@ -0,0 +1,24 @@
|
||||
using System.Data;
|
||||
using System.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections;
|
||||
using System.Reflection;
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Data.SqlClient;
|
||||
using System.Threading.Tasks;
|
||||
using MrWu.DB;
|
||||
using Server.DB.Sql;
|
||||
|
||||
/// <summary>
|
||||
/// ADOExtensions
|
||||
/// </summary>
|
||||
public static partial class ADOExtensions {
|
||||
|
||||
static ADOExtensions() {
|
||||
GetColumeValueMethod = typeof(ADOExtensions).GetMethod(nameof(GetColumeValue), BindingFlags.Static | BindingFlags.Public);
|
||||
var field = GameDB.Instance.GetType().GetField("mmsql", BindingFlags.Instance | BindingFlags.NonPublic);
|
||||
var mmsql = field.GetValue(GameDB.Instance) as MMSSQL;
|
||||
connectionString = mmsql.connectionString;
|
||||
}
|
||||
}
|
||||
196
GameDAL/db/Sql/DbSearchField.cs
Normal file
196
GameDAL/db/Sql/DbSearchField.cs
Normal file
@ -0,0 +1,196 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Reflection;
|
||||
using DBEntitys;
|
||||
using GameMessage;
|
||||
|
||||
namespace Server.DB.Sql
|
||||
{
|
||||
public class DbSearchField<T>
|
||||
{
|
||||
public Dictionary<string, object> Fields => _fields;
|
||||
|
||||
private readonly Dictionary<string, object> _fields;
|
||||
private readonly List<PropertyInfo> _properties;
|
||||
|
||||
public DbSearchField(Dictionary<string, object> fields)
|
||||
{
|
||||
_fields = new Dictionary<string, object>(fields);
|
||||
_properties = new List<PropertyInfo>(typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance));
|
||||
}
|
||||
|
||||
public void Remove(string key)
|
||||
{
|
||||
_fields.Remove(key);
|
||||
}
|
||||
|
||||
public bool Contains(string key)
|
||||
{
|
||||
return _fields.ContainsKey(key);
|
||||
}
|
||||
|
||||
public int GetInt(string key)
|
||||
{
|
||||
if (!Contains(key)) return 0;
|
||||
int.TryParse(_fields[key].ToString(), out int value);
|
||||
return value;
|
||||
}
|
||||
|
||||
public bool GetBool(string key)
|
||||
{
|
||||
if (!Contains(key)) return false;
|
||||
bool.TryParse(_fields[key].ToString(), out bool value);
|
||||
return value;
|
||||
}
|
||||
|
||||
public string GetString(string key)
|
||||
{
|
||||
if (!Contains(key)) return string.Empty;
|
||||
var value = _fields[key].ToString();
|
||||
return value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 根据属性注解自动构建SQL条件到SqlBuilder
|
||||
/// </summary>
|
||||
public void BuildWhereConditions(SqlBuilder sb)
|
||||
{
|
||||
foreach (var prop in _properties)
|
||||
{
|
||||
// 检查是否忽略
|
||||
if (prop.GetCustomAttribute<QueryIgnoreAttribute>() != null)
|
||||
continue;
|
||||
|
||||
var propName = prop.Name;
|
||||
string searchName = propName;
|
||||
|
||||
// 检查 FieldNameAttribute 别称
|
||||
var fieldNameAttr = prop.GetCustomAttribute<DBFieldNameAttribute>();
|
||||
if (fieldNameAttr != null && !string.IsNullOrEmpty(fieldNameAttr.FieldName))
|
||||
{
|
||||
searchName = fieldNameAttr.FieldName;
|
||||
}
|
||||
|
||||
if (!Contains(searchName))
|
||||
continue;
|
||||
|
||||
var value = _fields[searchName];
|
||||
if (value == null)
|
||||
continue;
|
||||
|
||||
// 检查注解类型并应用对应的查询方式
|
||||
var dateRangeAttr = prop.GetCustomAttribute<DateRangeFieldAttribute>();
|
||||
if (dateRangeAttr != null)
|
||||
{
|
||||
var dateRange = dateRangeAttr.IsDateRange ? GetDateRange(searchName) : GetDefaultDate(searchName);
|
||||
sb.WhereBetween(propName, dateRange.Start, dateRange.End);
|
||||
}
|
||||
else if (prop.GetCustomAttribute<LikeFieldAttribute>() != null)
|
||||
{
|
||||
sb.WhereLike(propName, value.ToString());
|
||||
}
|
||||
else if (prop.GetCustomAttribute<InFieldAttribute>() != null)
|
||||
{
|
||||
var attr = prop.GetCustomAttribute<InFieldAttribute>();
|
||||
var values = value.ToString().Split(attr.Separator).ToList();
|
||||
sb.WhereIn(propName, values);
|
||||
}
|
||||
else
|
||||
{
|
||||
// 默认使用等于查询
|
||||
sb.WhereEqual(propName, value);
|
||||
}
|
||||
|
||||
Remove(searchName);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取实体字段(不包含特殊处理的字段,如分页参数)
|
||||
/// </summary>
|
||||
public Dictionary<string, object> GetEntityFields()
|
||||
{
|
||||
Dictionary<string, object> fields = new Dictionary<string, object>();
|
||||
foreach (var prop in _properties)
|
||||
{
|
||||
var propName = prop.Name;
|
||||
// 检查 FieldNameAttribute 别称
|
||||
var fieldNameAttr = prop.GetCustomAttribute<DBFieldNameAttribute>();
|
||||
if (fieldNameAttr != null && !string.IsNullOrEmpty(fieldNameAttr.FieldName))
|
||||
{
|
||||
if (Contains(fieldNameAttr.FieldName))
|
||||
{
|
||||
fields[propName] = _fields[fieldNameAttr.FieldName];
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
if (Contains(propName))
|
||||
{
|
||||
fields[propName] = _fields[propName];
|
||||
}
|
||||
}
|
||||
return fields;
|
||||
}
|
||||
|
||||
#region 前端约定好的通用参数字段
|
||||
|
||||
public (DateTime Start, DateTime End) GetDefaultDate(string key)
|
||||
{
|
||||
if (!Contains(key))
|
||||
return (DateTime.Now, DateTime.Now);
|
||||
var value = GetString(key);
|
||||
var startDate = DateTime.Parse(value);
|
||||
var endDate = DateTime.Parse(value);
|
||||
if (endDate == startDate)
|
||||
{
|
||||
endDate = endDate.AddDays(1).AddSeconds(-1);
|
||||
}
|
||||
|
||||
return (startDate, endDate);
|
||||
}
|
||||
|
||||
public (DateTime Start, DateTime End) GetDateRange(string key)
|
||||
{
|
||||
if (!Contains(key))
|
||||
return (DateTime.Now, DateTime.Now);
|
||||
|
||||
var ranges = GetString(key).Split(',');
|
||||
var startDate = DateTime.Parse(ranges[0]);
|
||||
var endDate = DateTime.Parse(ranges[1]);
|
||||
if (endDate == startDate)
|
||||
{
|
||||
endDate = endDate.AddDays(1).AddSeconds(-1);
|
||||
}
|
||||
|
||||
return (startDate, endDate);
|
||||
}
|
||||
|
||||
public DataPage GetPage()
|
||||
{
|
||||
return new DataPage()
|
||||
{
|
||||
PageId = GetPageIndex(),
|
||||
PageSize = GetPageSize()
|
||||
};
|
||||
}
|
||||
|
||||
public int GetPageIndex()
|
||||
{
|
||||
if (!Contains("pageIndex"))
|
||||
return 1;
|
||||
|
||||
return GetInt("pageIndex");
|
||||
}
|
||||
|
||||
public int GetPageSize()
|
||||
{
|
||||
if (!Contains("pageSize"))
|
||||
return 10;
|
||||
return GetInt("pageSize");
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
334
GameDAL/db/Sql/GameDB.cs
Normal file
334
GameDAL/db/Sql/GameDB.cs
Normal file
@ -0,0 +1,334 @@
|
||||
/*
|
||||
* 由SharpDevelop创建。
|
||||
* 用户: Administrator
|
||||
* 日期: 2018-05-05
|
||||
* 时间: 13:23
|
||||
*
|
||||
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
|
||||
*/
|
||||
using System;
|
||||
using System.Data;
|
||||
using System.Data.SqlClient;
|
||||
using MrWu.DB;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using Dapper;
|
||||
using MrWu.Debug;
|
||||
using ObjectModel.Game;
|
||||
|
||||
namespace Server.DB.Sql {
|
||||
|
||||
/// <summary>
|
||||
/// 游戏数据库访问
|
||||
/// </summary>
|
||||
public class GameDB {
|
||||
static GameDB() {
|
||||
m_Instance = new GameDB();
|
||||
}
|
||||
|
||||
private GameDB() { }
|
||||
|
||||
private static GameDB m_Instance;
|
||||
|
||||
/// <summary>
|
||||
/// 数据库实例
|
||||
/// </summary>
|
||||
public static GameDB Instance {
|
||||
get {
|
||||
return m_Instance;
|
||||
}
|
||||
}
|
||||
|
||||
private ISqlEx<SqlConnection, SqlCommand, SqlDbType,SqlParameter> mmsql;
|
||||
|
||||
private string GetDataBaseName(dbbase db) {
|
||||
switch (db) {
|
||||
case dbbase.gamedb:
|
||||
return "jnxdgame";
|
||||
case dbbase.game2018:
|
||||
return "game2018";
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 初始化
|
||||
/// </summary>
|
||||
public void Init(MrWu.DB.SqlConfig config) {
|
||||
if (mmsql == null)
|
||||
mmsql = new MMSSQL(config);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查询数据库
|
||||
/// </summary>
|
||||
/// <param name="sty">数据库类型</param>
|
||||
/// <param name="db">数据库</param>
|
||||
/// <param name="table">查那个表</param>
|
||||
/// <param name="column">需要查询的列</param>
|
||||
/// <param name="whereStr">条件</param>
|
||||
/// <returns></returns>
|
||||
public DataTable selectDb(dbbase db, string table, string[] column = null, string whereStr = null, int count = -1, params SqlParameter[] sqlparams) {
|
||||
return mmsql.Select(GetDataBaseName(db), table, column, whereStr, count, -1, sqlparams.Length > 0 ? new List<SqlParameter>(sqlparams) : null);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开始设置存储过程参数
|
||||
/// </summary>
|
||||
public IProdureParameter<SqlCommand> BeginSetProcedureParameter(dbbase db, string procedureName) {
|
||||
return mmsql.BeginProcedure(GetDataBaseName(db), procedureName);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加存储过程参数
|
||||
/// </summary>
|
||||
public void AddProdureParameters(IProdureParameter<SqlCommand> spp, string parameName, SqlDbType type, object value, ParameterDirection pd = ParameterDirection.Input) {
|
||||
|
||||
SqlParameter sp = spp.command.Parameters.Add(parameName, type);
|
||||
sp.Direction = pd;
|
||||
if (value == null)
|
||||
sp.Value = DBNull.Value;
|
||||
else
|
||||
sp.Value = value;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 执行sql语句
|
||||
/// </summary>
|
||||
/// <param name="db">数据库</param>
|
||||
/// <param name="sql">sql语句</param>
|
||||
/// <param name="ds">获得的数据</param>
|
||||
public int ExceSql(dbbase db, string sql, IEnumerable<SqlParameter> sqlparams = null, DataSet ds = null) {
|
||||
return mmsql.ExecuteSql(GetDataBaseName(db), sql, sqlparams, ds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 结束执行存储过程
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public Dictionary<string, object> EndAddProdureParameters(IProdureParameter<SqlCommand> spp, DataSet ds = null) {
|
||||
return mmsql.SubProcedure(spp, ds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 开启一个事务
|
||||
/// </summary>
|
||||
/// <param name="dbbase"></param>
|
||||
/// <returns></returns>
|
||||
public IProdureParameter<SqlCommand> BeginTransaction(dbbase db) {
|
||||
return mmsql.BeginTransaction(GetDataBaseName(db));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 事务添加sql语句
|
||||
/// </summary>
|
||||
/// <param name="spp"></param>
|
||||
/// <param name="sql"></param>
|
||||
public int TransactionAddSql(IProdureParameter<SqlCommand> spp, string sql, List<ISqlAloneParameter<SqlDbType>> pms = null) {
|
||||
return mmsql.TransactionAddSql(spp, sql, pms);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 提交事务
|
||||
/// </summary>
|
||||
/// <param name="spp"></param>
|
||||
/// <returns>true 表示提交成功 false 表示提交失败</returns>
|
||||
public bool SubTransaction(IProdureParameter<SqlCommand> spp) {
|
||||
return mmsql.SubTransaction(spp);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 事务回滚
|
||||
/// </summary>
|
||||
/// <param name="spp"></param>
|
||||
public void Rollback(IProdureParameter<SqlCommand> spp) {
|
||||
mmsql.RollbackTransaction(spp);
|
||||
}
|
||||
|
||||
#region 异步存储过程与事务操作
|
||||
|
||||
/// <summary>
|
||||
/// 异步结束执行存储过程
|
||||
/// </summary>
|
||||
public async Task<Dictionary<string, object>> EndAddProdureParametersAsync(IProdureParameter<SqlCommand> spp, DataSet ds = null) {
|
||||
return await mmsql.SubProcedureAsync(spp, ds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步执行sql语句
|
||||
/// </summary>
|
||||
public async Task<int> ExceSqlAsync(dbbase db, string sql, IEnumerable<SqlParameter> sqlparams = null, DataSet ds = null) {
|
||||
return await mmsql.ExecuteSqlAsync(GetDataBaseName(db), sql, sqlparams, ds);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 异步查询数据库
|
||||
/// </summary>
|
||||
public async Task<DataTable> selectDbAsync(dbbase db, string table, string[] column = null, string whereStr = null, int count = -1, int againCount = -1, IEnumerable<SqlParameter> sqlparams = null) {
|
||||
return await mmsql.SelectAsync(GetDataBaseName(db), table, column, whereStr, count, againCount, sqlparams);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Dapper 操作
|
||||
|
||||
public SqlConnection GetSql(dbbase db)
|
||||
{
|
||||
return mmsql.GetConnection(GetDataBaseName(db));
|
||||
}
|
||||
|
||||
public int DapperExecute(dbbase db, string sqlText, object param)
|
||||
{
|
||||
using (var conn = mmsql.GetConnection(GetDataBaseName(db)))
|
||||
{
|
||||
return conn.Execute(sqlText, param);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<int> DapperExecuteAsync(dbbase db, string sqlText, object param)
|
||||
{
|
||||
using (var conn = mmsql.GetConnection(GetDataBaseName(db)))
|
||||
{
|
||||
return await conn.ExecuteAsync(sqlText, param);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<bool> DapperExecuteTransactionAsync(dbbase db, Func<SqlConnection, SqlTransaction, Task<bool>> doAction)
|
||||
{
|
||||
if (doAction == null) return false;
|
||||
using (var conn = mmsql.GetConnection(GetDataBaseName(db)))
|
||||
{
|
||||
await conn.OpenAsync();
|
||||
using (var transaction = conn.BeginTransaction())
|
||||
{
|
||||
try
|
||||
{
|
||||
var success = await doAction.Invoke(conn, transaction);
|
||||
if (success)
|
||||
transaction.Commit();
|
||||
else
|
||||
transaction.Rollback();
|
||||
|
||||
return success;
|
||||
}
|
||||
catch
|
||||
{
|
||||
transaction.Rollback();
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
public void DapperExecuteProcedure(dbbase db, string procedureName, DynamicParameters param)
|
||||
{
|
||||
using (var conn = mmsql.GetConnection(GetDataBaseName(db)))
|
||||
{
|
||||
conn.Execute(procedureName, param, commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task DapperExecuteProcedureAsync(dbbase db, string procedureName, DynamicParameters param)
|
||||
{
|
||||
using (var conn = mmsql.GetConnection(GetDataBaseName(db)))
|
||||
{
|
||||
await conn.ExecuteAsync(procedureName, param, commandType: CommandType.StoredProcedure);
|
||||
}
|
||||
}
|
||||
|
||||
public IEnumerable<T> DapperQuery<T>(dbbase db, string sqlText, object param)
|
||||
{
|
||||
using (var conn = mmsql.GetConnection(GetDataBaseName(db)))
|
||||
{
|
||||
return conn.Query<T>(sqlText, param);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<IEnumerable<T>> DapperQueryAsync<T>(dbbase db, string sqlText, object param)
|
||||
{
|
||||
using (var conn = mmsql.GetConnection(GetDataBaseName(db)))
|
||||
{
|
||||
return await conn.QueryAsync<T>(sqlText, param);
|
||||
}
|
||||
}
|
||||
|
||||
public T DapperQueryFirstOrDefault<T>(dbbase db, string sqlText, object param)
|
||||
{
|
||||
using (var conn = mmsql.GetConnection(GetDataBaseName(db)))
|
||||
{
|
||||
return conn.QueryFirstOrDefault<T>(sqlText, param);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<T> DapperQueryFirstOrDefaultAsync<T>(dbbase db, string sqlText, object param)
|
||||
{
|
||||
using (var conn = mmsql.GetConnection(GetDataBaseName(db)))
|
||||
{
|
||||
return await conn.QueryFirstOrDefaultAsync<T>(sqlText, param);
|
||||
}
|
||||
}
|
||||
|
||||
public T DapperExecuteScalar<T>(dbbase db, string sqlText, object param)
|
||||
{
|
||||
using (var conn = mmsql.GetConnection(GetDataBaseName(db)))
|
||||
{
|
||||
return conn.ExecuteScalar<T>(sqlText, param);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<T> DapperExecuteScalarAsync<T>(dbbase db, string sqlText, object param)
|
||||
{
|
||||
using (var conn = mmsql.GetConnection(GetDataBaseName(db)))
|
||||
{
|
||||
return await conn.ExecuteScalarAsync<T>(sqlText, param);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<T> DapperQueryMultipleAsync<T>(dbbase db, string sqlText, object param, Func<SqlMapper.GridReader, Task<T>> getResults)
|
||||
{
|
||||
if (getResults == null) return default(T);
|
||||
using (var conn = mmsql.GetConnection(GetDataBaseName(db)))
|
||||
{
|
||||
using var multi = await conn.QueryMultipleAsync(sqlText, param);
|
||||
return await getResults.Invoke(multi);
|
||||
}
|
||||
}
|
||||
|
||||
public async Task<PageDBEntity<T>> DapperQueryPageAsync<T>(dbbase db, string sqlText, int pageIndex, int pageSize)
|
||||
{
|
||||
int skip = pageSize * (pageIndex - 1);
|
||||
return await DapperQueryMultipleAsync(dbbase.gamedb, sqlText,
|
||||
new { StartIndex = skip, EndIndex = skip + pageSize },
|
||||
async reader =>
|
||||
{
|
||||
PageDBEntity<T> page = new PageDBEntity<T>();
|
||||
page.List = (await reader.ReadAsync<T>()).ToList();
|
||||
page.Total = await reader.ReadSingleAsync<int>();
|
||||
return page;
|
||||
});
|
||||
}
|
||||
|
||||
public async Task<PageDBEntity<T>> DapperQueryPageAsync<T>(dbbase db, string sql, object param)
|
||||
{
|
||||
try
|
||||
{
|
||||
return await DapperQueryMultipleAsync(db, sql,
|
||||
param,
|
||||
async reader =>
|
||||
{
|
||||
PageDBEntity<T> page = new PageDBEntity<T>();
|
||||
page.List = (await reader.ReadAsync<T>()).ToList();
|
||||
page.Total = await reader.ReadSingleAsync<int>();
|
||||
return page;
|
||||
});
|
||||
}catch (Exception ex)
|
||||
{
|
||||
Debug.Error($"[DapperQueryPageAsync]执行失败Sql={sql}");
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
379
GameDAL/db/Sql/SqlBuilder.cs
Normal file
379
GameDAL/db/Sql/SqlBuilder.cs
Normal file
@ -0,0 +1,379 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using Dapper;
|
||||
|
||||
namespace Server.DB.Sql
|
||||
{
|
||||
/// <summary>
|
||||
/// SQL 构建器,支持查询、分页、插入、更新、删除,兼容 Dapper
|
||||
/// </summary>
|
||||
public class SqlBuilder
|
||||
{
|
||||
private readonly string _tableName;
|
||||
private string _select = "*";
|
||||
private StringBuilder _where = new StringBuilder("1=1");
|
||||
private DynamicParameters _parameters = new DynamicParameters();
|
||||
private readonly List<string> _joins = new List<string>();
|
||||
private readonly List<string> _orderBy = new List<string>();
|
||||
private readonly List<string> _groupBy = new List<string>();
|
||||
private int _paramCount = 0;
|
||||
|
||||
public SqlBuilder(string tableName)
|
||||
{
|
||||
if (string.IsNullOrWhiteSpace(tableName))
|
||||
throw new ArgumentException("Table name cannot be null or empty");
|
||||
_tableName = tableName;
|
||||
}
|
||||
|
||||
public SqlBuilder Restart()
|
||||
{
|
||||
_select = "*";
|
||||
_where = new StringBuilder("1=1");
|
||||
_parameters = new DynamicParameters();
|
||||
_joins.Clear();
|
||||
_orderBy.Clear();
|
||||
_groupBy.Clear();
|
||||
_paramCount = 0;
|
||||
return this;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成增长式的参数
|
||||
/// </summary>
|
||||
private string GenerateParam(string column)
|
||||
{
|
||||
_paramCount++;
|
||||
var param = column.Replace(".", "_") + "_" + _paramCount;
|
||||
return param;
|
||||
}
|
||||
|
||||
#region Select
|
||||
|
||||
public SqlBuilder Select(string select)
|
||||
{
|
||||
_select = select;
|
||||
return this;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region Join
|
||||
|
||||
public SqlBuilder InnerJoin(string table, string on)
|
||||
{
|
||||
_joins.Add($"INNER JOIN {table} ON {on}");
|
||||
return this;
|
||||
}
|
||||
|
||||
public SqlBuilder LeftJoin(string table, string on)
|
||||
{
|
||||
_joins.Add($"LEFT JOIN {table} ON {on}");
|
||||
return this;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region WHERE 条件
|
||||
|
||||
public SqlBuilder WhereEqual(string column, object value)
|
||||
{
|
||||
if (value != null)
|
||||
{
|
||||
var param = GenerateParam(column);
|
||||
_where.Append($" AND {column} = @{param}");
|
||||
_parameters.Add(param, value);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public SqlBuilder WhereNotEqual(string column, object value)
|
||||
{
|
||||
if (value != null)
|
||||
{
|
||||
var param = GenerateParam(column);
|
||||
_where.Append($" AND {column} <> @{param}");
|
||||
_parameters.Add(param, value);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public SqlBuilder WhereBetween(string column, object value1, object value2)
|
||||
{
|
||||
if (value1 != null && value2 != null)
|
||||
{
|
||||
var param = column.Replace(".", "_");
|
||||
_where.Append($" AND {column} BETWEEN @{param}_1 AND @{param}_2");
|
||||
_parameters.Add($"{param}_1", value1);
|
||||
_parameters.Add($"{param}_2", value2);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public SqlBuilder WhereLike(string column, string value)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(value))
|
||||
{
|
||||
_where.Append($" AND {column} LIKE @{column}");
|
||||
_parameters.Add(column, $"%{value}%");
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public SqlBuilder WhereCustom(string condition, string paramName, object value)
|
||||
{
|
||||
if (!string.IsNullOrEmpty(condition) && value != null)
|
||||
{
|
||||
_where.Append($" AND {condition}");
|
||||
_parameters.Add(paramName, value);
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public SqlBuilder WhereIn<T>(string column, IEnumerable<T> values)
|
||||
{
|
||||
if (values != null && values.Any())
|
||||
{
|
||||
var list = values.ToList();
|
||||
var paramNames = new List<string>();
|
||||
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
if (list[i] == null) continue;
|
||||
string paramName = $"{column}_in{i}";
|
||||
paramNames.Add("@" + paramName);
|
||||
_parameters.Add(paramName, list[i]);
|
||||
}
|
||||
|
||||
string inClause = string.Join(",", paramNames);
|
||||
_where.Append($" AND {column} IN ({inClause})");
|
||||
}
|
||||
else
|
||||
{
|
||||
_where.Append(" AND 1=0");
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public SqlBuilder WhereNotIn<T>(string column, IEnumerable<T> values)
|
||||
{
|
||||
if (values != null && values.Any())
|
||||
{
|
||||
var list = values.ToList();
|
||||
var paramNames = new List<string>();
|
||||
|
||||
for (int i = 0; i < list.Count; i++)
|
||||
{
|
||||
if (list[i] == null) continue;
|
||||
string paramName = $"{column}_in{i}";
|
||||
paramNames.Add("@" + paramName);
|
||||
_parameters.Add(paramName, list[i]);
|
||||
}
|
||||
|
||||
string inClause = string.Join(",", paramNames);
|
||||
_where.Append($" AND {column} NOT IN ({inClause})");
|
||||
}
|
||||
else
|
||||
{
|
||||
_where.Append(" AND 1=0");
|
||||
}
|
||||
|
||||
return this;
|
||||
}
|
||||
|
||||
public SqlBuilder OrderBy(string column, bool descending = false)
|
||||
{
|
||||
_orderBy.Add($"{column} {(descending ? "DESC" : "ASC")}");
|
||||
return this;
|
||||
}
|
||||
|
||||
public SqlBuilder GroupBy(string column)
|
||||
{
|
||||
_groupBy.Add(column);
|
||||
return this;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region 查询 + 分页
|
||||
|
||||
public (string Sql, DynamicParameters Parameters) BuildSelect()
|
||||
{
|
||||
string order = _orderBy.Any() ? $" ORDER BY {string.Join(",", _orderBy)}" : "";
|
||||
string join = _joins.Any() ? $" {string.Join(" ", _joins)}" : "";
|
||||
string group = _groupBy.Any() ? $" GROUP BY {string.Join(",", _groupBy)}" : "";
|
||||
string sql = $"SELECT {_select} FROM {_tableName}{join} WHERE {_where}{group}{order};";
|
||||
return (sql, _parameters);
|
||||
}
|
||||
|
||||
public (string Sql, DynamicParameters Parameters) BuildPageSqlWithSearch<T>(DbSearchField<T> searchField)
|
||||
{
|
||||
var pageIndex = searchField.GetPageIndex();
|
||||
var pageSize = searchField.GetPageSize();
|
||||
// 根据注解自动构建查询条件
|
||||
searchField.BuildWhereConditions(this);
|
||||
|
||||
return BuildPageSql(pageIndex, pageSize);
|
||||
}
|
||||
|
||||
public (string Sql, DynamicParameters Parameters) BuildPageSql(int page, int pageSize)
|
||||
{
|
||||
int startRow = (page - 1) * pageSize + 1;
|
||||
int endRow = page * pageSize;
|
||||
|
||||
var parameters = new DynamicParameters();
|
||||
foreach (var paramName in _parameters.ParameterNames)
|
||||
{
|
||||
parameters.Add(paramName, _parameters.Get<object>(paramName));
|
||||
}
|
||||
|
||||
parameters.Add("StartRow", startRow);
|
||||
parameters.Add("EndRow", endRow);
|
||||
|
||||
string order = _orderBy.Any() ? string.Join(",", _orderBy) : "Id DESC";
|
||||
string join = _joins.Any() ? $" {string.Join(" ", _joins)}" : "";
|
||||
string tableAlias = "";
|
||||
string tableName = _tableName;
|
||||
if (_tableName.Contains(" "))
|
||||
{
|
||||
tableName = _tableName.Split(' ')[0];
|
||||
tableAlias = $" {_tableName.Split(' ')[1]}";
|
||||
}
|
||||
|
||||
string sql = $@"
|
||||
WITH BaseQuery AS (
|
||||
SELECT *, ROW_NUMBER() OVER (ORDER BY {order}) AS RowNum
|
||||
FROM {tableName}
|
||||
WHERE {_where}
|
||||
)
|
||||
SELECT {_select}
|
||||
FROM BaseQuery{tableAlias}{join}
|
||||
WHERE RowNum BETWEEN @StartRow AND @EndRow;
|
||||
|
||||
SELECT COUNT(1) FROM {tableName} WHERE {_where};
|
||||
";
|
||||
return (sql, parameters);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region INSERT
|
||||
|
||||
public (string Sql, DynamicParameters Parameters) BuildInsert(Dictionary<string, object> fields)
|
||||
{
|
||||
if (fields == null || fields.Count == 0)
|
||||
throw new ArgumentException("Insert fields cannot be empty");
|
||||
|
||||
var columns = string.Join(",", fields.Keys);
|
||||
var values = string.Join(",", fields.Keys.Select(k => "@" + k));
|
||||
|
||||
foreach (var kv in fields)
|
||||
{
|
||||
_parameters.Add(kv.Key, kv.Value);
|
||||
}
|
||||
|
||||
string sql = $"INSERT INTO {_tableName} ({columns}) VALUES ({values});";
|
||||
if (_where.ToString() != "1=1")
|
||||
{
|
||||
sql = $"IF NOT EXISTS (SELECT 1 FROM {_tableName} WHERE {_where}) BEGIN INSERT INTO {_tableName} ({columns}) VALUES ({values}) END;";
|
||||
}
|
||||
|
||||
return (sql, _parameters);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region UPDATE
|
||||
|
||||
public (string Sql, DynamicParameters Parameters) BuildUpdate(Dictionary<string, object> fields)
|
||||
{
|
||||
if (fields == null || fields.Count == 0)
|
||||
throw new ArgumentException("Update fields cannot be empty");
|
||||
|
||||
var setList = new List<string>();
|
||||
var parameters = new DynamicParameters();
|
||||
|
||||
foreach (var kv in fields)
|
||||
{
|
||||
setList.Add($"{kv.Key} = @{kv.Key}");
|
||||
parameters.Add(kv.Key, kv.Value);
|
||||
}
|
||||
|
||||
// 添加 WHERE 的参数
|
||||
foreach (var paramName in _parameters.ParameterNames)
|
||||
{
|
||||
parameters.Add(paramName, _parameters.Get<object>(paramName));
|
||||
}
|
||||
|
||||
string sql = $"UPDATE {_tableName} SET {string.Join(",", setList)} WHERE {_where};";
|
||||
|
||||
return (sql, parameters);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 生成 Upsert SQL
|
||||
/// </summary>
|
||||
public (string Sql, DynamicParameters Parameters) BuildUpsert(
|
||||
Dictionary<string, object> fields,
|
||||
string primaryKey, bool isInsertKey = false)
|
||||
{
|
||||
if (fields == null || fields.Count == 0)
|
||||
throw new ArgumentException("Fields cannot be empty");
|
||||
|
||||
if (string.IsNullOrWhiteSpace(primaryKey))
|
||||
throw new ArgumentException("Primary key must be provided");
|
||||
|
||||
var parameters = new DynamicParameters();
|
||||
foreach (var kv in fields)
|
||||
{
|
||||
if (kv.Value != null)
|
||||
parameters.Add(kv.Key, kv.Value);
|
||||
}
|
||||
|
||||
var parameterNames = parameters.ParameterNames
|
||||
.Where(k => k != primaryKey).ToList();
|
||||
var insertSourceColumns = string.Join(",", isInsertKey ? parameters.ParameterNames : parameterNames);
|
||||
var insertValues = string.Join(",", (isInsertKey ? parameters.ParameterNames : parameterNames).Select(k => "@" + k));
|
||||
var updateList = parameterNames.Select(k => $"{k} = @{k}");
|
||||
|
||||
string sql = @$"IF EXISTS (SELECT 1 FROM {_tableName} WHERE {primaryKey}=@{primaryKey})
|
||||
BEGIN
|
||||
UPDATE {_tableName} SET {string.Join(",", updateList)} WHERE {primaryKey}=@{primaryKey}
|
||||
END
|
||||
ELSE
|
||||
BEGIN
|
||||
INSERT INTO {_tableName} ({insertSourceColumns}) VALUES ({insertValues})
|
||||
SELECT CAST(SCOPE_IDENTITY() AS INT)
|
||||
END";
|
||||
return (sql, parameters);
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
#region DELETE
|
||||
|
||||
public (string Sql, DynamicParameters Parameters) BuildDelete()
|
||||
{
|
||||
if (_where.Length <= 0)
|
||||
throw new InvalidOperationException("Delete must have WHERE clause");
|
||||
|
||||
var parameters = new DynamicParameters();
|
||||
foreach (var paramName in _parameters.ParameterNames)
|
||||
{
|
||||
parameters.Add(paramName, _parameters.Get<object>(paramName));
|
||||
}
|
||||
|
||||
string sql = $"DELETE FROM {_tableName} WHERE {_where};";
|
||||
return (sql, parameters);
|
||||
}
|
||||
|
||||
#endregion
|
||||
}
|
||||
}
|
||||
22
GameDAL/db/Sql/dbbase.cs
Normal file
22
GameDAL/db/Sql/dbbase.cs
Normal file
@ -0,0 +1,22 @@
|
||||
/*
|
||||
* 由SharpDevelop创建。
|
||||
* 用户: Administrator
|
||||
* 日期: 2018-05-05
|
||||
* 时间: 13:23
|
||||
*
|
||||
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
|
||||
*/
|
||||
|
||||
/// <summary>
|
||||
/// 数据库
|
||||
/// </summary>
|
||||
public enum dbbase {
|
||||
/// <summary>
|
||||
/// jnxdgame
|
||||
/// </summary>
|
||||
gamedb = 0,
|
||||
/// <summary>
|
||||
/// game2018
|
||||
/// </summary>
|
||||
game2018 = 1
|
||||
}
|
||||
314
GameDAL/db/redis/DistributedLock.cs
Normal file
314
GameDAL/db/redis/DistributedLock.cs
Normal file
@ -0,0 +1,314 @@
|
||||
/*
|
||||
* 由SharpDevelop创建。
|
||||
* 用户: Administrator
|
||||
* 日期: 2018-10-24
|
||||
* 时间: 9:56
|
||||
*
|
||||
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
|
||||
*/
|
||||
using System;
|
||||
using System.Threading;
|
||||
using MrWu.Debug;
|
||||
using Server.DB.Redis;
|
||||
using StackExchange.Redis;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace Server.DB.Redis
|
||||
{
|
||||
/// <summary>
|
||||
/// 分布式锁
|
||||
/// </summary>
|
||||
public class DistributedLock{
|
||||
|
||||
/// <summary>
|
||||
/// 最大等待数量
|
||||
/// </summary>
|
||||
private readonly int maxWaitCnt;
|
||||
|
||||
/// <summary>
|
||||
/// 锁的钥匙
|
||||
/// </summary>
|
||||
private readonly string[] lockKey;
|
||||
|
||||
/// <summary>
|
||||
/// 下一个锁的位置
|
||||
/// </summary>
|
||||
private int nextid = -1;
|
||||
|
||||
/// <summary>
|
||||
/// 读写锁
|
||||
/// </summary>
|
||||
private readonly ReaderWriterLockSlim rwls = new ReaderWriterLockSlim();
|
||||
|
||||
private volatile IDatabaseProxy m_db;
|
||||
|
||||
/// <summary>
|
||||
/// 操作线程锁数据库
|
||||
/// </summary>
|
||||
private IDatabaseProxy db{
|
||||
get{
|
||||
if(m_db == null)
|
||||
m_db = redisManager.db;
|
||||
return m_db;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 创建分布式锁
|
||||
/// </summary>
|
||||
/// <param name="waitMaxCnt">最大等待数量</param>
|
||||
public DistributedLock(int waitMaxCnt){
|
||||
maxWaitCnt = waitMaxCnt;
|
||||
lockKey = new string[maxWaitCnt];
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加锁
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <returns></returns>
|
||||
private int AddKey(string key){
|
||||
while(true){
|
||||
rwls.EnterWriteLock();
|
||||
try{
|
||||
nextid++;
|
||||
if(nextid >= maxWaitCnt)
|
||||
nextid = 0;
|
||||
if(lockKey[nextid] == null){
|
||||
lockKey[nextid] = key;
|
||||
return nextid;
|
||||
}
|
||||
}finally{
|
||||
rwls.ExitWriteLock();
|
||||
}
|
||||
//SpinWait sw = new SpinWait();
|
||||
//sw.SpinOnce();
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除锁
|
||||
/// </summary>
|
||||
/// <param name="idx"></param>
|
||||
/// <returns></returns>
|
||||
private void RemoveKey(int idx){
|
||||
rwls.EnterWriteLock();
|
||||
try{
|
||||
lockKey[idx] = null;
|
||||
}finally{
|
||||
rwls.ExitWriteLock();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取钥匙
|
||||
/// </summary>
|
||||
/// <param name="idx"></param>
|
||||
/// <returns></returns>
|
||||
private string GetKey(int idx){
|
||||
rwls.EnterReadLock();
|
||||
try{
|
||||
return lockKey[idx];
|
||||
}finally{
|
||||
rwls.ExitReadLock();
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 为锁续航
|
||||
/// </summary>
|
||||
/// <param name="state"></param>
|
||||
private void AddLockLife(object state){
|
||||
Task.Factory.StartNew(()=>{
|
||||
int idx = (int)state;
|
||||
string key = GetKey(idx);
|
||||
|
||||
while(true){
|
||||
Thread.Sleep(1000);
|
||||
if(key == GetKey(idx) && key != null){
|
||||
string strtimeOut = db.StringGet(key);
|
||||
if(strtimeOut != null){
|
||||
int timeOut;
|
||||
if(int.TryParse(strtimeOut,out timeOut))
|
||||
db.KeyExpire(key,new TimeSpan(0,0,timeOut));
|
||||
else
|
||||
Debug.Error("不可能的错误存储的值不是数字anckjnsakjbdnja,"+strtimeOut + "," + key);
|
||||
}else{
|
||||
break;
|
||||
}
|
||||
}else
|
||||
break;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 尝试运行
|
||||
/// </summary>
|
||||
/// <param name="key">key</param>
|
||||
/// <param name="action">事件</param>
|
||||
/// <param name="timeOut">key超时时间</param>
|
||||
/// <param name="tryTimeOut">尝试超时时间</param>
|
||||
/// <returns>是否运行</returns>
|
||||
public bool TryLockRun(string key,Action action,int timeOut,int tryTimeOut = 0){
|
||||
if(key == null){
|
||||
Debug.Error("key不能为null");
|
||||
return false;
|
||||
}
|
||||
key = key+".lock";
|
||||
TimeSpan tm = new TimeSpan(0,0,timeOut);
|
||||
DateTime lastTime = DateTime.Now;
|
||||
//SpinWait sw = new SpinWait();
|
||||
while(!db.StringSet(key,timeOut,tm,When.NotExists)){
|
||||
if((DateTime.Now - lastTime).TotalMilliseconds >= tryTimeOut)
|
||||
return false;
|
||||
//sw.SpinOnce();
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
|
||||
//Debug.Log("运算开始:" + key + "," + DateTime.Now.Millisecond.ToString());
|
||||
Exception ex = null;
|
||||
int idx = AddKey(key);
|
||||
try{
|
||||
AddLockLife(idx);
|
||||
if(action != null)
|
||||
action();
|
||||
}catch(Exception e){
|
||||
Debug.Error("处理出错:" + e.ToString());
|
||||
ex = e;
|
||||
}finally{
|
||||
RemoveKey(idx);
|
||||
//Debug.Log("运算结束:" + key + "," + DateTime.Now.Millisecond.ToString());
|
||||
db.KeyDelete(key);
|
||||
if(ex != null)
|
||||
throw ex;
|
||||
}
|
||||
return true;
|
||||
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 尝试运行
|
||||
/// </summary>
|
||||
/// <param name="key">key</param>
|
||||
/// <param name="func">事件</param>
|
||||
/// <param name="timeOut">timeOut</param>
|
||||
/// <param name="result">返回结果</param>
|
||||
/// <param name="tryTimeOut">尝试超时时间</param>
|
||||
/// <returns>是否运行</returns>
|
||||
public bool TryLockRun<T>(string key,Func<T> func,int timeOut,out T result,int tryTimeOut = 0){
|
||||
result = default(T);
|
||||
if(key == null){
|
||||
Debug.Error("key不能为null");
|
||||
return false;
|
||||
}
|
||||
|
||||
key = key + ".lock";
|
||||
TimeSpan tm = new TimeSpan(0,0,timeOut);
|
||||
DateTime lastTime = DateTime.Now;
|
||||
//SpinWait sw = new SpinWait();
|
||||
while(!db.StringSet(key,timeOut,tm,When.NotExists)){
|
||||
if((DateTime.Now - lastTime).TotalMilliseconds >= tryTimeOut)
|
||||
return false;
|
||||
//sw.SpinOnce();
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
|
||||
Exception ex = null;
|
||||
int idx = AddKey(key);
|
||||
try{
|
||||
AddLockLife(idx);
|
||||
if(func != null)
|
||||
result = func();
|
||||
}catch(Exception e){
|
||||
ex = e;
|
||||
Debug.Error("处理出错:" + e.ToString());
|
||||
}finally{
|
||||
RemoveKey(idx);
|
||||
Debug.Log("运算结束:" + key + "," + DateTime.Now.Millisecond.ToString());
|
||||
db.KeyDelete(key);
|
||||
if(ex != null)
|
||||
throw ex;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加锁运行
|
||||
/// </summary>
|
||||
public void LockRun(string key,Action action,int timeOut = 3){
|
||||
if(key == null){
|
||||
Debug.Error("key不能为null");
|
||||
return;
|
||||
}
|
||||
key = key+".lock";
|
||||
TimeSpan tm = new TimeSpan(0,0,timeOut);
|
||||
//SpinWait sw = new SpinWait();
|
||||
while(!db.StringSet(key,timeOut,tm,When.NotExists)){
|
||||
//sw.SpinOnce();
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
|
||||
Exception ex = null;
|
||||
|
||||
int idx = AddKey(key);
|
||||
try{
|
||||
AddLockLife(idx);
|
||||
|
||||
if(action != null)
|
||||
action();
|
||||
|
||||
}catch(Exception e){
|
||||
ex = e;
|
||||
}finally{
|
||||
RemoveKey(idx);
|
||||
db.KeyDelete(key);
|
||||
if(ex != null)
|
||||
throw ex;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 加锁运行
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="func"></param>
|
||||
/// <param name="timeOut">超时时间</param>
|
||||
/// <returns></returns>
|
||||
public T LockRun<T>(string key,Func<T> func,int timeOut = 3){
|
||||
T result = default(T);
|
||||
if(key == null){
|
||||
Debug.Error("key不能为null");
|
||||
return result;
|
||||
}
|
||||
|
||||
key = key + ".lock";
|
||||
TimeSpan tm = new TimeSpan(0,0,timeOut);
|
||||
//SpinWait sw = new SpinWait();
|
||||
|
||||
while(!db.StringSet(key,timeOut,tm,When.NotExists)){
|
||||
//sw.SpinOnce();
|
||||
Thread.Sleep(1);
|
||||
}
|
||||
|
||||
Exception ex = null;
|
||||
int idx = AddKey(key);
|
||||
try{
|
||||
AddLockLife(idx);
|
||||
|
||||
if(func != null)
|
||||
result = func();
|
||||
|
||||
}catch(Exception e){
|
||||
ex = new Exception("lockRun error :" , e);
|
||||
}finally{
|
||||
RemoveKey(idx);
|
||||
db.KeyDelete(key);
|
||||
if(ex != null)
|
||||
throw ex;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
}
|
||||
}
|
||||
3622
GameDAL/db/redis/IDatabaseProxy.cs
Normal file
3622
GameDAL/db/redis/IDatabaseProxy.cs
Normal file
@ -0,0 +1,3622 @@
|
||||
/*
|
||||
* 由SharpDevelop创建。
|
||||
* 用户: Administrator
|
||||
* 日期: 2018-12-07
|
||||
* 时间: 15:34
|
||||
*
|
||||
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
|
||||
*/
|
||||
using System;
|
||||
using System.Collections;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
using System.Reflection;
|
||||
using System.Text;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using MrWu.Debug;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Server.DB.Redis {
|
||||
/*
|
||||
* CommandFlags
|
||||
* None = 0; //默认行为
|
||||
* HighPriority = 1; //不用了,废弃
|
||||
* FireAndForget = 2; //对结果不感兴趣,调用者将会立即收到默认值
|
||||
* PreferMaster = 0; //如果主服务器可用,则应在主服务器上执行此操作,但可以执行读操作
|
||||
* DemandMaster = 4; //此操作只应在[主站]上执行
|
||||
* PreferSlave = 8; //如果可用,则应在[从站]上执行此操作,但将在其上执行
|
||||
* DemandSlave = 12; //此操作只应在[从站]上执行。 仅适用于读取操作。
|
||||
* NoRedirect = 64; //表示由于ASK或MOVED响应,不应将此操作转发到其他服务器
|
||||
* NoScriptCache = 512 //表示与脚本相关的操作应使用EVAL,而不是SCRIPT LOAD + EVALSHA
|
||||
* */
|
||||
|
||||
/*
|
||||
* When
|
||||
* Always: 一直
|
||||
* Exists: 当key存在时才生效
|
||||
* NotExists: 当key不存在时才生效
|
||||
*
|
||||
* */
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// IDatabase 代理
|
||||
/// </summary>
|
||||
public partial class IDatabaseProxy {
|
||||
|
||||
private IDatabase db;
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="db"></param>
|
||||
public IDatabaseProxy(IDatabase db) {
|
||||
this.db = db;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 循环超时数量
|
||||
/// </summary>
|
||||
private const int loopOutCnt = 3;
|
||||
|
||||
private T FDBOpera<T, K1>(Func<K1, T> func, K1 param1) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return func(param1);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private T FDBOpera<T, K1, K2>(Func<K1, K2, T> func, K1 param1, K2 param2) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return func(param1, param2);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private T FDBOpera<T, K1, K2, K3>(Func<K1, K2, K3, T> func, K1 param1, K2 param2, K3 param3) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return func(param1, param2, param3);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private T FDBOpera<T, K1, K2, K3, K4>(Func<K1, K2, K3, K4, T> func, K1 param1, K2 param2, K3 param3, K4 param4) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return func(param1, param2, param3, param4);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private T FDBOpera<T, K1, K2, K3, K4, K5>(Func<K1, K2, K3, K4, K5, T> func, K1 param1, K2 param2, K3 param3, K4 param4, K5 param5) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return func(param1, param2, param3, param4, param5);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private T FDBOpera<T, K1, K2, K3, K4, K5, K6>(Func<K1, K2, K3, K4, K5, K6, T> func, K1 param1, K2 param2, K3 param3, K4 param4, K5 param5, K6 param6) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return func(param1, param2, param3, param4, param5, param6);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private T FDBOpera<T, K1, K2, K3, K4, K5, K6, K7>(Func<K1, K2, K3, K4, K5, K6, K7, T> func, K1 param1, K2 param2, K3 param3, K4 param4, K5 param5, K6 param6, K7 param7) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return func(param1, param2, param3, param4, param5, param6, param7);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private T FDBOpera<T, K1, K2, K3, K4, K5, K6, K7, K8>(Func<K1, K2, K3, K4, K5, K6, K7, K8, T> func, K1 param1, K2 param2, K3 param3, K4 param4, K5 param5, K6 param6, K7 param7, K8 param8) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return func(param1, param2, param3, param4, param5, param6, param7, param8);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private T FDBOpera<T, K1, K2, K3, K4, K5, K6, K7, K8, K9>(Func<K1, K2, K3, K4, K5, K6, K7, K8, K9, T> func, K1 param1, K2 param2, K3 param3, K4 param4, K5 param5, K6 param6, K7 param7, K8 param8, K9 param9) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return func(param1, param2, param3, param4, param5, param6, param7, param8, param9);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ADBOpera<K1, K2, K3>(Action<K1, K2, K3> action, K1 param1, K2 param2, K3 param3) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
action(param1, param2, param3);
|
||||
return;
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#region 异步重试方法
|
||||
|
||||
private async Task<T> FDBOperaAsync<T, K1>(Func<K1, Task<T>> func, K1 param1) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return await func(param1);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<T> FDBOperaAsync<T, K1, K2>(Func<K1, K2, Task<T>> func, K1 param1, K2 param2) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return await func(param1, param2);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<T> FDBOperaAsync<T, K1, K2, K3>(Func<K1, K2, K3, Task<T>> func, K1 param1, K2 param2, K3 param3) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return await func(param1, param2, param3);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<T> FDBOperaAsync<T, K1, K2, K3, K4>(Func<K1, K2, K3, K4, Task<T>> func, K1 param1, K2 param2, K3 param3, K4 param4) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return await func(param1, param2, param3, param4);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<T> FDBOperaAsync<T, K1, K2, K3, K4, K5>(Func<K1, K2, K3, K4, K5, Task<T>> func, K1 param1, K2 param2, K3 param3, K4 param4, K5 param5) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return await func(param1, param2, param3, param4, param5);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<T> FDBOperaAsync<T, K1, K2, K3, K4, K5, K6>(Func<K1, K2, K3, K4, K5, K6, Task<T>> func, K1 param1, K2 param2, K3 param3, K4 param4, K5 param5, K6 param6) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return await func(param1, param2, param3, param4, param5, param6);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<T> FDBOperaAsync<T, K1, K2, K3, K4, K5, K6, K7>(Func<K1, K2, K3, K4, K5, K6, K7, Task<T>> func, K1 param1, K2 param2, K3 param3, K4 param4, K5 param5, K6 param6, K7 param7) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return await func(param1, param2, param3, param4, param5, param6, param7);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<T> FDBOperaAsync<T, K1, K2, K3, K4, K5, K6, K7, K8>(Func<K1, K2, K3, K4, K5, K6, K7, K8, Task<T>> func, K1 param1, K2 param2, K3 param3, K4 param4, K5 param5, K6 param6, K7 param7, K8 param8) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return await func(param1, param2, param3, param4, param5, param6, param7, param8);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task<T> FDBOperaAsync<T, K1, K2, K3, K4, K5, K6, K7, K8, K9>(Func<K1, K2, K3, K4, K5, K6, K7, K8, K9, Task<T>> func, K1 param1, K2 param2, K3 param3, K4 param4, K5 param5, K6 param6, K7 param7, K8 param8, K9 param9) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
return await func(param1, param2, param3, param4, param5, param6, param7, param8, param9);
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ADBOperaAsync<K1, K2, K3>(Func<K1, K2, K3, Task> func, K1 param1, K2 param2, K3 param3) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
await func(param1, param2, param3);
|
||||
return;
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ADBOperaAsync<K1, K2, K3, K4>(Func<K1, K2, K3, K4, Task> func, K1 param1, K2 param2, K3 param3, K4 param4) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
await func(param1, param2, param3, param4);
|
||||
return;
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ADBOperaAsync<K1, K2, K3, K4, K5, K6>(Func<K1, K2, K3, K4, K5, K6, Task> func, K1 param1, K2 param2, K3 param3, K4 param4, K5 param5, K6 param6) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
await func(param1, param2, param3, param4, param5, param6);
|
||||
return;
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
private void ADBOpera<K1, K2, K3, K4>(Action<K1, K2, K3, K4> action, K1 param1, K2 param2, K3 param3, K4 param4) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
action(param1, param2, param3, param4);
|
||||
return;
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private void ADBOpera<K1, K2, K3, K4, K5, K6>(Action<K1, K2, K3, K4, K5, K6> action, K1 params1, K2 params2, K3 params3, K4 params4, K5 params5, K6 params6) {
|
||||
int cnt = 0;
|
||||
while(true) {
|
||||
try {
|
||||
action(params1, params2, params3, params4, params5, params6);
|
||||
return;
|
||||
} catch(TimeoutException) {
|
||||
cnt++;
|
||||
if(cnt > loopOutCnt) {
|
||||
Debug.Fatal("Redis 命令超时重试次数已达上限!");
|
||||
throw;
|
||||
}
|
||||
} catch(Exception e) {
|
||||
Debug.Fatal("redis错误:" + e);
|
||||
throw;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="asyncState"></param>
|
||||
/// <returns></returns>
|
||||
public IBatch CreateBatch(object asyncState = null) {
|
||||
return FDBOpera(db.CreateBatch, asyncState);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="toServer"></param>
|
||||
/// <param name="toDatabase"></param>
|
||||
/// <param name="timeoutMilliseconds"></param>
|
||||
/// <param name="migrateOptions"></param>
|
||||
/// <param name="flags"></param>
|
||||
public void KeyMigrate(RedisKey key, EndPoint toServer, int toDatabase = 0, int timeoutMilliseconds = 0, MigrateOptions migrateOptions = MigrateOptions.None, CommandFlags flags = CommandFlags.None) {
|
||||
ADBOpera(db.KeyMigrate, key, toServer, toDatabase, timeoutMilliseconds, migrateOptions, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue DebugObject(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.DebugObject, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="longitude"></param>
|
||||
/// <param name="latitude"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool GeoAdd(RedisKey key, double longitude, double latitude, RedisValue member, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.GeoAdd, key, longitude, latitude, member, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool GeoAdd(RedisKey key, GeoEntry value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.GeoAdd, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long GeoAdd(RedisKey key, GeoEntry[] values, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.GeoAdd, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool GeoRemove(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.GeoRemove, key, member, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member1"></param>
|
||||
/// <param name="member2"></param>
|
||||
/// <param name="unit"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public double? GeoDistance(RedisKey key, RedisValue member1, RedisValue member2, GeoUnit unit = GeoUnit.Meters, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.GeoDistance, key, member1, member2, unit, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="members"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public string[] GeoHash(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.GeoHash, key, members, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public string GeoHash(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.GeoHash, key, member, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="members"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public GeoPosition?[] GeoPosition(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.GeoPosition, key, members, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public GeoPosition? GeoPosition(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.GeoPosition, key, member, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="radius"></param>
|
||||
/// <param name="unit"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public GeoRadiusResult[] GeoRadius(RedisKey key, RedisValue member, double radius, GeoUnit unit = GeoUnit.Meters, int count = -1, Order? order = null, GeoRadiusOptions options = GeoRadiusOptions.Default, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.GeoRadius, key, member, radius, unit, count, order, options, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="longitude"></param>
|
||||
/// <param name="latitude"></param>
|
||||
/// <param name="radius"></param>
|
||||
/// <param name="unit"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public GeoRadiusResult[] GeoRadius(RedisKey key, double longitude, double latitude, double radius, GeoUnit unit = GeoUnit.Meters, int count = -1, Order? order = null, GeoRadiusOptions options = GeoRadiusOptions.Default, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.GeoRadius, key, longitude, latitude, radius, unit, count, order, options, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hash中作减法运算
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long HashDecrement(RedisKey key, RedisValue hashField, long value = 1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashDecrement, key, hashField, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hash中作减法运算
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public double HashDecrement(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashDecrement, key, hashField, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除一个Hash中的一个键
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>是否删除成功</returns>
|
||||
public bool HashDelete(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashDelete, key, hashField, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 删除hash中的一些键
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashFields"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>删除的数量</returns>
|
||||
public long HashDelete(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashDelete, key, hashFields, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 某个Hash的键存在不存在
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool HashExists(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashExists, key, hashField, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取某个Hash的值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue HashGet(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashGet, key, hashField, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取一堆Hash的值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashFields"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] HashGet(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashGet, key, hashFields, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取所有的Hash键值对
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public HashEntry[] HashGetAll(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashGetAll, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hash中的值做加法运算
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>运算后的结果</returns>
|
||||
public long HashIncrement(RedisKey key, RedisValue hashField, long value = 1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashIncrement, key, hashField, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hash中做加法运算
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public double HashIncrement(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashIncrement, key, hashField, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// hash的所有键
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] HashKeys(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashKeys, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Hash中的键的数量
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long HashLength(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashLength, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="pattern"></param>
|
||||
/// <param name="pageSize"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public IEnumerable<HashEntry> HashScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags) {
|
||||
return FDBOpera(db.HashScan, key, pattern, pageSize, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="pattern"></param>
|
||||
/// <param name="pageSize"></param>
|
||||
/// <param name="cursor"></param>
|
||||
/// <param name="pageOffset"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public IEnumerable<HashEntry> HashScan(RedisKey key, RedisValue pattern = default(RedisValue), int pageSize = 10, long cursor = 0L, int pageOffset = 0, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashScan, key, pattern, pageSize, cursor, pageOffset, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置一堆键值队.
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashFields"></param>
|
||||
/// <param name="flags"></param>
|
||||
public void HashSet(RedisKey key, HashEntry[] hashFields, CommandFlags flags = CommandFlags.None) {
|
||||
ADBOpera(db.HashSet, key, hashFields, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置Hash键值对
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="when">只能使用Always以及 NoeExists 表示是是Hash的key,而非redis的key</param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>是否设置成功</returns>
|
||||
public bool HashSet(RedisKey key, RedisValue hashField, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashSet, key, hashField, value, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取hash的所有值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] HashValues(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HashValues, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool HyperLogLogAdd(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HyperLogLogAdd, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool HyperLogLogAdd(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HyperLogLogAdd, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long HyperLogLogLength(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HyperLogLogLength, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long HyperLogLogLength(RedisKey[] keys, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.HyperLogLogLength, keys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="first"></param>
|
||||
/// <param name="second"></param>
|
||||
/// <param name="flags"></param>
|
||||
public void HyperLogLogMerge(RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) {
|
||||
ADBOpera(db.HyperLogLogMerge, destination, first, second, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="sourceKeys"></param>
|
||||
/// <param name="flags"></param>
|
||||
public void HyperLogLogMerge(RedisKey destination, RedisKey[] sourceKeys, CommandFlags flags = CommandFlags.None) {
|
||||
ADBOpera(db.HyperLogLogMerge, destination, sourceKeys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public EndPoint IdentifyEndpoint(RedisKey key = default(RedisKey), CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.IdentifyEndpoint, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool KeyDelete(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyDelete, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long KeyDelete(RedisKey[] keys, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyDelete, keys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public byte[] KeyDump(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyDump, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool KeyExists(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyExists, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="expiry"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool KeyExpire(RedisKey key, TimeSpan? expiry, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyExpire, key, expiry, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="expiry"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool KeyExpire(RedisKey key, DateTime? expiry, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyExpire, key, expiry, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="database"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool KeyMove(RedisKey key, int database, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyMove, key, database, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool KeyPersist(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyPersist, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisKey KeyRandom(CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyRandom, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="newKey"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool KeyRename(RedisKey key, RedisKey newKey, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyRename, key, newKey, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="expiry"></param>
|
||||
/// <param name="flags"></param>
|
||||
public void KeyRestore(RedisKey key, byte[] value, TimeSpan? expiry = null, CommandFlags flags = CommandFlags.None) {
|
||||
ADBOpera(db.KeyRestore, key, value, expiry, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public TimeSpan? KeyTimeToLive(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyTimeToLive, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisType KeyType(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyType, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取列表中某个位置的元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue ListGetByIndex(RedisKey key, long index, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ListGetByIndex, key, index, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在pivot的后面插入一个元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="pivot"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>插入成功返回列表总长度 插入失败返回-1</returns>
|
||||
public long ListInsertAfter(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ListInsertAfter, key, pivot, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 在pivot的前面插入一个元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="pivot"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>插入成功返回列表总长度,插入失败返回-1</returns>
|
||||
public long ListInsertBefore(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ListInsertBefore, key, pivot, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从列表的左侧取出一个值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue ListLeftPop(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ListLeftPop, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从列表的左侧插入元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long ListLeftPush(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ListLeftPush, key, value, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从列表的左侧插入一堆值 顺序按数组的顺序插入
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>返回插入后的元素个数</returns>
|
||||
public long ListLeftPush(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ListLeftPush, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long ListLength(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ListLength, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] ListRange(RedisKey key, long start = 0L, long stop = -1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ListRange, key, start, stop, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从列表中删除某个元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="count">要删除的数量</param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>真正删除的数量</returns>
|
||||
public long ListRemove(RedisKey key, RedisValue value, long count = 0L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ListRemove, key, value, count, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从列表的右侧取出一个值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue ListRightPop(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ListRightPop, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从source中的右侧取出元素 并把 元素从左侧插入到 destination
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>取出的元素</returns>
|
||||
public RedisValue ListRightPopLeftPush(RedisKey source, RedisKey destination, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ListRightPopLeftPush, source, destination, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从列表的右侧插入元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>插入后的元素个数</returns>
|
||||
public long ListRightPush(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ListRightPush, key, value, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从列表的右侧插入一堆元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>插入后的元素个数</returns>
|
||||
public long ListRightPush(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) {
|
||||
|
||||
return FDBOpera(db.ListRightPush, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置列表中某个位置的元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
public void ListSetByIndex(RedisKey key, long index, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
ADBOpera(db.ListSetByIndex, key, index, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 裁剪列表
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="flags"></param>
|
||||
public void ListTrim(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None) {
|
||||
ADBOpera(db.ListTrim, key, start, stop, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="expiry"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool LockExtend(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.LockExtend, key, value, expiry, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue LockQuery(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.LockQuery, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool LockRelease(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.LockRelease, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="expiry"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool LockTake(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.LockTake, key, value, expiry, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="channel"></param>
|
||||
/// <param name="message"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long Publish(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.Publish, channel, message, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="script"></param>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisResult ScriptEvaluate(string script, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ScriptEvaluate, script, keys, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="hash"></param>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisResult ScriptEvaluate(byte[] hash, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ScriptEvaluate, hash, keys, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="script"></param>
|
||||
/// <param name="parameters"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisResult ScriptEvaluate(LuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ScriptEvaluate, script, parameters, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="script"></param>
|
||||
/// <param name="parameters"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisResult ScriptEvaluate(LoadedLuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.ScriptEvaluate, script, parameters, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 集合添加
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>是否添加成功</returns>
|
||||
public bool SetAdd(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetAdd, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 集合添加
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SetAdd(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetAdd, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 合并集合
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="first"></param>
|
||||
/// <param name="second"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] SetCombine(SetOperation operation, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetCombine, operation, first, second, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 合并集合
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] SetCombine(SetOperation operation, RedisKey[] keys, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetCombine, operation, keys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 合并集合并另存
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="first"></param>
|
||||
/// <param name="second"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetCombineAndStore, operation, destination, first, second, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 合并集合并另存
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetCombineAndStore, operation, destination, keys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 是否宝航
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool SetContains(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetContains, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 集合元素个数
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SetLength(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetLength, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取集合所有成员
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] SetMembers(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetMembers, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 集合移动到另一个集合
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool SetMove(RedisKey source, RedisKey destination, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetMove, source, destination, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 随机取出一个元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue SetPop(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetPop, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 随机返回一个元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue SetRandomMember(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetRandomMember, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 随机返回count个元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] SetRandomMembers(RedisKey key, long count, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetRandomMembers, key, count, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除一个元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool SetRemove(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetRemove, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 移除一堆元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SetRemove(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetRemove, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查找元素
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="pattern"></param>
|
||||
/// <param name="pageSize"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public IEnumerable<RedisValue> SetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags) {
|
||||
return FDBOpera(db.SetScan, key, pattern, pageSize, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 查找
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="pattern"></param>
|
||||
/// <param name="pageSize"></param>
|
||||
/// <param name="cursor"></param>
|
||||
/// <param name="pageOffset"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public IEnumerable<RedisValue> SetScan(RedisKey key, RedisValue pattern = default(RedisValue), int pageSize = 10, long cursor = 0L, int pageOffset = 0, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SetScan, key, pattern, pageSize, cursor, pageOffset, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="skip"></param>
|
||||
/// <param name="take"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="sortType"></param>
|
||||
/// <param name="by"></param>
|
||||
/// <param name="get"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] Sort(RedisKey key, long skip = 0L, long take = -1L, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.Sort, key, skip, take, order, sortType, by, get, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="skip"></param>
|
||||
/// <param name="take"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="sortType"></param>
|
||||
/// <param name="by"></param>
|
||||
/// <param name="get"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SortAndStore(RedisKey destination, RedisKey key, long skip = 0L, long take = -1L, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortAndStore, destination, key, skip, take, order, sortType, by, get, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 添加一个元素到有序集合 如果存在则修改其对应的分值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="score"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>是否添加成功</returns>
|
||||
public bool SortedSetAdd(RedisKey key, RedisValue member, double score, CommandFlags flags) {
|
||||
return FDBOpera(db.SortedSetAdd, key, member, score, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="score"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool SortedSetAdd(RedisKey key, RedisValue member, double score, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetAdd, key, member, score, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SortedSetAdd(RedisKey key, SortedSetEntry[] values, CommandFlags flags) {
|
||||
return FDBOpera(db.SortedSetAdd, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SortedSetAdd(RedisKey key, SortedSetEntry[] values, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetAdd, key, values, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="first"></param>
|
||||
/// <param name="second"></param>
|
||||
/// <param name="aggregate"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SortedSetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetCombineAndStore, operation, destination, first, second, aggregate, flags);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="weights"></param>
|
||||
/// <param name="aggregate"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SortedSetCombineAndStore(SetOperation operation, RedisKey destination, RedisKey[] keys, double[] weights = null, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetCombineAndStore, operation, destination, keys, weights, aggregate, flags);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public double SortedSetDecrement(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetDecrement, key, member, value, flags);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public double SortedSetIncrement(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetIncrement, key, member, value, flags);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="min"></param>
|
||||
/// <param name="max"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SortedSetLength(RedisKey key, double min = double.NegativeInfinity, double max = double.PositiveInfinity, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetLength, key, min, max, exclude, flags);
|
||||
}
|
||||
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="min"></param>
|
||||
/// <param name="max"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SortedSetLengthByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetLengthByValue, key, min, max, exclude, flags);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] SortedSetRangeByRank(RedisKey key, long start = 0L, long stop = -1L, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetRangeByRank, key, start, stop, order, flags);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public SortedSetEntry[] SortedSetRangeByRankWithScores(RedisKey key, long start = 0L, long stop = -1L, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetRangeByRankWithScores, key, start, stop, order, flags);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="skip"></param>
|
||||
/// <param name="take"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] SortedSetRangeByScore(RedisKey key, double start = double.NegativeInfinity, double stop = double.PositiveInfinity, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0L, long take = -1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetRangeByScore, key, start, stop, exclude, order, skip, take, flags);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="skip"></param>
|
||||
/// <param name="take"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public SortedSetEntry[] SortedSetRangeByScoreWithScores(RedisKey key, double start = double.NegativeInfinity, double stop = double.PositiveInfinity, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0L, long take = -1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetRangeByScoreWithScores, key, start, stop, exclude, order, skip, take, flags);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="min"></param>
|
||||
/// <param name="max"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="skip"></param>
|
||||
/// <param name="take"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] SortedSetRangeByValue(RedisKey key, RedisValue min = default(RedisValue), RedisValue max = default(RedisValue), Exclude exclude = Exclude.None, long skip = 0L, long take = -1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetRangeByValue, key, min, max, exclude, skip, take, flags);
|
||||
}
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long? SortedSetRank(RedisKey key, RedisValue member, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetRank, key, member, order, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool SortedSetRemove(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetRemove, key, member, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="members"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SortedSetRemove(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetRemove, key, members, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SortedSetRemoveRangeByRank(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetRemoveRangeByRank, key, start, stop, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SortedSetRemoveRangeByScore(RedisKey key, double start, double stop, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetRemoveRangeByScore, key, start, stop, exclude, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="min"></param>
|
||||
/// <param name="max"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long SortedSetRemoveRangeByValue(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetRemoveRangeByValue, key, min, max, exclude, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="pattern"></param>
|
||||
/// <param name="pageSize"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public IEnumerable<SortedSetEntry> SortedSetScan(RedisKey key, RedisValue pattern, int pageSize, CommandFlags flags) {
|
||||
return FDBOpera(db.SortedSetScan, key, pattern, pageSize, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="pattern"></param>
|
||||
/// <param name="pageSize"></param>
|
||||
/// <param name="cursor"></param>
|
||||
/// <param name="pageOffset"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public IEnumerable<SortedSetEntry> SortedSetScan(RedisKey key, RedisValue pattern = default(RedisValue), int pageSize = 10, long cursor = 0L, int pageOffset = 0, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetScan, key, pattern, pageSize, cursor, pageOffset, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public double? SortedSetScore(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.SortedSetScore, key, member, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 字符串追加
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long StringAppend(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringAppend, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 某范围二进制中出现1的次数
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="end"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long StringBitCount(RedisKey key, long start = 0L, long end = -1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringBitCount, key, start, end, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// first 与 second做位运算,结果放在destination中
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="first"></param>
|
||||
/// <param name="second"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>返回运算后的字符串长度</returns>
|
||||
public long StringBitOperation(Bitwise operation, RedisKey destination, RedisKey first, RedisKey second = default(RedisKey), CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringBitOperation, operation, destination, first, second, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 一堆值做位运算。
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long StringBitOperation(Bitwise operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringBitOperation, operation, destination, keys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取二进制中第一次出现1或0的位置
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="bit"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="end"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>返回其位置</returns>
|
||||
public long StringBitPosition(RedisKey key, bool bit, long start = 0L, long end = -1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringBitPosition, key, bit, start, end, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 数值减去一个值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value">减去的值</param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>返回减去后得到的结果</returns>
|
||||
public long StringDecrement(RedisKey key, long value = 1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringDecrement, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 数值减去一个值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value">减去的值</param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>返回减去后得到的结果</returns>
|
||||
public double StringDecrement(RedisKey key, double value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringDecrement, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取String的值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue StringGet(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringGet, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取一组String的值
|
||||
/// </summary>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue[] StringGet(RedisKey[] keys, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringGet, keys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取某位二进制的值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="offset"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>返回原来的值</returns>
|
||||
public bool StringGetBit(RedisKey key, long offset, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringGetBit, key, offset, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取String的一个范围
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="end"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue StringGetRange(RedisKey key, long start, long end, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringGetRange, key, start, end, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取原来的String 并用新值替换
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValue StringGetSet(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringGetSet, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取String以及key的过期时间
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public RedisValueWithExpiry StringGetWithExpiry(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringGetWithExpiry, key, flags);
|
||||
}
|
||||
/// <summary>
|
||||
/// 数值增加一个值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long StringIncrement(RedisKey key, long value = 1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringIncrement, key, value, flags);
|
||||
}
|
||||
/// <summary>
|
||||
/// 数值增加一个值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public double StringIncrement(RedisKey key, double value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringIncrement, key, value, flags);
|
||||
}
|
||||
/// <summary>
|
||||
/// 获取字符串长
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public long StringLength(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringLength, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置值字符串
|
||||
/// </summary>
|
||||
/// <param name="key">字符串的键</param>
|
||||
/// <param name="value">字符串的值</param>
|
||||
/// <param name="expiry">过期时间</param>
|
||||
/// <param name="when">那种情况设置值</param>
|
||||
/// <param name="flags">用于操作的标记</param>
|
||||
/// <returns>true 设置成功 false设置失败</returns>
|
||||
/// <remarks>https://redis.io/commands/set</remarks>
|
||||
public bool StringSet(RedisKey key, RedisValue value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringSet, key, value, expiry, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置一组字符串值
|
||||
/// </summary>
|
||||
/// <param name="values">字符串键值对</param>
|
||||
/// <param name="when">设置的条件,要么都通过,要么都不通过</param>
|
||||
/// <param name="flags">操作的类型</param>
|
||||
/// <returns>true 表示成功 false表示失败</returns>
|
||||
public bool StringSet(KeyValuePair<RedisKey, RedisValue>[] values, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringSet, values, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 设置某位二进制的值
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="offset"></param>
|
||||
/// <param name="bit"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>返回二进制中原来的值</returns>
|
||||
public bool StringSetBit(RedisKey key, long offset, bool bit, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringSetBit, key, offset, bit, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 从偏移量offset 开始 使用 value填充,如果原来没有值或者原来的长度小于 offset ,那从原来的字符串开始到offset使用'\0'字符填充。
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="offset"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns>修改后string的长度</returns>
|
||||
public RedisValue StringSetRange(RedisKey key, long offset, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.StringSetRange, key, offset, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> DebugObjectAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.DebugObjectAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="longitude"></param>
|
||||
/// <param name="latitude"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> GeoAddAsync(RedisKey key, double longitude, double latitude, RedisValue member, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.GeoAddAsync, key, longitude, latitude, member, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> GeoAddAsync(RedisKey key, GeoEntry value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.GeoAddAsync, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> GeoAddAsync(RedisKey key, GeoEntry[] values, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.GeoAddAsync, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> GeoRemoveAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.GeoRemoveAsync, key, member, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member1"></param>
|
||||
/// <param name="member2"></param>
|
||||
/// <param name="unit"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<double?> GeoDistanceAsync(RedisKey key, RedisValue member1, RedisValue member2, GeoUnit unit = GeoUnit.Meters, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.GeoDistanceAsync, key, member1, member2, unit, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="members"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<string[]> GeoHashAsync(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.GeoHashAsync, key, members, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<string> GeoHashAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.GeoHashAsync, key, member, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="members"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<GeoPosition?[]> GeoPositionAsync(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.GeoPositionAsync, key, members, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<GeoPosition?> GeoPositionAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.GeoPositionAsync, key, member, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="radius"></param>
|
||||
/// <param name="unit"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<GeoRadiusResult[]> GeoRadiusAsync(RedisKey key, RedisValue member, double radius, GeoUnit unit = GeoUnit.Meters, int count = -1, Order? order = null, GeoRadiusOptions options = GeoRadiusOptions.Default, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.GeoRadiusAsync, key, member, radius, unit, count, order, options, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="longitude"></param>
|
||||
/// <param name="latitude"></param>
|
||||
/// <param name="radius"></param>
|
||||
/// <param name="unit"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="options"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<GeoRadiusResult[]> GeoRadiusAsync(RedisKey key, double longitude, double latitude, double radius, GeoUnit unit = GeoUnit.Meters, int count = -1, Order? order = null, GeoRadiusOptions options = GeoRadiusOptions.Default, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.GeoRadiusAsync, key, longitude, latitude, radius, unit, count, order, options, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> HashDecrementAsync(RedisKey key, RedisValue hashField, long value = 1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashDecrementAsync, key, hashField, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<double> HashDecrementAsync(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashDecrementAsync, key, hashField, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> HashDeleteAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashDeleteAsync, key, hashField, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashFields"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> HashDeleteAsync(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashDeleteAsync, key, hashFields, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> HashExistsAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashExistsAsync, key, hashField, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<HashEntry[]> HashGetAllAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashGetAllAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> HashGetAsync(RedisKey key, RedisValue hashField, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashGetAsync, key, hashField, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashFields"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> HashGetAsync(RedisKey key, RedisValue[] hashFields, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashGetAsync, key, hashFields, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> HashIncrementAsync(RedisKey key, RedisValue hashField, long value = 1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashIncrementAsync, key, hashField, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<double> HashIncrementAsync(RedisKey key, RedisValue hashField, double value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashIncrementAsync, key, hashField, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> HashKeysAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashKeysAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> HashLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashLengthAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashFields"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task HashSetAsync(RedisKey key, HashEntry[] hashFields, CommandFlags flags = CommandFlags.None) {
|
||||
return ADBOperaAsync(db.HashSetAsync, key, hashFields, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="hashField"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> HashSetAsync(RedisKey key, RedisValue hashField, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashSetAsync, key, hashField, value, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> HashValuesAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HashValuesAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> HyperLogLogAddAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HyperLogLogAddAsync, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> HyperLogLogAddAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HyperLogLogAddAsync, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> HyperLogLogLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HyperLogLogLengthAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> HyperLogLogLengthAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.HyperLogLogLengthAsync, keys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="first"></param>
|
||||
/// <param name="second"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task HyperLogLogMergeAsync(RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) {
|
||||
return ADBOperaAsync(db.HyperLogLogMergeAsync, destination, first, second, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="sourceKeys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task HyperLogLogMergeAsync(RedisKey destination, RedisKey[] sourceKeys, CommandFlags flags = CommandFlags.None) {
|
||||
return ADBOperaAsync(db.HyperLogLogMergeAsync, destination, sourceKeys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<EndPoint> IdentifyEndpointAsync(RedisKey key = default(RedisKey), CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.IdentifyEndpointAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public bool IsConnected(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.IsConnected, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> KeyDeleteAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.KeyDeleteAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> KeyDeleteAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.KeyDeleteAsync, keys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<byte[]> KeyDumpAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.KeyDumpAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> KeyExistsAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.KeyExistsAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="expiry"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> KeyExpireAsync(RedisKey key, TimeSpan? expiry, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.KeyExpireAsync, key, expiry, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="expiry"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> KeyExpireAsync(RedisKey key, DateTime? expiry, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.KeyExpireAsync, key, expiry, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="toServer"></param>
|
||||
/// <param name="toDatabase"></param>
|
||||
/// <param name="timeoutMilliseconds"></param>
|
||||
/// <param name="migrateOptions"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task KeyMigrateAsync(RedisKey key, EndPoint toServer, int toDatabase = 0, int timeoutMilliseconds = 0, MigrateOptions migrateOptions = MigrateOptions.None, CommandFlags flags = CommandFlags.None) {
|
||||
return ADBOperaAsync(db.KeyMigrateAsync, key, toServer, toDatabase, timeoutMilliseconds, migrateOptions, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="database"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> KeyMoveAsync(RedisKey key, int database, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.KeyMoveAsync, key, database, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> KeyPersistAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.KeyPersistAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisKey> KeyRandomAsync(CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.KeyRandomAsync, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="newKey"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> KeyRenameAsync(RedisKey key, RedisKey newKey, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.KeyRenameAsync, key, newKey, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="expiry"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task KeyRestoreAsync(RedisKey key, byte[] value, TimeSpan? expiry = null, CommandFlags flags = CommandFlags.None) {
|
||||
return ADBOperaAsync(db.KeyRestoreAsync, key, value, expiry, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<TimeSpan?> KeyTimeToLiveAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.KeyTimeToLiveAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisType> KeyTypeAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.KeyTypeAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> ListGetByIndexAsync(RedisKey key, long index, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListGetByIndexAsync, key, index, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="pivot"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> ListInsertAfterAsync(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListInsertAfterAsync, key, pivot, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="pivot"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> ListInsertBeforeAsync(RedisKey key, RedisValue pivot, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListInsertBeforeAsync, key, pivot, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> ListLeftPopAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListLeftPopAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> ListLeftPushAsync(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListLeftPushAsync, key, value, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> ListLeftPushAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListLeftPushAsync, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> ListLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListLengthAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> ListRangeAsync(RedisKey key, long start = 0L, long stop = -1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListRangeAsync, key, start, stop, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> ListRemoveAsync(RedisKey key, RedisValue value, long count = 0L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListRemoveAsync, key, value, count, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> ListRightPopAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListRightPopAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> ListRightPopLeftPushAsync(RedisKey source, RedisKey destination, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListRightPopLeftPushAsync, source, destination, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> ListRightPushAsync(RedisKey key, RedisValue value, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListRightPushAsync, key, value, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> ListRightPushAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ListRightPushAsync, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="index"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task ListSetByIndexAsync(RedisKey key, long index, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return ADBOperaAsync(db.ListSetByIndexAsync, key, index, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task ListTrimAsync(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None) {
|
||||
return ADBOperaAsync(db.ListTrimAsync, key, start, stop, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="expiry"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> LockExtendAsync(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.LockExtendAsync, key, value, expiry, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> LockQueryAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.LockQueryAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> LockReleaseAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.LockReleaseAsync, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="expiry"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> LockTakeAsync(RedisKey key, RedisValue value, TimeSpan expiry, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.LockTakeAsync, key, value, expiry, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="channel"></param>
|
||||
/// <param name="message"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> PublishAsync(RedisChannel channel, RedisValue message, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.PublishAsync, channel, message, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="script"></param>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisResult> ScriptEvaluateAsync(string script, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ScriptEvaluateAsync, script, keys, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="hash"></param>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisResult> ScriptEvaluateAsync(byte[] hash, RedisKey[] keys = null, RedisValue[] values = null, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ScriptEvaluateAsync, hash, keys, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="script"></param>
|
||||
/// <param name="parameters"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisResult> ScriptEvaluateAsync(LuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ScriptEvaluateAsync, script, parameters, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="script"></param>
|
||||
/// <param name="parameters"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisResult> ScriptEvaluateAsync(LoadedLuaScript script, object parameters = null, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.ScriptEvaluateAsync, script, parameters, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> SetAddAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetAddAsync, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SetAddAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetAddAsync, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="first"></param>
|
||||
/// <param name="second"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetCombineAndStoreAsync, operation, destination, first, second, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetCombineAndStoreAsync, operation, destination, keys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="first"></param>
|
||||
/// <param name="second"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> SetCombineAsync(SetOperation operation, RedisKey first, RedisKey second, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetCombineAsync, operation, first, second, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> SetCombineAsync(SetOperation operation, RedisKey[] keys, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetCombineAsync, operation, keys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> SetContainsAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetContainsAsync, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SetLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetLengthAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> SetMembersAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetMembersAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="source"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> SetMoveAsync(RedisKey source, RedisKey destination, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetMoveAsync, source, destination, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> SetPopAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetPopAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> SetRandomMemberAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetRandomMemberAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="count"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> SetRandomMembersAsync(RedisKey key, long count, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetRandomMembersAsync, key, count, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> SetRemoveAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetRemoveAsync, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SetRemoveAsync(RedisKey key, RedisValue[] values, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SetRemoveAsync, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="skip"></param>
|
||||
/// <param name="take"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="sortType"></param>
|
||||
/// <param name="by"></param>
|
||||
/// <param name="get"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SortAndStoreAsync(RedisKey destination, RedisKey key, long skip = 0L, long take = -1L, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortAndStoreAsync, destination, key, skip, take, order, sortType, by, get, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="skip"></param>
|
||||
/// <param name="take"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="sortType"></param>
|
||||
/// <param name="by"></param>
|
||||
/// <param name="get"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> SortAsync(RedisKey key, long skip = 0L, long take = -1L, Order order = Order.Ascending, SortType sortType = SortType.Numeric, RedisValue by = default(RedisValue), RedisValue[] get = null, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortAsync, key, skip, take, order, sortType, by, get, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="score"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> SortedSetAddAsync(RedisKey key, RedisValue member, double score, CommandFlags flags) {
|
||||
return FDBOperaAsync(db.SortedSetAddAsync, key, member, score, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="score"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> SortedSetAddAsync(RedisKey key, RedisValue member, double score, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetAddAsync, key, member, score, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SortedSetAddAsync(RedisKey key, SortedSetEntry[] values, CommandFlags flags) {
|
||||
return FDBOperaAsync(db.SortedSetAddAsync, key, values, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SortedSetAddAsync(RedisKey key, SortedSetEntry[] values, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetAddAsync, key, values, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="first"></param>
|
||||
/// <param name="second"></param>
|
||||
/// <param name="aggregate"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SortedSetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey first, RedisKey second, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetCombineAndStoreAsync, operation, destination, first, second, aggregate, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="weights"></param>
|
||||
/// <param name="aggregate"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SortedSetCombineAndStoreAsync(SetOperation operation, RedisKey destination, RedisKey[] keys, double[] weights = null, Aggregate aggregate = Aggregate.Sum, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetCombineAndStoreAsync, operation, destination, keys, weights, aggregate, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<double> SortedSetDecrementAsync(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetDecrementAsync, key, member, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<double> SortedSetIncrementAsync(RedisKey key, RedisValue member, double value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetIncrementAsync, key, member, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="min"></param>
|
||||
/// <param name="max"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SortedSetLengthAsync(RedisKey key, double min = double.NegativeInfinity, double max = double.PositiveInfinity, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetLengthAsync, key, min, max, exclude, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="min"></param>
|
||||
/// <param name="max"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SortedSetLengthByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetLengthByValueAsync, key, min, max, exclude, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> SortedSetRangeByRankAsync(RedisKey key, long start = 0L, long stop = -1L, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetRangeByRankAsync, key, start, stop, order, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<SortedSetEntry[]> SortedSetRangeByRankWithScoresAsync(RedisKey key, long start = 0L, long stop = -1L, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetRangeByRankWithScoresAsync, key, start, stop, order, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="skip"></param>
|
||||
/// <param name="take"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> SortedSetRangeByScoreAsync(RedisKey key, double start = double.NegativeInfinity, double stop = double.PositiveInfinity, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0L, long take = -1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetRangeByScoreAsync, key, start, stop, exclude, order, skip, take, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="skip"></param>
|
||||
/// <param name="take"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<SortedSetEntry[]> SortedSetRangeByScoreWithScoresAsync(RedisKey key, double start = double.NegativeInfinity, double stop = double.PositiveInfinity, Exclude exclude = Exclude.None, Order order = Order.Ascending, long skip = 0L, long take = -1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetRangeByScoreWithScoresAsync, key, start, stop, exclude, order, skip, take, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="min"></param>
|
||||
/// <param name="max"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="skip"></param>
|
||||
/// <param name="take"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> SortedSetRangeByValueAsync(RedisKey key, RedisValue min = default(RedisValue), RedisValue max = default(RedisValue), Exclude exclude = Exclude.None, long skip = 0L, long take = -1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetRangeByValueAsync, key, min, max, exclude, skip, take, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="order"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long?> SortedSetRankAsync(RedisKey key, RedisValue member, Order order = Order.Ascending, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetRankAsync, key, member, order, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> SortedSetRemoveAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetRemoveAsync, key, member, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="members"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SortedSetRemoveAsync(RedisKey key, RedisValue[] members, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetRemoveAsync, key, members, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SortedSetRemoveRangeByRankAsync(RedisKey key, long start, long stop, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetRemoveRangeByRankAsync, key, start, stop, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="stop"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SortedSetRemoveRangeByScoreAsync(RedisKey key, double start, double stop, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetRemoveRangeByScoreAsync, key, start, stop, exclude, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="min"></param>
|
||||
/// <param name="max"></param>
|
||||
/// <param name="exclude"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> SortedSetRemoveRangeByValueAsync(RedisKey key, RedisValue min, RedisValue max, Exclude exclude = Exclude.None, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetRemoveRangeByValueAsync, key, min, max, exclude, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="member"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<double?> SortedSetScoreAsync(RedisKey key, RedisValue member, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.SortedSetScoreAsync, key, member, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> StringAppendAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringAppendAsync, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="end"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> StringBitCountAsync(RedisKey key, long start = 0L, long end = -1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringBitCountAsync, key, start, end, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="first"></param>
|
||||
/// <param name="second"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> StringBitOperationAsync(Bitwise operation, RedisKey destination, RedisKey first, RedisKey second = default(RedisKey), CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringBitOperationAsync, operation, destination, first, second, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="operation"></param>
|
||||
/// <param name="destination"></param>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> StringBitOperationAsync(Bitwise operation, RedisKey destination, RedisKey[] keys, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringBitOperationAsync, operation, destination, keys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="bit"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="end"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> StringBitPositionAsync(RedisKey key, bool bit, long start = 0L, long end = -1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringBitPositionAsync, key, bit, start, end, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> StringDecrementAsync(RedisKey key, long value = 1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringDecrementAsync, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<double> StringDecrementAsync(RedisKey key, double value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringDecrementAsync, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> StringGetAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringGetAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="keys"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue[]> StringGetAsync(RedisKey[] keys, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringGetAsync, keys, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="offset"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> StringGetBitAsync(RedisKey key, long offset, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringGetBitAsync, key, offset, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="start"></param>
|
||||
/// <param name="end"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> StringGetRangeAsync(RedisKey key, long start, long end, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringGetRangeAsync, key, start, end, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> StringGetSetAsync(RedisKey key, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringGetSetAsync, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValueWithExpiry> StringGetWithExpiryAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringGetWithExpiryAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> StringIncrementAsync(RedisKey key, long value = 1L, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringIncrementAsync, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<double> StringIncrementAsync(RedisKey key, double value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringIncrementAsync, key, value, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<long> StringLengthAsync(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringLengthAsync, key, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="expiry"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> StringSetAsync(RedisKey key, RedisValue value, TimeSpan? expiry = null, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringSetAsync, key, value, expiry, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="values"></param>
|
||||
/// <param name="when"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> StringSetAsync(KeyValuePair<RedisKey, RedisValue>[] values, When when = When.Always, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringSetAsync, values, when, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="offset"></param>
|
||||
/// <param name="bit"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<bool> StringSetBitAsync(RedisKey key, long offset, bool bit, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringSetBitAsync, key, offset, bit, flags);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="offset"></param>
|
||||
/// <param name="value"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public Task<RedisValue> StringSetRangeAsync(RedisKey key, long offset, RedisValue value, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOperaAsync(db.StringSetRangeAsync, key, offset, value, flags);
|
||||
}
|
||||
}
|
||||
}
|
||||
35
GameDAL/db/redis/RedisDataBaseExtensions.cs
Normal file
35
GameDAL/db/redis/RedisDataBaseExtensions.cs
Normal file
@ -0,0 +1,35 @@
|
||||
/*
|
||||
* 由SharpDevelop创建。
|
||||
* 用户: Administrator
|
||||
* 日期: 2018-12-07
|
||||
* 时间: 15:34
|
||||
*
|
||||
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
|
||||
*/
|
||||
using System;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Server.DB.Redis {
|
||||
public partial class IDatabaseProxy {
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="key"></param>
|
||||
/// <param name="flags"></param>
|
||||
/// <returns></returns>
|
||||
public TimeSpan? KeyIdleTime(RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
return FDBOpera(db.KeyIdleTime, key, flags);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
public static class RedisDataBaseExtensions {
|
||||
static readonly RedisValue IDLETIME = "IDLETIME";
|
||||
public static TimeSpan? KeyIdleTime(this IDatabase db, RedisKey key, CommandFlags flags = CommandFlags.None) {
|
||||
var rabbitdb = db as RedisDatabase;
|
||||
var msg = Message.Create(db.Database, flags, RedisCommand.OBJECT, IDLETIME, key);
|
||||
return rabbitdb.ExecuteSync(msg, ResultProcessor.TimeSpanFromSeconds);
|
||||
}
|
||||
}
|
||||
}
|
||||
181
GameDAL/db/redis/RedisDictionary.cs
Normal file
181
GameDAL/db/redis/RedisDictionary.cs
Normal file
@ -0,0 +1,181 @@
|
||||
/*
|
||||
* 由SharpDevelop创建。
|
||||
* 用户: Administrator
|
||||
* 日期: 2019-01-02
|
||||
* 时间: 13:07
|
||||
*
|
||||
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
|
||||
*/
|
||||
using System;
|
||||
using Server.Data.Module;
|
||||
using GameData;
|
||||
|
||||
namespace Server.DB.Redis
|
||||
{
|
||||
/// <summary>
|
||||
/// redis字典
|
||||
/// </summary>
|
||||
public static class RedisDictionary
|
||||
{
|
||||
/// <summary>
|
||||
/// 配置所在的redis数据库
|
||||
/// </summary>
|
||||
public const int configDb = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 缓存数据库
|
||||
/// </summary>
|
||||
public const int cachedb = 1;
|
||||
|
||||
/// <summary>
|
||||
/// 版本数据库
|
||||
/// </summary>
|
||||
public const int clientverdb = 2;
|
||||
|
||||
/// <summary>
|
||||
/// 聊天缓存的消息数据
|
||||
/// </summary>
|
||||
public const int chatmessagedb = 3;
|
||||
|
||||
/// <summary>
|
||||
/// 玩家状态存储库
|
||||
/// </summary>
|
||||
public const int PlayerState = 4;
|
||||
|
||||
/// <summary>
|
||||
/// 统计库-6381
|
||||
/// </summary>
|
||||
public const int Statistics = 6;
|
||||
|
||||
/// <summary>
|
||||
/// 游戏服务器细节信息
|
||||
/// </summary>
|
||||
public const string GameSerinfoDetail = "GameSerinfoDetail";
|
||||
|
||||
/// <summary>
|
||||
/// 所有的服务器配置
|
||||
/// </summary>
|
||||
public const string AllServerConfig = "AllServerConfig";
|
||||
|
||||
public const string AllServerConfigVer = "AllServerConfig:ver";
|
||||
|
||||
/// <summary>
|
||||
/// 存储配置服务器用的Key todo 这个key废弃了 1 号库
|
||||
/// </summary>
|
||||
public const string GameConfigServerLuBanKey = "GameConfigServerLuBan";
|
||||
|
||||
/// <summary>
|
||||
/// 玩家活动数据
|
||||
/// </summary>
|
||||
public const string ActivityPlayerData = "Game:ActivityPlayerData:{0}";
|
||||
|
||||
#region 模块数据表
|
||||
|
||||
/// <summary>
|
||||
/// 权重
|
||||
/// </summary>
|
||||
public const string weightsField = "Weights";
|
||||
|
||||
/// <summary>
|
||||
/// 是否死亡
|
||||
/// </summary>
|
||||
public const string dieField = "isDie";
|
||||
|
||||
/// <summary>
|
||||
/// 模块数据表
|
||||
/// </summary>
|
||||
public const string tbModuleData = "tbModuleData";
|
||||
|
||||
/// <summary>
|
||||
/// 节点名称
|
||||
/// </summary>
|
||||
public const string moduleNames = "nodenames";
|
||||
|
||||
#endregion
|
||||
|
||||
#region ModuleOnlineTab
|
||||
|
||||
/// <summary>
|
||||
/// 在线模块编号表
|
||||
/// </summary>
|
||||
public const string tbModuleNum = "tbModuleNum";
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="util"></param>
|
||||
/// <returns></returns>
|
||||
public static string dbModuleNumKey(ModuleUtile util){
|
||||
return tbModuleData + "." + util.id;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
///
|
||||
/// </summary>
|
||||
/// <param name="ModuleUtileId"></param>
|
||||
/// <returns></returns>
|
||||
public static string dbModuleNumKey(int ModuleUtileId){
|
||||
return tbModuleData + "." + ModuleUtileId;
|
||||
}
|
||||
|
||||
#endregion
|
||||
|
||||
/// <summary>
|
||||
/// 模块名称表
|
||||
/// </summary>
|
||||
public const string tbModuleName = "Game:tbModuleName";
|
||||
|
||||
/// <summary>
|
||||
/// 游戏信息表名 存储gameid gamesty
|
||||
/// </summary>
|
||||
public const string GameInfoTabName = "Game:NodeInfo:GamesInfo";
|
||||
|
||||
|
||||
#region friendRoom
|
||||
/// <summary>
|
||||
/// 上次创建房间的时间 数据类型hash key1 lastCreateRoomTime 上次的创建时间 key2 lastRoomNum 上次的房间号
|
||||
/// </summary>
|
||||
public const string lastRoomNum = "Game:FriendRoom:lastRoomNum";
|
||||
|
||||
/// <summary>
|
||||
/// 上次创建房间的时间
|
||||
/// </summary>
|
||||
public const string lastCreatRoomTime = "Game:FriendRoom:lastDateTime";
|
||||
|
||||
/// <summary>
|
||||
/// 上次创建房间的房间号
|
||||
/// </summary>
|
||||
public const string lastCreateRoomNum = "Game:FriendRoom:lastRoomNum";
|
||||
|
||||
/// <summary>
|
||||
/// 房间号标记 数据类型 string key=roomTag+"roomNum"; 存储的房间唯一码
|
||||
/// </summary>
|
||||
public const string roomTag = "Game:FriendRoom:Room.";
|
||||
|
||||
/// <summary>
|
||||
/// 玩家的房间号以及唯一码信息
|
||||
/// </summary>
|
||||
public const string PlayerRoomNum = "Game:FriendRoom:Player:";
|
||||
|
||||
/// <summary>
|
||||
/// 房间其他字段
|
||||
/// key1 friendRoomField+"唯一吗" hash 房间详细数据
|
||||
/// key3 friendRoomField+"唯一吗."+"每局详情_idx" hash 存储每局分数
|
||||
/// </summary>
|
||||
public const string friendRoomField = "Game:FriendRoom:weiyima:";
|
||||
|
||||
/// <summary>
|
||||
/// 朋友房战斗数据_用来恢复用的
|
||||
/// </summary>
|
||||
public const string friendRoomfightdata = "Game:FriendRoom:data:";
|
||||
|
||||
/// <summary>
|
||||
/// 朋友房战斗记_用来回放用的
|
||||
/// </summary>
|
||||
public const string friendRoomfightRecord = "Game:FriendRoom:Record:";
|
||||
|
||||
#endregion
|
||||
|
||||
|
||||
}
|
||||
}
|
||||
6
GameDAL/db/redis/RedisTable.txt
Normal file
6
GameDAL/db/redis/RedisTable.txt
Normal file
@ -0,0 +1,6 @@
|
||||
1.客户端版本对应的服务器版本表: ClientVer.[ClientVer] style: Hash
|
||||
2.模块的数据表: tbModuleData.[ver].[id].[num] style: Hash
|
||||
3.模块的名称表: tbModuleName style Hash
|
||||
4.某类模块的在线版本表: tbModuleNum.[id] style:List
|
||||
5.某类某版本模块的在线模块编号表: tbModuleNum.[id].[ver] style:List
|
||||
6.玩家数据表: OnlinePlayers.[id] style:Hash;
|
||||
453
GameDAL/db/redis/redisManager.cs
Normal file
453
GameDAL/db/redis/redisManager.cs
Normal file
@ -0,0 +1,453 @@
|
||||
/*
|
||||
* 由SharpDevelop创建。
|
||||
* 用户: Administrator
|
||||
* 日期: 2018-09-14
|
||||
* 时间: 15:16
|
||||
*
|
||||
* 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
|
||||
*/
|
||||
|
||||
using System;
|
||||
using StackExchange.Redis;
|
||||
using System.Collections.Generic;
|
||||
using MrWu.Debug;
|
||||
using System.Linq;
|
||||
using GameData;
|
||||
using Server.Config;
|
||||
|
||||
namespace Server.DB.Redis
|
||||
{
|
||||
/// <summary>
|
||||
/// 数据库类型
|
||||
/// </summary>
|
||||
public enum DbStyle
|
||||
{
|
||||
/// <summary>
|
||||
/// 主库
|
||||
/// </summary>
|
||||
main,
|
||||
|
||||
/// <summary>
|
||||
/// 比赛
|
||||
/// </summary>
|
||||
bisai
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// redis数据库管理
|
||||
/// </summary>
|
||||
public class redisManager
|
||||
{
|
||||
/* redis 命令大全
|
||||
* del key 删除键
|
||||
* dump key 序列化key 返回序列化的值
|
||||
* exists key 检查key是否存在
|
||||
* exipire key seconds 设置过期的时间
|
||||
* pexipire key milliseconds 设置过期时间毫秒
|
||||
* keys keyspattem 查找给定格式的key
|
||||
* move key db 将key移动到给定数据库db中
|
||||
* persist key 移除key的过期时间
|
||||
* pttl key 返回剩余过期时间以毫秒计
|
||||
* ttl key 返回剩余的过期时间以秒计
|
||||
* randomkey 随机返回一个key
|
||||
* rename key newkey 修改key的名称
|
||||
* renamenx key newkey 仅当newkey不存在时,将key改名为newkey
|
||||
* type key 返回key所存储的值类型
|
||||
*
|
||||
* 字符串类型的命令
|
||||
* set key value 设置key 字符串值
|
||||
* get key 获取key的字符串值
|
||||
* getrange key start end 获取key的字符串一段值
|
||||
* getset key value 从新设置key的值 并返回原来的值
|
||||
* getbit key offset ------
|
||||
* strlen key 返回key存储的字符串长度
|
||||
* mset key1 value1 key2 value2 设置一个或多个字符串的值
|
||||
* msetnx key1 value1 key2 value2 设置一个活多个字符串的值不如果存在key则不设置
|
||||
* setex key seconds value 将值value关联到key,并将key的过期时间设为seconds秒
|
||||
* psetex key millseconds value 将value关联到key,并将key的过期时间设为milliseconds毫秒
|
||||
* incr key 将key中存储的数字值增一 只能value是整数才能使用 并返回存储后的值
|
||||
* incrby key increment 将key中存储的数字值增加increment 并返回存储后的值
|
||||
* incrbyfloat key increment 将key中存储的数字值增加increment的浮点值 并返回存储后的值 存在误差
|
||||
* decr key 将key中存储的数字减一 只有value是数字型的时候才能使用 并返回存储后的值
|
||||
* decrby key decrement 将key中存储的数字值减少decrement 并返回存储后的值
|
||||
* append key value 如果key已经存在并且是一个字符串 append 命令将指定的value追加到key原来的值的末尾 并返回追加后的字符串长度
|
||||
*
|
||||
* hash类型的命令
|
||||
* hmset key hashkey1 value1 hashkey2 vlaue2 将新的hash字段插入到hash表中
|
||||
* hget key hashkey 获取hash中的key
|
||||
* hdel key hashkey1 hashkey2 删除一个或多个hash字段
|
||||
* hexists key filed 查询哈希表中是否存在filed
|
||||
* hgetall key 获取在哈希表中指定的key的所有字段和值
|
||||
* hincrby key field increment 为哈希表中key 的值增加1
|
||||
* hincrbyfloat key field increment 为哈希表中key 的值浮点值增量
|
||||
* hkeys key 获取所有的哈希表中key值
|
||||
* hlen key 获取哈希表中字段的数量
|
||||
* hmget key field1 field2 获取给定字段的值
|
||||
* hset key field vlaue 如果hash表中存在key则 修改key的值 如果不存在则添加
|
||||
* hsernx key filed value 只有在hash表中不存在field字段时才设置值
|
||||
* hvals key 获取hash表中的所有值
|
||||
*
|
||||
* List 列表类型命令
|
||||
* lpush key value1 value2 将值插入到key列表中的头部
|
||||
* blpop key key1 timeout 优先取key中的值如果key中有值返回第一个值 如果key中没有值取key1中的值 如果key1也没有值 则会等待timeout后超时
|
||||
* brpop key key1 timeout 获取最后一个值
|
||||
* brpoplpush source destination timeout 从source 中取出一个值并插入到destination 中 如果没有值知道timeout才停止
|
||||
* lindex key index 通过索引获取表中的元素
|
||||
* linsert key before value
|
||||
* lpop key 移出并获取列表中的第一个元素
|
||||
* lpush key value1 value2 将值插入到已存在key列表中的头部
|
||||
* lpushx key value 将一个值插入到已存在key表中的头部
|
||||
* lrange key start end 获取列表中指定范围的内的元素
|
||||
* lrem key count value count>0表示从头向尾搜索,移除value相等的元素 数量为count count<0表示从尾巴向头搜索,移除value相等的元素 数量为count的绝对值 count = 0 时移除列表中所有的value相等的元素
|
||||
* lset key index value 设置列表index上的值
|
||||
* ltrim key satrt stop 指定列表保留的元素区间,不在区间内的元素将会被删除
|
||||
* rpop key 移除并获取列表中的最后一个元素\
|
||||
* rpoplpush source destination 移除source中的最后一个元素并将该元素添加到destination表中
|
||||
* rpush key value1 value2 将值插入到列表的尾部
|
||||
* rpushx key value 向已存在的表中添加值
|
||||
*
|
||||
* Set 集合命令
|
||||
* sadd key menber1 menber2 向集合中添加一个或多个成员
|
||||
* scard key 获取集合中的成员数量
|
||||
* sdiff key key1 返回所有集合的差集
|
||||
* sdiffstore destination key key1 返回给定所有集合的差集 并存储到destination 中
|
||||
* sinter key key1 缩回所有集合的交集
|
||||
* sindterstore destination key key1 返回所有集合的交集 并存储到destination中
|
||||
* sismember key member 判断member元素是否是集合key的成员
|
||||
* smemers key 返回集合中的所有成员
|
||||
* smove source destination member 将member元素从source集合移动到destination集合中
|
||||
* spop key 移除并返回集合中的一个随机元素
|
||||
* srandmember key count 返回集合中的一个或多个随机元素
|
||||
* serm key member member1 移除集合中的一个或多个成员
|
||||
* sunion key key1 返回所有给定集合的并集
|
||||
* sunionstore destination key1 key2 返回所有给定集合的并集并存储在destination集合中
|
||||
* 迭代集合中的元素xxxx
|
||||
*
|
||||
* 有序集合
|
||||
* zadd key score member1 socre1 member2 向有序集合添加一个或多个成员,或者更新已存在的成员的分数
|
||||
* zcard key 获取有序集合的成员数量
|
||||
* zcount key min max 计算在有序集合中指定区间分数的成员数
|
||||
* zincrby key increment member 有序集合中对指定成员的分数加增量increment
|
||||
* ---zinterstore destination numkeys key key1
|
||||
* --zlexcount key min max 在有序集合中计算指定字典区间内成员数量
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
*
|
||||
* */
|
||||
|
||||
|
||||
/**
|
||||
* 通配符 * 表示任意一个或多个字符
|
||||
* ? 表示任意字符
|
||||
* [abc] 表示方括号中任意一个字母
|
||||
*
|
||||
* */
|
||||
private redisManager()
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 主redis 数据库连接
|
||||
/// </summary>
|
||||
private static RedisConnectionHelp mainDBConnection;
|
||||
|
||||
/// <summary>
|
||||
/// 比赛redis 数据库连接
|
||||
/// </summary>
|
||||
private static RedisConnectionHelp bisaiDBConnection;
|
||||
|
||||
private static volatile bool isStart = false;
|
||||
|
||||
/// <summary>
|
||||
/// redis操作数据库代理_逻辑数据库处理
|
||||
/// </summary>
|
||||
public static IDatabaseProxy db
|
||||
{
|
||||
get
|
||||
{
|
||||
if (isStart)
|
||||
{
|
||||
return new IDatabaseProxy(mainDBConnection.Instance.GetDatabase());
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// redis 操作数据库代理_逻辑数据库处理
|
||||
/// </summary>
|
||||
/// <param name="idx"></param>
|
||||
/// <returns></returns>
|
||||
public static IDatabaseProxy Getdb(int idx)
|
||||
{
|
||||
if (isStart)
|
||||
return new IDatabaseProxy(mainDBConnection.Instance.GetDatabase(idx));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取比赛数据库处理
|
||||
/// </summary>
|
||||
/// <param name="idx"></param>
|
||||
/// <returns></returns>
|
||||
public static IDatabaseProxy GetBiSaidb(int idx = -1)
|
||||
{
|
||||
if (isStart)
|
||||
return new IDatabaseProxy(bisaiDBConnection.Instance.GetDatabase(idx));
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 获取数据库操作
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public static IDatabase GetDataBase(DbStyle sty = DbStyle.main, int idx = -1)
|
||||
{
|
||||
ConnectionMultiplexer cm = null;
|
||||
switch (sty)
|
||||
{
|
||||
case DbStyle.main:
|
||||
cm = mainDBConnection.Instance;
|
||||
break;
|
||||
case DbStyle.bisai:
|
||||
cm = bisaiDBConnection.Instance;
|
||||
break;
|
||||
}
|
||||
|
||||
if (cm == null)
|
||||
return null;
|
||||
return cm.GetDatabase(idx);
|
||||
}
|
||||
|
||||
public static List<RedisKey> Keys(string pattern, int dbidx, int pageSize = 1000, DbStyle sty = DbStyle.main)
|
||||
{
|
||||
if (!isStart) return null;
|
||||
|
||||
ConnectionMultiplexer cm = null;
|
||||
switch (sty)
|
||||
{
|
||||
case DbStyle.main:
|
||||
cm = mainDBConnection.Instance;
|
||||
break;
|
||||
case DbStyle.bisai:
|
||||
cm = bisaiDBConnection.Instance;
|
||||
break;
|
||||
}
|
||||
|
||||
if (cm == null)
|
||||
return null;
|
||||
|
||||
List<RedisKey> allkeys = new List<RedisKey>();
|
||||
|
||||
try
|
||||
{
|
||||
var points = cm.GetEndPoints();
|
||||
if (points.Length < 1)
|
||||
{
|
||||
Debug.Error("redis 没有任何连接!");
|
||||
return null;
|
||||
}
|
||||
|
||||
IServer server = cm.GetServer(points[0]);
|
||||
|
||||
if (points.Length > 1)
|
||||
{
|
||||
ClusterConfiguration clusternodes = server.ClusterNodes();
|
||||
foreach (var item in clusternodes.Nodes)
|
||||
{
|
||||
if (!item.IsSlave)
|
||||
{
|
||||
IServer temp = cm.GetServer(item.EndPoint);
|
||||
IEnumerable<RedisKey> rks = temp.Keys(dbidx, pattern,pageSize);
|
||||
foreach (RedisKey rk in rks)
|
||||
{
|
||||
allkeys.Add(rk);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
var rks = server.Keys(dbidx, pattern, pageSize);
|
||||
|
||||
foreach (var key in rks)
|
||||
{
|
||||
allkeys.Add(key);
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
Debug.Error("查询错误asdsahdjk" + e.ToString());
|
||||
return allkeys;
|
||||
}
|
||||
|
||||
|
||||
return allkeys;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 启动redis 服务器
|
||||
/// </summary>
|
||||
/// <param name="AllowAdmin">管理员模式</param>
|
||||
public static void Start(bool AllowAdmin = false)
|
||||
{
|
||||
for (int i = 0; i < RedisConfigCategory.Instance.DataList.Count; i++)
|
||||
{
|
||||
var item = RedisConfigCategory.Instance.DataList[i];
|
||||
switch (item.Name)
|
||||
{
|
||||
case "main":
|
||||
mainDBConnection = new RedisConnectionHelp();
|
||||
mainDBConnection.Start(item, AllowAdmin);
|
||||
break;
|
||||
case "bisai":
|
||||
bisaiDBConnection = new RedisConnectionHelp();
|
||||
bisaiDBConnection.Start(item, AllowAdmin);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
isStart = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// ConnectionMultiplexer对象管理帮助类__单例换多例
|
||||
/// </summary>
|
||||
public class RedisConnectionHelp
|
||||
{
|
||||
private readonly object Locker = new object();
|
||||
private ConnectionMultiplexer _instance;
|
||||
|
||||
/// <summary>
|
||||
/// 单例获取
|
||||
/// </summary>
|
||||
public ConnectionMultiplexer Instance
|
||||
{
|
||||
get
|
||||
{
|
||||
if (_instance == null)
|
||||
{
|
||||
lock (Locker)
|
||||
{
|
||||
if (_instance == null || !_instance.IsConnected)
|
||||
{
|
||||
//Debug.Error("获取新的实例!!!!");
|
||||
_instance = GetManager();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return _instance;
|
||||
}
|
||||
}
|
||||
|
||||
RedisConfig redisConfig;
|
||||
bool AllowAdmin;
|
||||
|
||||
/// <summary>
|
||||
/// 启动redis
|
||||
/// </summary>
|
||||
/// <param name="redisConfig_"></param>
|
||||
/// <param name="AllowAdmin_"></param>
|
||||
public void Start(RedisConfig redisConfig_, bool AllowAdmin_ = false)
|
||||
{
|
||||
redisConfig = redisConfig_;
|
||||
AllowAdmin = AllowAdmin_;
|
||||
}
|
||||
|
||||
private ConnectionMultiplexer GetManager(string connectionString = null)
|
||||
{
|
||||
ConfigurationOptions options = new ConfigurationOptions();
|
||||
|
||||
options.ConnectTimeout = redisConfig.ConnectTimeOut;
|
||||
options.AllowAdmin = AllowAdmin;
|
||||
options.AbortOnConnectFail = false; //true 表示连接失败将不会创建链接实例
|
||||
options.ConnectRetry = 5; //失败尝试重新链接的次数
|
||||
|
||||
options.EndPoints.Add(redisConfig.Host, redisConfig.Port);
|
||||
|
||||
ConnectionMultiplexer cml = ConnectionMultiplexer.Connect(options);
|
||||
|
||||
//redisPool.TimeoutMilliseconds = 3000;
|
||||
|
||||
cml.ConnectionFailed += MuxerConnectionFailed;
|
||||
cml.ConnectionRestored += MuxerConnectionRestored;
|
||||
cml.ErrorMessage += MuxerErrorMessage;
|
||||
cml.ConfigurationChanged += MuxerConfigurationChanged;
|
||||
cml.HashSlotMoved += MuxerHashSlotMoved;
|
||||
cml.InternalError += MuxerInternalError;
|
||||
|
||||
return cml;
|
||||
}
|
||||
|
||||
#region 事件
|
||||
|
||||
/// <summary>
|
||||
/// 配置更改时
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void MuxerConfigurationChanged(object sender, EndPointEventArgs e)
|
||||
{
|
||||
Debug.Fatal("Configuration changed: " + e.EndPoint);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 发生错误时
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void MuxerErrorMessage(object sender, RedisErrorEventArgs e)
|
||||
{
|
||||
Debug.Fatal("ErrorMessage: " + e.Message);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 重新建立连接之前的错误
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void MuxerConnectionRestored(object sender, ConnectionFailedEventArgs e)
|
||||
{
|
||||
Debug.Fatal("ConnectionRestored: " + e.EndPoint);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 连接失败 , 如果重新连接成功你将不会收到这个通知
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void MuxerConnectionFailed(object sender, ConnectionFailedEventArgs e)
|
||||
{
|
||||
Debug.Fatal("重新连接:Endpoint failed: " + e.EndPoint + ", " + e.FailureType +
|
||||
(e.Exception == null ? "" : (", " + e.Exception.Message)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// 更改集群
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void MuxerHashSlotMoved(object sender, HashSlotMovedEventArgs e)
|
||||
{
|
||||
Debug.Fatal("HashSlotMoved:NewEndPoint" + e.NewEndPoint + ", OldEndPoint" + e.OldEndPoint);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// redis类库错误
|
||||
/// </summary>
|
||||
/// <param name="sender"></param>
|
||||
/// <param name="e"></param>
|
||||
private void MuxerInternalError(object sender, InternalErrorEventArgs e)
|
||||
{
|
||||
Debug.Fatal("InternalError:Message" + e.Exception.Message);
|
||||
}
|
||||
|
||||
#endregion 事件
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user