Skip to content

Commit

Permalink
Merge branch 'dev' of http://git.newlifex.com/NewLife/X into dev
Browse files Browse the repository at this point in the history
  • Loading branch information
nnhy committed Jun 29, 2018
2 parents cd5f321 + 8ddd86c commit de1db65
Show file tree
Hide file tree
Showing 8 changed files with 124 additions and 58 deletions.
24 changes: 19 additions & 5 deletions NewLife.Core/Log/TextFileLog.cs
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,13 @@ public static TextFileLog CreateFile(String path)
/// <summary>销毁</summary>
public void Dispose()
{
if (LogWriter != null)
// 销毁前把队列日志输出
if (_Logs != null && !_Logs.IsEmpty) WriteFile(null);

var writer = LogWriter;
if (writer != null)
{
LogWriter.Dispose();
writer.TryDispose();
LogWriter = null;
}
}
Expand Down Expand Up @@ -102,6 +106,7 @@ public String LogPath

#region 内部方法
private StreamWriter LogWriter;
private String CurrentLogFile;

/// <summary>初始化日志记录文件</summary>
private StreamWriter InitLog()
Expand All @@ -125,7 +130,7 @@ private StreamWriter InitLog()

if (writer == null)
{
logfile = Path.Combine(path, FileFormat.F(DateTime.Now));
logfile = Path.Combine(path, FileFormat.F(TimerX.Now));
var ext = Path.GetExtension(logfile);
var i = 0;
while (i < 10)
Expand All @@ -147,6 +152,7 @@ private StreamWriter InitLog()
logfile = logfile.Replace(ext, "_0" + ext);
}
}
CurrentLogFile = logfile;
}
if (writer == null) throw new XException("无法写入日志!");

Expand Down Expand Up @@ -179,14 +185,22 @@ private StreamWriter InitLog()
protected virtual void WriteFile(Object state)
{
var writer = LogWriter;

var now = TimerX.Now;
var logfile = Path.Combine(LogPath, FileFormat.F(now));
if (logfile != CurrentLogFile)
{
writer.TryDispose();
writer = null;
}

if (_Logs.IsEmpty)
{
// 连续5秒没日志,就关闭
var now = TimerX.Now;
if (_NextClose < now)
{
LogWriter = null;
writer.TryDispose();
writer = null;

_NextClose = now.AddSeconds(5);
}
Expand Down
45 changes: 27 additions & 18 deletions NewLife.Core/Threading/TimerScheduler.cs
Original file line number Diff line number Diff line change
Expand Up @@ -171,6 +171,11 @@ private void Process(Object state)
// 内部线程池,让异步任务有公平竞争CPU的机会
//ThreadPoolX.QueueUserWorkItem(Execute, timer);
}
// 即使不能执行,也要设置下一次的时间
else
{
OnFinish(timer);
}
}
}
}
Expand Down Expand Up @@ -251,28 +256,11 @@ private void Execute(Object state)

if (d > MaxCost && !timer.Async) XTrace.WriteLine("任务 {0} 耗时过长 {1:n0}ms,建议使用异步任务Async=true", timer, d);

// 再次读取周期,因为任何函数可能会修改
var p = timer.Period;

timer.Timers++;

// 如果内部设置了下一次时间,则不再递加周期
if (!timer.hasSetNext)
{
if (timer.Absolutely)
timer.NextTime = timer.NextTime.AddMilliseconds(p);
else
timer.NextTime = DateTime.Now.AddMilliseconds(p);
}
OnFinish(timer);

timer.Calling = false;

// 清理一次性定时器
if (p <= 0)
timer.Dispose();
else if (p < period)
period = p;

TimerX.Current = null;

// 控制日志显示
Expand All @@ -283,6 +271,27 @@ private void Execute(Object state)
}
}

private void OnFinish(TimerX timer)
{
// 再次读取周期,因为任何函数可能会修改
var p = timer.Period;

// 如果内部设置了下一次时间,则不再递加周期
if (!timer.hasSetNext)
{
if (timer.Absolutely)
timer.NextTime = timer.NextTime.AddMilliseconds(p);
else
timer.NextTime = DateTime.Now.AddMilliseconds(p);
}

// 清理一次性定时器
if (p <= 0)
timer.Dispose();
else if (p < period)
period = p;
}

/// <summary>已重载。</summary>
/// <returns></returns>
public override String ToString() => Name;
Expand Down
17 changes: 10 additions & 7 deletions NewLife.Core/Web/OAuthServer.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ namespace NewLife.Web
public class OAuthServer
{
#region 属性
private ICache Cache { get; } = NewLife.Caching.Cache.Default;
/// <summary>缓存</summary>
public ICache Cache { get; set; } = NewLife.Caching.Cache.Default;

/// <summary>令牌提供者</summary>
public TokenProvider TokenProvider { get; set; } = new TokenProvider();
Expand All @@ -32,15 +33,15 @@ public class OAuthServer
/// 子系统需要验证访问者身份时,引导用户跳转到这里。
/// 用户登录完成后,得到一个独一无二的code,并跳转回去子系统。
/// </remarks>
/// <param name="appid">应用标识</param>
/// <param name="client_id">应用标识</param>
/// <param name="redirect_uri">回调地址</param>
/// <param name="response_type">响应类型。默认code</param>
/// <param name="scope">授权域</param>
/// <param name="state">用户状态数据</param>
/// <returns></returns>
public virtual Int32 Authorize(String appid, String redirect_uri, String response_type = null, String scope = null, String state = null)
public virtual Int32 Authorize(String client_id, String redirect_uri, String response_type = null, String scope = null, String state = null)
{
//if (appid.IsNullOrEmpty()) throw new ArgumentNullException(nameof(appid));
//if (client_id.IsNullOrEmpty()) throw new ArgumentNullException(nameof(client_id));
//if (redirect_uri.IsNullOrEmpty()) throw new ArgumentNullException(nameof(redirect_uri));
//if (response_type.IsNullOrEmpty()) response_type = "code";

Expand All @@ -49,7 +50,7 @@ public virtual Int32 Authorize(String appid, String redirect_uri, String respons
// 用缓存把数据存下来,避免本站登录期间,跳转地址很长
var model = new Model
{
AppID = appid,
AppID = client_id,
Uri = redirect_uri,
Type = response_type,
Scope = scope,
Expand All @@ -64,7 +65,7 @@ public virtual Int32 Authorize(String appid, String redirect_uri, String respons
}
while (!Cache.Add("Model:" + key, model, 20 * 60));

if (Log != null) WriteLog("Authorize appid={0} redirect_uri={1}", appid, redirect_uri);
if (Log != null) WriteLog("Authorize client_id={0} redirect_uri={1}", client_id, redirect_uri);

return key;
}
Expand Down Expand Up @@ -109,9 +110,11 @@ public virtual String GetResult(Int32 key, IManageUser user)
}

/// <summary>根据Code获取令牌</summary>
/// <param name="client_id"></param>
/// <param name="client_secret"></param>
/// <param name="code"></param>
/// <returns></returns>
public virtual String GetToken(String code)
public virtual String GetToken(String client_id, String client_secret, String code)
{
var k = "Code:" + code;
var model = Cache.Get<Model>(k);
Expand Down
21 changes: 16 additions & 5 deletions Test/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -134,14 +134,25 @@ static void Test3()
//var list = Role.FindAllWithCache();
//Console.WriteLine(list.Count);

ThreadPoolX.Instance.Pool.Log = XTrace.Log;
//var log = TextFileLog.Create(".", "{0:yyyy_MM_dd_HHmm}.log");

for (int i = 0; i < 10000; i++)
////ThreadPoolX.Instance.Pool.Log = XTrace.Log;

//for (int i = 0; i < 10000; i++)
//{
// //XTrace.WriteLine("T{0:n0}", i);
// log.Info("T {0:n0}", i);

// var n = Rand.Next(300, 3000);
// Thread.Sleep(n);
//}

Log.Meta.Session.Dal.Db.ShowSQL = true;
for (var i = 0; i < 1000; i++)
{
XTrace.WriteLine("T{0:n0}", i);
LogProvider.Provider.WriteLog("aa", "bb", "cc");

var n = Rand.Next(300, 3000);
Thread.Sleep(n);
Thread.Sleep(1000);
}
}

Expand Down
15 changes: 13 additions & 2 deletions XCode/Entity/EntityQueue.cs
Original file line number Diff line number Diff line change
Expand Up @@ -50,8 +50,6 @@ public class EntityQueue
public EntityQueue(IEntitySession session)
{
Session = session;
_Timer = new TimerX(Work, null, Period, Period, "EQ") { Async = true };
_Timer.CanExecute = () => DelayEntities.Any() || Entities.Any();
}
#endregion

Expand All @@ -62,6 +60,19 @@ public EntityQueue(IEntitySession session)
/// <returns>返回是否添加成功,实体对象已存在于队列中则返回false</returns>
public Boolean Add(IEntity entity, Int32 msDelay)
{
// 首次使用时初始化定时器
if (_Timer == null)
{
lock (this)
{
if (_Timer == null)
{
_Timer = new TimerX(Work, null, Period, Period, "EQ") { Async = true };
_Timer.CanExecute = () => DelayEntities.Any() || Entities.Any();
}
}
}

var rs = false;
if (msDelay <= 0)
rs = Entities.TryAdd(entity, entity);
Expand Down
35 changes: 28 additions & 7 deletions XCode/Entity/EntitySession.cs
Original file line number Diff line number Diff line change
Expand Up @@ -129,17 +129,17 @@ public virtual String FormatedTableName
var str = TableName;

// 检查自动表前缀
var dal = DAL.Create(ConnName);
var pf = dal.Db.TablePrefix;
var db = Dal.Db;
var pf = db.TablePrefix;
if (!pf.IsNullOrEmpty() && !str.StartsWithIgnoreCase(pf)) str = pf + str;

str = Dal.Db.FormatName(str);
str = db.FormatName(str);

// 特殊处理Oracle数据库,在表名前加上方案名(用户名)
if (!str.Contains("."))
{
// 角色名作为点前缀来约束表名,支持所有数据库
var owner = dal.Db.Owner;
var owner = db.Owner;
if (!owner.IsNullOrEmpty()) str = Dal.Db.FormatName(owner) + "." + str;
}

Expand All @@ -149,6 +149,27 @@ public virtual String FormatedTableName
}
}

private String _TableNameWithPrefix;
/// <summary>带前缀的表名</summary>
public virtual String TableNameWithPrefix
{
get
{
if (_TableNameWithPrefix.IsNullOrEmpty())
{
var str = TableName;

// 检查自动表前缀
var db = Dal.Db;
var pf = db.TablePrefix;
if (!pf.IsNullOrEmpty() && !str.StartsWithIgnoreCase(pf)) str = pf + str;

_TableNameWithPrefix = str;
}
return _TableNameWithPrefix;
}
}

private EntitySession<TEntity> _Default;
/// <summary>该实体类的默认会话。</summary>
private EntitySession<TEntity> Default
Expand Down Expand Up @@ -547,7 +568,7 @@ private Int64 GetCount(Int64 count)
// 100w数据时,没有预热Select Count需要3000ms,预热后需要500ms
if (count < 500000)
{
if (count <= 0) count = Dal.Session.QueryCountFast(FormatedTableName);
if (count <= 0) count = Dal.Session.QueryCountFast(TableNameWithPrefix);

// 查真实记录数,修正FastCount不够准确的情况
if (count < 10000000)
Expand All @@ -563,7 +584,7 @@ private Int64 GetCount(Int64 count)
else
{
// 异步查询弥补不足,千万数据以内
if (count < 10000000) count = Dal.Session.QueryCountFast(FormatedTableName);
if (count < 10000000) count = Dal.Session.QueryCountFast(TableNameWithPrefix);
}

return count;
Expand Down Expand Up @@ -709,7 +730,7 @@ public event Action<Type> OnDataChange
/// <returns></returns>
public Int32 Truncate()
{
var rs = Dal.Session.Truncate(FormatedTableName);
var rs = Dal.Session.Truncate(TableNameWithPrefix);

// 干掉所有缓存
_cache?.Clear("Truncate");
Expand Down
20 changes: 11 additions & 9 deletions XCode/Membership/用户.Biz.cs
Original file line number Diff line number Diff line change
Expand Up @@ -51,6 +51,11 @@ static User()
// 不过这不是理由,同一个线程遇到同一个锁不会堵塞
// 发生死锁的可能性是这里引发EnsureInit,而另一个线程提前引发EnsureInit拿到锁
Meta.Factory.AdditionalFields.Add(__.Logins);

// 单对象缓存
var sc = Meta.SingleCache;
sc.FindSlaveKeyMethod = k => Find(__.Name, k);
sc.GetSlaveKeyMethod = e => e.Name;
}

/// <summary>首次连接数据库时初始化数据,仅用于实体类重载,用户不应该调用该方法</summary>
Expand Down Expand Up @@ -202,13 +207,10 @@ public static TEntity FindByID(Int32 id)
{
if (id <= 0) return null;

if (Meta.Count >= 1000)
return Find(__.ID, id);
else // 实体缓存
return Meta.Cache.Find(e => e.ID == id);
if (Meta.Count < 1000) return Meta.Cache.Find(e => e.ID == id);

// 实体缓存
//return Meta.SingleCache[id];
return Meta.SingleCache[id];
}

/// <summary>根据名称查找</summary>
Expand All @@ -218,10 +220,10 @@ public static TEntity FindByName(String name)
{
if (name.IsNullOrEmpty()) return null;

if (Meta.Count >= 1000)
return Find(__.Name, name);
else // 实体缓存
return Meta.Cache.Find(e => e.Name.EqualIgnoreCase(name));
if (Meta.Count < 1000) return Meta.Cache.Find(e => e.Name.EqualIgnoreCase(name));

// 单对象缓存
return Meta.SingleCache.GetItemWithSlaveKey(name) as TEntity;
}

/// <summary>根据邮箱地址查找</summary>
Expand Down
5 changes: 0 additions & 5 deletions XCode/Membership/菜单.Biz.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,6 @@
using NewLife.Reflection;
using NewLife.Collections;
using NewLife.Threading;
#if NET4
using System.Threading.Tasks;
#else
using TaskEx = System.Threading.Tasks.Task;
#endif

namespace XCode.Membership
{
Expand Down

0 comments on commit de1db65

Please sign in to comment.