首页 文章 精选 留言 我的

精选列表

搜索[安全机制],共10000篇文章
优秀的个人博客,低调大师

Node工程-构建优秀的Session机制

我们公司的大佬 串串,搭建了一套基于koa2的node框架,虽然说是重复造轮子,但适用当前场景的轮子才是最好的,何况很多人还造不出轮子呢~ 大佬搭建的框架命名为 Sponse,其中有很多出色的设计,这里对 session 的设计做个总结(其实是为了自己加深印象,学习大佬的设计) Sponse意思是海绵,而我们这套框架就如同海绵一样,通过不断吸收其他框架的优秀设计丰满自己 cookie 与 session 做开发的小伙伴对这两个应该在熟悉不过了,这两个一起构建起前后端状态的联系,常见的如维护用户登录状态,用户登录后,需要在服务端记录下该用户的登录状态,前端才可以使用需要登录态的接口,此时,浏览器中的 cookie 就是查询用户是否登录的凭证,在服务端,通常是将用户状态信息存储在缓存中,简单说,就是基于 cookie的session 调用方式 优秀的架构中,调用方式必须是友好的 期望能够通过上下文直接调用,如:获取session对象 ctx.session ; 设置session的值 ctx.session.name = name 逻辑图 整体实现逻辑如下 实现 koa提供了操作cookie的api,开箱即用,官方截图如下 缓存基于redis实现 详细代码如下: Session 对象 首先构建一个session对象 核心方法: save 用于同步cookie changed 用于检测session对象是否发生修改,为了同步更新缓存中的值 export class Session { private _ctx; isNew: boolean; _json; // session对象的json串,用于比较session对象是否发生变化 constructor(ctx, obj) { this._ctx = ctx; if (!obj) this.isNew = true; else { for (const k in obj) { this[k] = obj[k]; } } } /** * Save session changes by * performing a Set-Cookie. * * @api private */ save() { const ctx = this._ctx; const json = this._json || JSON.stringify(this.inspect()); const sid = ctx.sessionId; const opts = ctx.cookieOption; const key = ctx.sessionKey; if (ctx.cookies.get(key) !== sid) { // 设置cookies的值 ctx.cookies.set(key, sid, opts); } return json; }; /** * JSON representation of the session. * * @return {Object} * @api public */ inspect() { const self = this; const obj = {}; Object.keys(this).forEach(function (key) { if ('isNew' === key) return; if ('_' === key[0]) return; obj[key] = self[key]; }); return obj; } /** * Check if the session has changed relative to the `prev` * JSON value from the request. * * @param {String} [prev] * @return {Boolean} * @api private */ changed(prev) { if (!prev) return true; this._json = JSON.stringify(this.inspect()); return this._json !== prev; }; } 复制代码 SessionEngine koa中间件 koa 当然是离不开中间件了,洋葱模型酷炫到不行,非常方便的解决了session对象与缓存的同步 decorator(app) { app.keys = ['signed-key']; const CONFIG = { key: app.config.name + '.sess', /** (string) cookie key (default is koa:sess) */ cookie: { // maxAge: 1000, /** (number) maxAge in ms (default is 1 days) */ overwrite: false, /** (boolean) can overwrite or not (default true) */ httpOnly: true, /** (boolean) httpOnly or not (default true) */ signed: true, /** (boolean) signed or not (default true) */ } }; app.use(async (ctx, next) => { let sess: Session; let sid; let json; ctx.cookieOption = CONFIG.cookie; ctx.sessionKey = CONFIG.key; ctx.sessionId = null; // 获取cookie 对应的值, 即sessionID,就是缓存中的key sid = ctx.cookies.get(CONFIG.key, ctx.cookieOption); // 获取session值 if (sid) { try { // 若key存在,则从缓存中获取对应的值 json = await app.redisClient.get(sid); } catch (e) { console.log('从缓存中读取session失败: %s\n', e); json = null; } } // 实例化session if (json) { // 若缓存中有值,则基于缓存中的值构建session对象 ctx.sessionId = sid; try { sess = new Session(ctx, json); } catch (err) { if (!(err instanceof SyntaxError)) throw err; sess = new Session(ctx, null); } } else { sid = ctx.sessionId = sid || Uuid.gen(); sess = new Session(ctx, null); } // 为了便于使用,将session挂载到上下文,这样就可以 ctx.session 这么使用了 Object.defineProperty(ctx, 'session', { get: function () { return sess; }, set: function (val) { if (null === val) return sess = null; if ('object' === typeof val) return sess = new Session(this, val); throw new Error('this.session can only be set as null or an object.'); } }); try { await next(); } catch (err) { throw err; } finally { if (null === sess) { // 设置session=null表示清空session ctx.cookies.set(CONFIG.key, '', ctx.cookieOption); } else if (sess.changed(json)) { // 检查 session 是否发生变化,若有变化,更新缓存中的值 json = sess.save(); await app.redisClient.set(sid, json); app.redisClient.ttl(sid); // 设置redis值过期时间为60分钟 app.redisClient.expire(sid, 7200); } else { // session 续期 app.redisClient.expire(sid, 7200); } } }); 复制代码 小结 多多学习~ 点点进步~ 原文发布时间:2018年06月29日 作者:小黎也 本文来源 掘金如需转载请紧急联系作者

优秀的个人博客,低调大师

HFile和HLog的回收机制

正常回收流程HBase数据主要存储在分布式文件系统上HFile和HLog文件中。HBase数据基于LSM模型,写操作写到内存(MemStore)和Write Ahead Log(HLog, 放在.logs下regionserver目录下)就返回。当内存不足或者MemStore超过一定大小的时候,HBase会将MemStore的数据顺序写到分布式文件系统上,形成一个HFile。当RegionServer进程down机时候,regionserver的log目录会被HMaster重命名(添加-splitting后缀),目录下所有hlog会被logSpliter分割成为各个region的recover.edits. 当log split完成之后,HMaster会将log移动到.oldlog目录下。当小的HFile过多的时候,会将多个小的HFile压缩形成一个大的HFile。压缩完成之后这些小的HFile就被移动.archive目录下。如果HLog里所有记录对应的数据都已经刷新到HFile上,HLog就被RegionServer移动到.oldlog目录下。HMaster上的定时线程HFileCleaner/LogCleaner周期性扫描archive目录和.oldlog目录, 判断目录下的HFile或者HLog是否可以被删除,如果可以, 就直接删除文件. recyling TimeToLive为了防止系统错误删除HFile/HLog, HFile/HLog都有一个全局的过期时间(TTL), 超过这个过期时间的HFile/HLog才被删除. 这个过期时间可以通过hbase.master.logcleaner.ttl和hbase.master.hfilecleaner.ttl配置(单位是ms) ReplicationHBase的Replication是通过将主集群的HLog推送到备集群,然后在备集群上重放Hlog实现的, 因此如果在oldlog目录下的HLog还在被Replication推送完成,这些文件不能删除。 HMaster上的ReplicationLogCleaner通过zk负责记录Replication正在使用那些HLog。 当Regionserver创建一个新的hlog时,Replication会在对应zk replication目录下建立相应的hlog节点,即将hlog加入replication队列。ReplicationLogCleaner会收到zk上replication目录节点创建的通知,将此hlog标记为使用中。当Replication推送完成hlog的数据后,replicaton会将zk上replication目录下hlog节点删除。ReplicationLogCleaner会收到节点删除通知,将此hlog标记为可删除。当然需要注意的是一个hlog可能同时被多个不同peer的replication使用,只有当所有不同peer的replication都推送完成这个hlog的数据之后,这个hlog才能被删除。 SnapShot标的Snapshot在单独的snapshot目录下,创建了表结构和HFile的引用。HMaster上SnapshotFileCache会定期扫描分布式文件系统上的snapshot目录,标记那些HFile现在被某个Snapshot引用。HMaster上的HFileCleaner在尝试删除HFile时候会通过SnapshotHFileCleaner检查HFile是否被引用,如果被引用就不能删除。 Region Split当Region大小超过一定阈值时,Region会自动分裂成两个子Region. Region Split执行时间是秒级别的. Split前父Region会预flush一次,然后关闭Region的写,最后做一次flush, 保证Region所有的数据都写到HFile中。Split时两个Region并不实际分割父Region的HFile,而是在子Region目录下生成父region所有HFile引用。 这些引用指向实际的HFile文件,子Region Compaction时候,会删除这些引用,生产真实的HFile。HMaster上定时线程CatalogJanitor会周期性扫描出Meta表上的分裂后的父Region,通过父Region找到分裂后的两个子Region。通过扫描两个子Region的hdfs目录,确认两个子Region是否还有到父Region的引用(HFile 引用是有特殊的文件名)。确认子Region中所有引用HFile都被compaction回收之后,CatalogJanitor线程会将父Region的HFile,被移动到archive目录下,删除meta表上遗留的父region数据,已经父region的hdfs目录。

优秀的个人博客,低调大师

Android消息机制-Handler,Message,MessageQueue,Looper

Android的消息是怎样传的?Handler为什么要这么用? 一个简单的例子 import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.util.Log; import android.widget.TextView; import java.lang.ref.WeakReference; public class MainActivity extends AppCompatActivity { private static final String TAG = "MainActivity>"; private final MyHandler handler=new MyHandler(MainActivity.this); private final MyRunable myRunable=new MyRunable(MainActivity.this); private TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView=findViewById(R.id.textView); handler.postDelayed(myRunable,30000); } /** * 静态内部类,防止对外部类的引用 */ private static class MyHandler extends Handler{ private final WeakReference<MainActivity> mainActivityWeakReference; public MyHandler(MainActivity mainActivity) { this.mainActivityWeakReference = new WeakReference<MainActivity>(mainActivity); } @Override public void handleMessage(Message msg) { MainActivity mainActivity=mainActivityWeakReference.get(); if (mainActivity!=null){ Log.d(TAG, "handleMessage: !!!!!!!!!"); }else { Log.d(TAG, "run: mainActivity already destroy!"); } } } /** * 静态内部类,防止对外部类的引用造成内存泄露 */ private static class MyRunable implements Runnable { private final WeakReference<MainActivity> mainActivityWeakReference; public MyRunable(MainActivity main) { this.mainActivityWeakReference = new WeakReference<MainActivity>(main); } @Override public void run() { MainActivity mainActivity=mainActivityWeakReference.get(); if (mainActivity!=null){ Log.d(TAG, "run: !!!!!!!!!!!!!!!!!!!"); }else { Log.d(TAG, "run: mainActivity already destroy!"); } } } } Handler 怎么发消息的? 留给开发者的接口: post方式: post sendMessage方式: sendMessage(Message msg) sendEmptyMessage(int what) sendEmptyMessageDelayed(int what, long delayMillis) sendMessageDelayed(Message msg, long delayMillis) sendMessageAtTime(Message msg, long uptimeMillis) 两种方式发送的最终对象都是Message,发送的最终方式都是sendMessageAtTime(Message msg, long uptimeMillis)或sendMessageAtFrontOfQueue(Message msg),两个通用的接口变化出不同情况的接口,这样做的好处就是方便开发者灵活调用吧。很多类的构造方法也是如此 那么,继续,看sendMessageAtTime public boolean sendMessageAtTime(Message msg, long uptimeMillis) { MessageQueue queue = mQueue; //获取messageQueue,就是消息队列 if (queue == null) {//队列为空,则输出异常,提示没有消息队列,方法执行结束 RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, uptimeMillis); } 消息队列不为空,就调用enqueueMessage()方法,但是mQueue从哪儿来的? 这里可以查看Handler的构造方法: public Handler(Callback callback, boolean async) { if (FIND_POTENTIAL_LEAKS) { final Class<? extends Handler> klass = getClass(); if ((klass.isAnonymousClass() || klass.isMemberClass() || klass.isLocalClass()) && (klass.getModifiers() & Modifier.STATIC) == 0) { Log.w(TAG, "The following Handler class should be static or leaks might occur: " + klass.getCanonicalName()); } } mLooper = Looper.myLooper(); if (mLooper == null) { throw new RuntimeException( "Can't create handler inside thread that has not called Looper.prepare()"); } mQueue = mLooper.mQueue; mCallback = callback; mAsynchronous = async; } Handler的构造方法我分为两类,一类是要传Looper的,一类的不传Looper的,这里是不传Looper的,不传Looper的最终都会调用上述方法,也就是用的当前线程的Looper,一般是使用的时候都是主线程的Looper,比如前面的例子就是不传Looper得到的handler。具体Looper.myLooper()怎么获取的,待会在看。一个Looper拥有一个消息队列,所以mLooper.mQueue就给Handler的mQueue赋值了 继续 看sendMessageAtFrontOfQueue(Message msg) public final boolean sendMessageAtFrontOfQueue(Message msg) { MessageQueue queue = mQueue; if (queue == null) { RuntimeException e = new RuntimeException( this + " sendMessageAtTime() called with no mQueue"); Log.w("Looper", e.getMessage(), e); return false; } return enqueueMessage(queue, msg, 0); } 除了最终调用enqueueMessage()传入的第三个参数,方法块几乎一摸一样,可以看出0就是将消息放在消息队列的最前面了 继续 终于羊肠小道了 private boolean enqueueMessage(MessageQueue queue, Message msg, long uptimeMillis) { msg.target = this; if (mAsynchronous) { msg.setAsynchronous(true); } return queue.enqueueMessage(msg, uptimeMillis); } 这里可以先看下Message类,个人认为,Message就是个消息的载体,像货箱,大货箱里面又有很多位置,比如what,arg1,arg2放int数据,obj放引用数据,位置不够还可以用Bundle; public static Message obtain()方法可以快速获取一个实例化的Message;最后有个重要的成员就是target,就是指定最终处理它的Handler对象。enqueueMessage()方法给msg的target为Handler自己,从而得出message由Handler发送,也由同一个Handler处理。 MessageQueue是如果入队的?查看enqueueMessage(Message msg, long when) boolean enqueueMessage(Message msg, long when) { // 如果处理它的Handler为空,当然选择抛异常 if (msg.target == null) { throw new IllegalArgumentException("Message must have a target."); } // 如果msg已经标记被使用了,当然选择抛异常 ,你发个已经被用的msg来干嘛 if (msg.isInUse()) { throw new IllegalStateException(msg + " This message is already in use."); } // 在同步的情况下,检查此队列所在的线程(比如主线程)有没有dead,dead的话回收msg,返回false,退出此方法 synchronized (this) { if (mQuitting) { IllegalStateException e = new IllegalStateException( msg.target + " sending message to a Handler on a dead thread"); Log.w(TAG, e.getMessage(), e); msg.recycle(); return false; } // 标记msg正在使用 msg.markInUse(); // 执行时间,队列是以时间顺序放的,0代表放队列的最前面,当然越前面就越先执行 msg.when = when; // 当前待执行的Message,应该是从队列跑出来的 Message p = mMessages; // 需不需要唤醒 boolean needWake; // 如果当前待执行的Message为空,或者传入的msg执行时间为现在,或者执行时间还要比待执行Message的执行时间还要提前,那么当然是优先执行传入的msg啦 if (p == null || when == 0 || when < p.when) { // 指定下一要执行的msg msg.next = p; // 替换当前待执行的Message为新传入的msg mMessages = msg; // New head, wake up the event queue if blocked. 保证唤醒队列,可以动了 needWake = mBlocked; } else { // Inserted within the middle of the queue. Usually we don't have to wake // up the event queue unless there is a barrier at the head of the queue // and the message is the earliest asynchronous message in the queue. // 设置唤醒状态 = 当前唤醒 并且 当前待执行的Message为空 并且 新msg为异步msg needWake = mBlocked && p.target == null && msg.isAsynchronous(); Message prev; for (;;) { prev = p; p = p.next; if (p == null || when < p.when) { break; } if (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; // invariant: p == prev.next prev.next = msg; } // We can assume mPtr != 0 because mQuitting is false. if (needWake) { nativeWake(mPtr); } } return true; } 新msg入队过程 Message prev; for (;;) { prev = p; p = p.next; if (p == null || when < p.when) { break; } if (needWake && p.isAsynchronous()) { needWake = false; } } msg.next = p; // invariant: p == prev.next prev.next = msg; } 首先从头开始遍历队列 遍历队列 在遍历过程的每一步判断,如果新msg的执行时间比p的执行时间提前,则停止遍历,插入新msg image.png image.png 在enqueueMessage中首先判断,如果当前的消息队列为空,或者新添加的消息的执行时间when是0,或者新添加的消息的执行时间比消息队列头的消息的执行时间还早,就把消息添加到消息队列头(消息队列按时间排序),否则就要找到合适的位置将当前消息添加到消息队列。 主线程的Looper是在哪儿启动消息循环的? 从Android程序的Main方法看,它就在Android.App.MainThread.java类里 public static void main(String[] args) { Trace.traceBegin(Trace.TRACE_TAG_ACTIVITY_MANAGER, "ActivityThreadMain"); SamplingProfilerIntegration.start(); // CloseGuard defaults to true and can be quite spammy. We // disable it here, but selectively enable it later (via // StrictMode) on debug builds, but using DropBox, not logs. CloseGuard.setEnabled(false); Environment.initForCurrentUser(); // Set the reporter for event logging in libcore EventLogger.setReporter(new EventLoggingReporter()); // Make sure TrustedCertificateStore looks in the right place for CA certificates final File configDir = Environment.getUserConfigDirectory(UserHandle.myUserId()); TrustedCertificateStore.setDefaultUserDirectory(configDir); Process.setArgV0("<pre-initialized>"); Looper.prepareMainLooper(); ActivityThread thread = new ActivityThread(); thread.attach(false); if (sMainThreadHandler == null) { sMainThreadHandler = thread.getHandler(); } if (false) { Looper.myLooper().setMessageLogging(new LogPrinter(Log.DEBUG, "ActivityThread")); } // End of event ActivityThreadMain. Trace.traceEnd(Trace.TRACE_TAG_ACTIVITY_MANAGER); Looper.loop(); throw new RuntimeException("Main thread loop unexpectedly exited"); } 可以看到调用了Looper.prepareMainLooper(),然后实例化了一个sMainThreadHandler,然后Looper.loop(),相当于主线程的消息循环就在这儿启动了。 具体分析Looper prepareMainLooper() public static void prepareMainLooper() { prepare(false); synchronized (Looper.class) { if (sMainLooper != null) { throw new IllegalStateException("The main Looper has already been prepared."); } sMainLooper = myLooper(); } } prepare(false): private static void prepare(boolean quitAllowed) { if (sThreadLocal.get() != null) { throw new RuntimeException("Only one Looper may be created per thread"); } sThreadLocal.set(new Looper(quitAllowed)); } sThreadLocal 设置了一个Looper实例 myLooper()方法: /** * Return the Looper object associated with the current thread. Returns * null if the calling thread is not associated with a Looper. */ public static @Nullable Looper myLooper() { return sThreadLocal.get(); } 主线程的looper就是从sThreadLocal得到的,可以知道这里用了ThreadLocal类,那么ThreadLocal是干嘛的呢? ThreadLocal干嘛的? 这里采用该作者的讲解,理解Java中的ThreadLocal 1.ThreadLocal是一个关于创建线程局部变量的类。 2.通常情况下,我们创建的变量是可以被任何一个线程访问并修改的。而使用ThreadLocal创建的变量只能被当前线程访问,其他线程则无法访问和修改。 3.正如Android的Looper,设计出来就是一个线程维护一个Looper,使用ThreadLocal保证了一个线程最多一个Looper,其实分析下ThreadLocal相关的方法,就知道ThreadLocal的值是放入了当前线程的一个ThreadLocalMap实例中,所以只能在本线程中访问,其他线程无法访问。 Looper怎样循环的? 前面的代码可以知道,main方法里,创建了主线程的Looper,而且调用loop()方法 /** * Run the message queue in this thread. Be sure to call * 运行当前线程的消息队列 * {@link #quit()} to end the loop. */ public static void loop() { final Looper me = myLooper(); if (me == null) { throw new RuntimeException("No Looper; Looper.prepare() wasn't called on this thread."); } final MessageQueue queue = me.mQueue; // Make sure the identity of this thread is that of the local process, // and keep track of what that identity token actually is. Binder.clearCallingIdentity(); final long ident = Binder.clearCallingIdentity(); for (;;) { Message msg = queue.next(); // might block if (msg == null) { // No message indicates that the message queue is quitting. return; } // This must be in a local variable, in case a UI event sets the logger final Printer logging = me.mLogging; if (logging != null) { logging.println(">>>>> Dispatching to " + msg.target + " " + msg.callback + ": " + msg.what); } final long slowDispatchThresholdMs = me.mSlowDispatchThresholdMs; final long traceTag = me.mTraceTag; if (traceTag != 0 && Trace.isTagEnabled(traceTag)) { Trace.traceBegin(traceTag, msg.target.getTraceName(msg)); } final long start = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); final long end; try { msg.target.dispatchMessage(msg); end = (slowDispatchThresholdMs == 0) ? 0 : SystemClock.uptimeMillis(); } finally { if (traceTag != 0) { Trace.traceEnd(traceTag); } } if (slowDispatchThresholdMs > 0) { final long time = end - start; if (time > slowDispatchThresholdMs) { Slog.w(TAG, "Dispatch took " + time + "ms on " + Thread.currentThread().getName() + ", h=" + msg.target + " cb=" + msg.callback + " msg=" + msg.what); } } if (logging != null) { logging.println("<<<<< Finished to " + msg.target + " " + msg.callback); } // Make sure that during the course of dispatching the // identity of the thread wasn't corrupted. final long newIdent = Binder.clearCallingIdentity(); if (ident != newIdent) { Log.wtf(TAG, "Thread identity changed from 0x" + Long.toHexString(ident) + " to 0x" + Long.toHexString(newIdent) + " while dispatching to " + msg.target.getClass().getName() + " " + msg.callback + " what=" + msg.what); } msg.recycleUnchecked(); } } 就是不断地从messageQueue中取得新消息,如果消息不为空就调用message地target也就是处理它的Handler处理它,为空就退出循环。queue.next()可能会阻塞,查了查资料,两种情况下线程会进入等待状态,两种情况,一是当消息队列中没有消息时,它会使线程进入等待状态;二是消息队列中有消息,但是消息指定了执行的时间,而现在还没有到这个时间,线程也会进入等待状态。消息队列中的消息是按时间先后来排序的,后面我们在分析消息的发送时会看到。 我觉主线程的消息队列随时都有消息,很少有空闲的时候,因为应用启动后,界面不断刷新,那些控件的触摸事件等等各种各样的事件都需要处理,也许都添加进了主线程的事件队列(这个有待验证,我推测是这样的),那这样,主线程的任务也太多了吧。

资源下载

更多资源
Mario

Mario

马里奥是站在游戏界顶峰的超人气多面角色。马里奥靠吃蘑菇成长,特征是大鼻子、头戴帽子、身穿背带裤,还留着胡子。与他的双胞胎兄弟路易基一起,长年担任任天堂的招牌角色。

腾讯云软件源

腾讯云软件源

为解决软件依赖安装时官方源访问速度慢的问题,腾讯云为一些软件搭建了缓存服务。您可以通过使用腾讯云软件源站来提升依赖包的安装速度。为了方便用户自由搭建服务架构,目前腾讯云软件源站支持公网访问和内网访问。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册