>  기사  >  Java  >  shiro의 소스코드 학습에서 Session session = getSession() 분석 예시

shiro의 소스코드 학습에서 Session session = getSession() 분석 예시

黄舟
黄舟원래의
2017-07-24 13:26:517410검색

subject는 로그인, 로그아웃, 역할/권한 보기 등 사용자가 서버에 액세스하는 일부 작업을 나타냅니다.

동시에 subject.getSession(), 이 인터페이스, 이전에 세션이 존재하지 않았다면 세션을 생성하십시오. 생성 과정은 대략 다음과 같습니다.

주체는 SecurityManager에 생성을 맡기고, SecurityManager는 SessionManager에 생성을 맡기고, SessionManager는 SessionFactory 팩토리를 통해 생성됩니다. 시로의 창작과정은 분업이 명확하게 되어 있음을 알 수 있다.

생성 과정은 다음과 같이 분석됩니다.

(1) DelegatingSubject 클래스에서 세션을 얻을 수 있습니다:

public Session getSession(boolean create) {
      .......
      SessionContext sessionContext = createSessionContext();
      //创建Session上下文,context有个backMap,存放创建Session时所需的数据
      Session session = this.securityManager.start(sessionContext);
      this.session = decorate(session);//创建代理session,当session.stop()调用时,清空subject的session
      .......
      return this.session;//返回代理session
 }

(2)SecurityManager는 sessionManager(DefaultSessionManage)에 세션 생성을 처리하도록 맡깁니다:

1 public Session start(SessionContext context) throws AuthorizationException {
2     return this.sessionManager.start(context);
3     }

*참고: DefaultSessionManage의 내부 구조는 다음과 같습니다.

(3) AbstractNativeSessionManager가 Session을 생성하고 Session을 관리합니다:

public Session start(SessionContext context) {
        Session session = createSession(context);//通过模板模式,子类实现通过上下仍创建Session
        applyGlobalSessionTimeout(session);//更新sessionDAO的sessions(map<String,session>)
        onStart(session, context);//一个槽点,待子类实现
        notifyStart(session);//注册的监听器开始执行
        //Don&#39;t expose the EIS-tier Session object to the client-tier:
        return createExposedSession(session, context);//创建暴露的Session
    }

(4) Session 생성이 완료되었으며, 자세한 코드는 다음과 같습니다. AbstractNativeSessionManager는 처리를 위해 AbstractValidatingSessionManager로 넘겨집니다.

protected Session createSession(SessionContext context) throws AuthorizationException {
        enableSessionValidationIfNecessary();
        //创建Session之前,先起一个Session自动定时任务的线程去执行,校验sessionDAO的sessions是否过期。
        return doCreateSession(context);
    }
//
private void enableSessionValidationIfNecessary() {
        SessionValidationScheduler scheduler = getSessionValidationScheduler();
        if (isSessionValidationSchedulerEnabled() && (scheduler == null || !scheduler.isEnabled())) {
            enableSessionValidation();
        }
    }
//
protected void enableSessionValidation() {
        SessionValidationScheduler scheduler = getSessionValidationScheduler();
        if (scheduler == null) {
            scheduler = createSessionValidationScheduler();
            //scheduler = new ExecutorServiceSessionValidationScheduler(this);scheduler.setInterval(getSessionValidationInterval());
            setSessionValidationScheduler(scheduler);
        }
        if (log.isInfoEnabled()) {
            log.info("Enabling session validation scheduler...");
        }
        scheduler.enableSessionValidation();//自动任务启动执行
        afterSessionValidationEnabled();//一个槽点,待子类实现
}

(5) ExecutorServiceSessionValidationScheduler는 만료 of 세션:

/**
     * Creates a single thread {@link ScheduledExecutorService} to validate sessions at fixed intervals 
     * and enables this scheduler. The executor is created as a daemon thread to allow JVM to shut down
     */
    //TODO Implement an integration test to test for jvm exit as part of the standalone example
    // (so we don&#39;t have to change the unit test execution model for the core module)
    public void enableSessionValidation() {
        if (this.interval > 0l) {
            this.service = Executors.newSingleThreadScheduledExecutor(new ThreadFactory() {  
            public Thread newThread(Runnable r) {  
                Thread thread = new Thread(r);  
                thread.setDaemon(true);  
                return thread;  
                }  
            });                  
            this.service.scheduleAtFixedRate(this, interval, interval, TimeUnit.MILLISECONDS);
            this.enabled = true;
        }
    }

    public void run() {
        if (log.isDebugEnabled()) {
            log.debug("Executing session validation...");
        }
        long startTime = System.currentTimeMillis();
        this.sessionManager.validateSessions();//ExecutorServiceSessionValidationSchedule的在被SessionManager创建里,
        long stopTime = System.currentTimeMillis();
        if (log.isDebugEnabled()) {
            log.debug("Session validation completed successfully in " + (stopTime - startTime) + " milliseconds.");
        }
    }

(6) AbstractValidatingSessionManager 세션 만료 확인:

/**
     * @see ValidatingSessionManager#validateSessions()
     */
    public void validateSessions() {
        if (log.isInfoEnabled()) {
            log.info("Validating all active sessions...");
        }
        int invalidCount = 0;
        Collection<Session> activeSessions = getActiveSessions();//获取取保存的Session
        if (activeSessions != null && !activeSessions.isEmpty()) {
            for (Session s : activeSessions) {
                try {
                    //simulate a lookup key to satisfy the method signature.
                    //this could probably stand to be cleaned up in future versions:
                    SessionKey key = new DefaultSessionKey(s.getId());
                    validate(s, key);
                } catch (InvalidSessionException e) {
                    if (log.isDebugEnabled()) {
                        boolean expired = (e instanceof ExpiredSessionException);
                        String msg = "Invalidated session with id [" + s.getId() + "]" +
                                (expired ? " (expired)" : " (stopped)");
                        log.debug(msg);
                    }
                    invalidCount++;
                }
            }
        }

        if (log.isInfoEnabled()) {
            String msg = "Finished session validation.";
            if (invalidCount > 0) {
                msg += "  [" + invalidCount + "] sessions were stopped.";
            } else {
                msg += "  No sessions were stopped.";
            }
            log.info(msg);
        }
    }
    //类DefaultSessionManager实现getActiveSessions接口
    protected abstract Collection<Session> getActiveSessions();

     protected Collection<Session> getActiveSessions() {
        Collection<Session> active = sessionDAO.getActiveSessions();
        return active != null ? active : Collections.<Session>emptySet();
    }

(7) 세션 확인이 완료되고 DefaultSessionManager가 세션을 생성합니다.

protected Session doCreateSession(SessionContext context) {
        Session s = newSessionInstance(context);
        if (log.isTraceEnabled()) {
            log.trace("Creating session for host {}", s.getHost());
         }
        create(s);
        return s;
     }

   protected Session newSessionInstance(SessionContext context) {
      return getSessionFactory().createSession(context);
   }
   protected void create(Session session) {
      if (log.isDebugEnabled()) {
         log.debug("Creating new EIS record for new session instance [" + session + "]");
        }
      sessionDAO.create(session);
    }

(8) DefaultSessionManager는 Session을 유지하기 위한 Session(MemorySessionDAO):

protected Serializable doCreate(Session session) {
        Serializable sessionId = generateSessionId(session);
        assignSessionId(session, sessionId);
        storeSession(sessionId, session);
        return sessionId;
    }
        protected Session storeSession(Serializable id, Session session) {
          if (id == null) {
             throw new NullPointerException("id argument cannot be null.");
          }
          return sessions.putIfAbsent(id, session);
        }

(9) 생성 및 유지 Session이 끝난 후 AbstractNativeSessionManager가 등록된 리스너에게 넘겨지고 리스너는 onStart 인터페이스

  protected void notifyStart(Session session) {
  2         for (SessionListener listener : this.listeners) {
  3             listener.onStart(session);
  4         }
  5     }

(10)를 호출하고 마지막으로 델리게이트를 생성합니다. Session,

protected Session createExposedSession(Session session, SessionContext context) {        
return new DelegatingSession(this, new DefaultSessionKey(session.getId()));
    }

(11) 마지막으로 주체는 주로 중지 메서드를 가로채는 데 사용되는 자체 프록시 세션을 생성합니다.

protected Session decorate(Session session) {
         if (session == null) {
             throw new IllegalArgumentException("session cannot be null");
         }
         return new StoppingAwareProxiedSession(session, this);
     }
    private class StoppingAwareProxiedSession extends ProxiedSession {

           private final DelegatingSubject owner;

           private StoppingAwareProxiedSession(Session target, DelegatingSubject owningSubject) {
                super(target);
                owner = owningSubject;
            }
16            public void stop() throws InvalidSessionException {
           super.stop();
           owner.sessionStopped();
         }
       }

요약: 세션(SimpleSession)이 DefaultSessionManage에서 생성되면 DelegatingSession에 캡슐화됩니다. 주제에 프록시 세션(StoppingAwareProxiedSession)으로 장식되어 있어 원본 데이터가 잘 보존되어 클라이언트가 Session

........


위 내용은 shiro의 소스코드 학습에서 Session session = getSession() 분석 예시의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
이전 기사:Ant 시작하기다음 기사:Ant 시작하기