Foreword
This chapter describes the caching and session management of shiro
method
1. Concept
In the previous example, we found that every time we need certain access privileges url, the program will query role permissions required information automatically to the database, too much control once written on our menus and buttons, it will many times the corresponding database query.
Shown above, every time we need access rights to the database query page requires appropriate roles and permissions.
In order to avoid the above problems, we can configure shiro cache.
2.shiro cache management
1) introducing a jar cache coherency shiro
2) Configuration profile shiro
<!-- 配置Shiro的SecurityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
<property name="cacheManager" ref="cacheManager"/>
</bean>
<!-- 缓存管理器 使用Ehcache实现 -->
<bean id="cacheManager" class="org.apache.shiro.cache.ehcache.EhCacheManager">
<property name="cacheManagerConfigFile" value="classpath:ehcache.xml"/>
</bean>
3) Configuration ehcache.xml
Here used to use hibernate in a can.
4) test procedure
This time, we found userRealm in the authorization only gone once, the successful implementation of the cache.
So, one might ask, if I put it permission to change the background, you read cache, it is not wrong yet?
It does not matter, shiro had given us ready to refresh the cache function, this method only needs to be performed once on the line when the updated permissions.
The method of writing in userRealm, if necessary can be called directly! !
/**
* 清理缓存
*/
public void clearCache() {
Subject currentUser = SecurityUtils.getSubject();
super.clearCache(currentUser.getPrincipals());
}
3.shiro Session Management
We know, shiro can manage our session, such as setting session valid time, and so on.
1) Configuration profile shiro
<!-- 配置Shiro的SecurityManager -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm"/>
<property name="cacheManager" ref="cacheManager"/>
<property name="sessionManager" ref="sessionManager"/>
</bean>
<!-- 会话管理器 -->
<bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<!-- 配置session的失效时间 -->
<property name="globalSessionTimeout" value="10000"/>
<!-- 删除无效的session -->
<property name="deleteInvalidSessions" value="true"/>
</bean>
This get away.
2) verification process
Above we configured the 10s (10000ms) after failure of session, that is to log in again, we have to verify:
When we successfully log in using zhangsan, quietly waiting for the 10s is not operating, refresh the page again we'll find back to the login page: