和上一篇tomcat sexxion共享一样,用的也是redis

代码:

  1. package com.test.shiro;
  2.  
  3. import com.jfinal.log.Log;
  4. import com.jfinal.plugin.redis.Redis;
  5. import org.apache.shiro.session.Session;
  6. import org.apache.shiro.session.UnknownSessionException;
  7. import org.apache.shiro.session.mgt.SimpleSession;
  8. import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO;
  9.  
  10. import java.io.*;
  11.  
  12. public class OnlineSessionDao extends EnterpriseCacheSessionDAO {
  13.  
  14. private static final Log log = Log.getLog(OnlineSessionDao.class);
  15.  
  16. //定义sessionDao缓存的前缀,可以通过 Redis.use().getJedis().keys(OnlineSessionDao.cacheNamePrefix + "*") 获取到sessionDao缓存的所有session
  17. public static final String cacheNamePrefix = "shiro_sessionDao_cache:";
  18.  
  19. private void set(String key, Object value){
  20. Redis.use().set(cacheNamePrefix + key, value);
  21. }
  22.  
  23. private Object get(String key){
  24. return Redis.use().get(cacheNamePrefix + key);
  25. }
  26.  
  27. private void remove(String key){
  28. Redis.use().del(cacheNamePrefix + key);
  29. }
  30.  
  31. /**
  32. * 创建session
  33. */
  34. @Override
  35. public Serializable doCreate(Session session) {
  36. Serializable sessionId = super.doCreate(session);
  37. log.info("创建 Session:"+session.getHost() + ";" + session.getId());
  38. set(session.getId().toString(), sessionToByte(session));
  39. return sessionId;
  40. }
  41.  
  42. /**
  43. * 删除session
  44. */
  45. @Override
  46. public void doDelete(Session session) {
  47. log.info("删除 Session:"+session.getHost() + ";" + session.getId());
  48. remove(session.getId().toString());
  49. super.doDelete(session);
  50. }
  51.  
  52. /**
  53. * 更新session的最后一次访问时间
  54. */
  55. @Override
  56. public void doUpdate(Session session) throws UnknownSessionException {
  57. log.info("更新 Session:"+session.getHost() + ";" + session.getId());
  58. set(session.getId().toString(), sessionToByte(session));
  59. super.doUpdate(session);
  60.  
  61. }
  62.  
  63. /**
  64. * 获取session
  65. */
  66. @Override
  67. protected Session doReadSession(Serializable sessionId) {
  68. Session session = super.doReadSession(sessionId);
  69. if(session == null){
  70. byte[] bytes = (byte[]) get(sessionId.toString());
  71. if(bytes != null && bytes.length > 0){
  72. session = byteToSession(bytes);
  73. }
  74. }
  75. return session;
  76. }
  77.  
  78. // 把session对象转化为byte保存到缓存中
  79. public byte[] sessionToByte(Session session){
  80. ByteArrayOutputStream bo = new ByteArrayOutputStream();
  81. byte[] bytes = null;
  82. try {
  83. ObjectOutputStream oo = new ObjectOutputStream(bo);
  84. oo.writeObject(session);
  85. bytes = bo.toByteArray();
  86. } catch (IOException e) {
  87. e.printStackTrace();
  88. }
  89. return bytes;
  90. }
  91.  
  92. // 把byte还原为session
  93. public Session byteToSession(byte[] bytes){
  94. ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
  95. ObjectInputStream in;
  96. SimpleSession session = null;
  97. try {
  98. in = new ObjectInputStream(bi);
  99. session = (SimpleSession) in.readObject();
  100. } catch (ClassNotFoundException e) {
  101. e.printStackTrace();
  102. } catch (IOException e) {
  103. e.printStackTrace();
  104. }
  105.  
  106. return session;
  107. }
  108. }

  

  1. package com.test.shiro;
  2.  
  3. import com.jfinal.log.Log;
  4. import org.apache.shiro.cache.Cache;
  5. import org.apache.shiro.cache.CacheException;
  6. import redis.clients.jedis.Jedis;
  7.  
  8. import java.util.*;
  9.  
  10. public class RedisCache <K, V> implements Cache<K, V> {
  11.  
  12. Log log = Log.getLog(RedisCache.class);
  13.  
  14. private RedisManage redisManage;
  15.  
  16. public RedisCache(RedisManage redisManage){
  17. this.redisManage = redisManage;
  18. }
  19.  
  20. private com.jfinal.plugin.redis.Cache getCache(){
  21. log.info("user cache :" + redisManage.getPrefix());
  22. return redisManage.getCache();
  23. }
  24.  
  25. public void clear() throws CacheException {
  26. // TODO Auto-generated method stub
  27. getCache().getJedis().flushDB();
  28. }
  29.  
  30. public V get(K key) throws CacheException {
  31. // TODO Auto-generated method stub
  32. return getCache().get(redisManage.getPrefix() + key);
  33. }
  34.  
  35. @SuppressWarnings("unchecked")
  36. public Set<K> keys() {
  37. // TODO Auto-generated method stub
  38. Jedis jedis = getCache().getJedis();
  39. Set<String> keys = jedis.keys(redisManage.getPrefix() + "*");
  40. Set<K> ks = new HashSet<K>();
  41. for (String key : keys) {
  42. ks.add((K)key);
  43. }
  44. return ks;
  45. }
  46.  
  47. public V put(K key, V value) throws CacheException {
  48. // TODO Auto-generated method stub
  49. getCache().set(redisManage.getPrefix() + key, value);
  50. return value;
  51. }
  52.  
  53. public V remove(K key) throws CacheException {
  54. // TODO Auto-generated method stub
  55. V value = getCache().get(redisManage.getPrefix() + key);
  56. getCache().del(redisManage.getPrefix() + key);
  57. return value;
  58. }
  59.  
  60. public int size() {
  61. // TODO Auto-generated method stub
  62. return keys().size();
  63. }
  64.  
  65. public Collection<V> values() {
  66. // TODO Auto-generated method stub
  67. Set<K> ks = keys();
  68. List<V> vs = new ArrayList<V>();
  69. for (K k : ks) {
  70. vs.add(get(k));
  71. }
  72. return vs;
  73. }
  74.  
  75. }
  1. package com.test.shiro;
  2.  
  3. import com.jfinal.log.Log;
  4. import org.apache.shiro.cache.Cache;
  5. import org.apache.shiro.cache.CacheException;
  6. import org.apache.shiro.cache.CacheManager;
  7.  
  8. import java.util.concurrent.ConcurrentHashMap;
  9. import java.util.concurrent.ConcurrentMap;
  10.  
  11. public class RedisCacheManage implements CacheManager {
  12. private static final Log log = Log.getLog(RedisCacheManage.class);
  13.  
  14. private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();
  15.  
  16. public <K, V> Cache<K, V> getCache(String name) throws CacheException {
  17. // TODO Auto-generated method stub
  18. log.info(String.format("获取redis %s 实例", name));
  19. if(caches.containsKey(name)){
  20. return caches.get(name);
  21. }
  22. RedisCache<K, V> redisCache = new RedisCache<K, V>(new RedisManage(name));
  23. caches.put(name, redisCache);
  24. return redisCache;
  25. }
  26. }
  1. package com.test.shiro;
  2.  
  3. import com.jfinal.plugin.redis.Redis;
  4.  
  5. public class RedisManage {
  6. private com.jfinal.plugin.redis.Cache cache;
  7.  
  8. //用于区分shiro不同的cache name
  9. private String prefix;
  10.  
  11. public RedisManage(String cachename) {
  12. // TODO Auto-generated constructor stub
  13. this.prefix = cachename + ":";
  14. }
  15.  
  16. public com.jfinal.plugin.redis.Cache getCache() {
  17. if(cache == null){
  18. //在jfinalConfig中添加redis插件 me.add(new RedisPlugin(Constant.REDIS_SHIROMANAGE_CACHE, "127.0.0.1", 6379));
  19. //cache = Redis.use(Constant.REDIS_SHIROMANAGE_CACHE);
  20. cache = Redis.use("jfinalShiro");
  21. }
  22. return cache;
  23. }
  24.  
  25. public String getPrefix(){
  26. return this.prefix;
  27. }
  28. }
  1. package com.test.shiro;
  2.  
  3. import com.test.common.model.AuthUser;
  4. import org.apache.shiro.authc.*;
  5. import org.apache.shiro.authz.AuthorizationInfo;
  6. import org.apache.shiro.authz.SimpleAuthorizationInfo;
  7. import org.apache.shiro.cache.Cache;
  8. import org.apache.shiro.realm.AuthorizingRealm;
  9. import org.apache.shiro.subject.PrincipalCollection;
  10. import org.apache.shiro.subject.SimplePrincipalCollection;
  11.  
  12. public class ShiroDbRealm extends AuthorizingRealm {
  13. /**
  14. * 认证回调函数,登录时调用.
  15. */
  16. @Override
  17. protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
  18. UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
  19. AuthUser user = AuthUser.dao.findByName(token.getUsername());
  20. if (user != null) {
  21. return new SimpleAuthenticationInfo(new ShiroUser(user), user.getPassword(), getName());
  22. } else {
  23. return null;
  24. }
  25. }
  26.  
  27. /**
  28. * 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
  29. */
  30. @Override
  31. protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
  32. ShiroUser user = (ShiroUser) principals.getPrimaryPrincipal();
  33.  
  34. SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
  35.  
  36. return info;
  37. }
  38.  
  39. /**
  40. * 更新用户授权信息缓存.
  41. */
  42. public void clearCachedAuthorizationInfo(String principal) {
  43. SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
  44. clearCachedAuthorizationInfo(principals);
  45. }
  46.  
  47. /**
  48. * 清除所有用户授权信息缓存.
  49. */
  50. public void clearAllCachedAuthorizationInfo() {
  51. Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
  52. if (cache != null) {
  53. for (Object key : cache.keys()) {
  54. cache.remove(key);
  55. }
  56. }
  57. }
  58. }
  1. public void configPlugin(Plugins plugins) {
  2.  
  3. plugins.add(new RedisPlugin("jfinalShiro", "ip", 6379,"123456"));
  4.  
  5. }

jfinal shiro共享的更多相关文章

  1. spring+shiro共享session完整小例子

    之前写过一个,只不过那个不单纯,有人跑不通,所以今天整个纯粹的小例子. 要求你有Redis. 源码 GitHub 目录结构 因为这是个例子,仅仅为了体现共享session,所以权限认证部分没有加入处理 ...

  2. springboot+shiro 01 - 实现权限控制

    sb_shiro_session <?xml version="1.0" encoding="UTF-8"?> <project xmlns= ...

  3. 集成Ehcache

    提醒 这一小节的是如何在应用层(service或者module或action类)中使用ehcache   准备工作 下载ehcache 你需要一个js文件   请务必阅读下面代码中的注释!! 分情况选 ...

  4. shiro实现session共享

    session共享:在多应用系统中,如果使用了负载均衡,用户的请求会被分发到不同的应用中,A应用中的session数据在B应用中是获取不到的,就会带来共享的问题. 假设:用户第一次访问,连接的A服务器 ...

  5. JFinal的Shiro权限管理插件--玛雅牛 / JFinalShiro

    http://git.oschina.net/myaniu/jfinalshiroplugin JFinalShiroPlugin JFinal的Shiro插件,实现权限管理. 升级说明 1)支持JF ...

  6. Apache shiro集群实现 (七)分布式集群系统下---cache共享

    Apache shiro集群实现 (一) shiro入门介绍 Apache shiro集群实现 (二) shiro 的INI配置 Apache shiro集群实现 (三)shiro身份认证(Shiro ...

  7. Apache shiro集群实现 (六)分布式集群系统下的高可用session解决方案---Session共享

    Apache shiro集群实现 (一) shiro入门介绍 Apache shiro集群实现 (二) shiro 的INI配置 Apache shiro集群实现 (三)shiro身份认证(Shiro ...

  8. Spring Boot分布式系统实践【扩展1】shiro+redis实现session共享、simplesession反序列化失败的问题定位及反思改进

    前言 调试之前请先关闭Favicon配置 spring:     favicon:       enabled: false 不然会发现有2个请求(如果用nginx+ 浏览器调试的话) 序列化工具类[ ...

  9. 使用redis进行基于shiro的session集群共享

    之前写过一篇nginx多tomcat负载均衡,主要记录了使用nginx对多个tomcat 进行负载均衡,其实进行负载均衡之前还有一个问题没有解决,那就是集群间的session共享,不然用户在登录网站之 ...

随机推荐

  1. 使用TensorRT对caffe和pytorch onnx版本的mnist模型进行fp32和fp16 推理 | tensorrt fp32 fp16 tutorial with caffe pytorch minist model

    本文首发于个人博客https://kezunlin.me/post/bcdfb73c/,欢迎阅读最新内容! tensorrt fp32 fp16 tutorial with caffe pytorch ...

  2. Ubuntu 16.04安装ROS Kinetic详细教程 | Tutorial to Install and Configure ROS Kinetic on Ubuntu 16.04

    本文首发于个人博客https://kezunlin.me/post/e2780b93/,欢迎阅读! Tutorial to Install and Configure ROS Kinetic on U ...

  3. 设计模式之美学习(九):业务开发常用的基于贫血模型的MVC架构违背OOP吗?

    我们都知道,很多业务系统都是基于 MVC 三层架构来开发的.实际上,更确切点讲,这是一种基于贫血模型的 MVC 三层架构开发模式. 虽然这种开发模式已经成为标准的 Web 项目的开发模式,但它却违反了 ...

  4. Hadoop运行模式

    Hadoop运行模式 (1)本地模式(默认模式): 不需要启用单独进程,直接可以运行,测试和开发时使用. 即在一台机器上进行操作,仅为单机版. 本地运行Hadoop官方MapReduce案例 操作命令 ...

  5. 依赖注入利器 - Dagger ‡

    转载请标明出处:http://blog.csdn.net/shensky711/article/details/53715960 本文出自: [HansChen的博客] 概述 声明需要注入的对象 如何 ...

  6. Mybatis拦截器实现原理深度分析

    1.拦截器简介 拦截器可以说使我们平时开发经常用到的技术了,Spring AOP.Mybatis自定义插件原理都是基于拦截器实现的,而拦截器又是以动态代理为基础实现的,每个框架对拦截器的实现不完全相同 ...

  7. c# 窗体开发4 数据库访问技术

    ADO.NET的名称起源于ADO(ACTIVEX DATA OBJECTS) USING SYSTEM; USING SYSTEM.COLLECTIONS.GENERIC; USING SYSTEM. ...

  8. iOS 一些struct类型的NSLog输出格式

    https://my.oschina.net/sayonala/blog/215910 我们经常会输出一些坐标尺寸信息之类的,比如view的frame,是CGRect类型的,用frame.oringi ...

  9. 华为云备案服务全面升级,EI助力带来极速体验

    华为云备案"电子化核验"正式发布,备案更轻松.更快捷.自2019年9月12日起,华为云用户申请办理ICP备案可以通过华为云APP进行"ICP备案主体真实身份信息采集&qu ...

  10. Python协程与Go协程的区别二

    写在前面 世界是复杂的,每一种思想都是为了解决某些现实问题而简化成的模型,想解决就得先面对,面对就需要选择角度,角度决定了模型的质量, 喜欢此UP主汤质看本质的哲学科普,其中简洁又不失细节的介绍了人类 ...