目录
Shiro独立的会话管理,包含了单点登录的业务场景;Nginx负载多个tomcat;
Shiro提供了完整的企业级会话管理功能,不依赖于底层容器(如Tomcat),不管是J2SE还是J2EE环境都可以使用,提供了会话管理,会话事件监听,会话存储/持久化,容器无关的集群,失效/过期支持,对Web的透明支持,SSO单点登录的支持等特性。
所谓会话,即用户访问应用时保持的连接关系,在多次交互中应用能够识别出当前访问的用户是谁,且可以在多次交互中保存一些数据。如访问一些网站时登录成功后,网站可以记住用户,且在退出之前都可以识别当前用户是谁。
- package com.zlp.ssm.shiro;
-
- import org.apache.shiro.session.Session;
- import org.apache.shiro.session.SessionListener;
-
- public class ShiroSessionListener implements SessionListener {
- @Override
- public void onStart(Session session) {
- System.out.println("ShiroSessionListener.onstart..."+session.getId());
- }
-
- @Override
- public void onStop(Session session) {
- System.out.println("ShiroSessionListener.onStop..."+session.getId());
- }
-
- @Override
- public void onExpiration(Session session) {
- System.out.println("ShiroSessionListener.onExpiration..."+session.getId());
- }
- }
-
Shiro提供SessionDAO用于会话的CRUD,即DAO(Data Access Object)模式实现。
1)AbstractSessionDAO:提供了SessionDAO的基础实现,如生成会话ID等
2)CachingSessionDAO:提供了对开发者透明的会话缓存的功能,需要设置相应的CacheManager
3)MemorySessionDAO:直接在内存中进行会话维护(默认方式)
4)EnterpriseCacheSessionDAO:提供了缓存功能的会话维护,默认情况下使用MapCache实现,内部使用ConcurrentHashMap保存缓存的会话。
自定义一个监听器类并实现SessionListener接口
在Spring与shiro的整合配置文件中配置相关文件
SessionLestentener
- package com.zlp.shiroo;
-
- import org.apache.shiro.session.Session;
- import org.apache.shiro.session.SessionListener;
-
- public class SessionLestentener implements SessionListener {
- @Override
- public void onStart(Session session) {
- System.out.println("SessionLestentener.onStart "+session.getId());
- }
-
- @Override
- public void onStop(Session session) {
- System.out.println("SessionLestentener.onStop "+session.getId());
- }
-
- @Override
- public void onExpiration(Session session) {
- System.out.println("SessionLestentener.onExpiration "+session.getId());
- }
- }
Spring-shiro.xml
-
- <bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
- <property name="realm" ref="shiroRealm" />
- <property name="sessionManager" ref="sessionManager">property>
- bean>
-
- <bean id="sessionIdGenerator" class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator">
- bean>
-
-
- <bean id="customSessionDao" class="org.apache.shiro.session.mgt.eis.MemorySessionDAO">
- <property name="sessionIdGenerator" ref="sessionIdGenerator"/>
- bean>
-
-
- <bean id="shiroSessionListener" class="com.zlp.ssm.shiro.ShiroSessionListener"/>
-
-
- <bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
-
- <constructor-arg value="shiro.session"/>
-
- <property name="maxAge" value="-1"/>
-
- <property name="httpOnly" value="true"/>
- bean>
-
-
- <bean id="sessionManager" class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
-
- <property name="globalSessionTimeout" value="120000"/>
-
- <property name="sessionDAO" ref="customSessionDao"/>
-
- <property name="sessionValidationInterval" value="60000"/>
-
-
-
-
-
- <property name="deleteInvalidSessions" value="true"/>
-
- <property name="sessionListeners">
- <list>
- <ref bean="shiroSessionListener"/>
- list>
- property>
-
- <property name="sessionIdCookie" ref="sessionIdCookie"/>
-
- <property name="sessionIdUrlRewritingEnabled" value="false"/>
- bean>
解决反复授权查询数据库的问题
- package com.zlp.ssm.ehcache;
-
- import java.util.HashMap;
- import java.util.Map;
-
- /**
- * 利用map集合简易实现缓存原理
- * @author zjjt
- *
- */
- public class EhcacheDemo1 {
- static Map<String, Object> cache = new HashMap<String, Object>();
- static Object getValue(String key) {
- Object value = cache.get(key);
- if(value == null) {
- System.out.println("hello zs");
- cache.put(key, new String[] {"zs"});
- return cache.get(key);
- }
- return value;
- }
-
- public static void main(String[] args) {
- System.out.println(getValue("sname"));
- System.out.println(getValue("sname"));
- }
- }
-
- "1.0" encoding="UTF-8"?>
- <ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:noNamespaceSchemaLocation="http://ehcache.org/ehcache.xsd"
- updateCheck="false">
-
-
-
- <diskStore path="D://xxx"/>
-
-
-
-
-
-
-
-
-
-
-
-
-
- <defaultCache eternal="false" maxElementsInMemory="1000" overflowToDisk="false" diskPersistent="false"
- timeToIdleSeconds="0" timeToLiveSeconds="600" memoryStoreEvictionPolicy="LRU"/>
-
-
-
- <cache name="com.javaxl.one.entity.User" eternal="false" maxElementsInMemory="100"
- overflowToDisk="true" diskPersistent="true" timeToIdleSeconds="0"
- timeToLiveSeconds="300" memoryStoreEvictionPolicy="LRU"/>
- ehcache>
-
- package com.zlp.ssm.ehcache;
-
- import net.sf.ehcache.Cache;
- import net.sf.ehcache.CacheManager;
- import net.sf.ehcache.Element;
-
- import java.io.InputStream;
-
- public class EhcacheUtil {
-
- private static CacheManager cacheManager;
-
- static {
- try {
- InputStream is = EhcacheUtil.class.getResourceAsStream("/ehcache.xml");
- cacheManager = CacheManager.create(is);
- } catch (Exception e) {
- throw new RuntimeException(e);
- }
- }
-
- private EhcacheUtil() {
- }
-
- public static void put(String cacheName, Object key, Object value) {
- Cache cache = cacheManager.getCache(cacheName);
- if (null == cache) {
- //以默认配置添加一个名叫cacheName的Cache
- cacheManager.addCache(cacheName);
- cache = cacheManager.getCache(cacheName);
- }
- cache.put(new Element(key, value));
- }
-
-
- public static Object get(String cacheName, Object key) {
- Cache cache = cacheManager.getCache(cacheName);
- if (null == cache) {
- //以默认配置添加一个名叫cacheName的Cache
- cacheManager.addCache(cacheName);
- cache = cacheManager.getCache(cacheName);
- }
- Element element = cache.get(key);
- return null == element ? null : element.getValue();
- }
-
- public static void remove(String cacheName, Object key) {
- Cache cache = cacheManager.getCache(cacheName);
- cache.remove(key);
- }
- }
-
演示利用缓存存储数据
- package com.zlp.ssm.ehcache;
-
-
- /**
- * 演示利用缓存存储数据
- * @author Administrator
- *
- */
- public class EhcacheDemo2 {
- public static void main(String[] args) {
- System.out.println(System.getProperty("java.io.tmpdir"));
- // EhcacheUtil.put("com.javaxl.four.entity.Book", 11, "zhangsan");
- // System.out.println(EhcacheUtil.get("com.javaxl.four.entity.Book", 11));
-
- EhcacheUtil.put("com.javaxl.one.entity.User", 11, "zhangsan");
- System.out.println(EhcacheUtil.get("com.javaxl.one.entity.User", 11));
-
- }
- }
-
- package com.zlp.ssm.shiro;
-
- import com.zlp.ssm.biz.UserBiz;
- import com.zlp.ssm.ehcache.EhcacheUtil;
- import com.zlp.ssm.model.User;
- import org.apache.shiro.authc.AuthenticationException;
- import org.apache.shiro.authc.AuthenticationInfo;
- import org.apache.shiro.authc.AuthenticationToken;
- import org.apache.shiro.authc.SimpleAuthenticationInfo;
- import org.apache.shiro.authz.AuthorizationInfo;
- import org.apache.shiro.authz.SimpleAuthorizationInfo;
- import org.apache.shiro.realm.AuthorizingRealm;
- import org.apache.shiro.subject.PrincipalCollection;
- import org.apache.shiro.util.ByteSource;
-
- import java.util.Set;
-
- public class Myrealm extends AuthorizingRealm {
- private UserBiz userBiz;
-
- public UserBiz getUserBiz() {
- return userBiz;
- }
-
- public void setUserBiz(UserBiz userBiz) {
- this.userBiz = userBiz;
- }
-
- @Override
- protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
- System.out.println("用户授权...");
- String username = principals.getPrimaryPrincipal().toString();
- User user = userBiz.queryByName(username);
- String user_role_key = "user:roles:";
- String user_pers_key = "user:pers:";
- Set<String> roles = userBiz.getRolesByUserId(user.getUsername());
- Set<String> pers = userBiz.getPersByUserId(user.getUsername());
- if(roles == null||roles.size()==0){
- System.out.println("从数据库中获取相关角色信息...");
- roles=userBiz.getRolesByUserId(user.getUsername());
- EhcacheUtil.put(user_role_key+user.getUserid(),user.getUserid(),roles);
- }
- if(pers==null||pers.size()==0){
- System.out.println("从数据库中获取相关权限信息...");
- pers=userBiz.getPersByUserId(user.getUsername());
- EhcacheUtil.put(user_pers_key+user.getUserid(),user.getUserid(),pers);
- }
- SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();
- info.setRoles(roles);
- info.setStringPermissions(pers);
- return info;
- }
-
- @Override
- protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
- System.out.println("身份验证...");
- String username = token.getPrincipal().toString();
- String password = token.getCredentials().toString();
- User user = userBiz.queryByName(username);
- AuthenticationInfo info=new SimpleAuthenticationInfo(
- user.getUsername(),
- user.getPassword(),
- ByteSource.Util.bytes(user.getSalt()),
- this.getName()
- );
- return info;
- }
- }
-
今天的分享就到这啦!!!我们下期再见~~~~