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

代码:

package com.test.shiro;

import com.jfinal.log.Log;
import com.jfinal.plugin.redis.Redis;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.SimpleSession;
import org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO; import java.io.*; public class OnlineSessionDao extends EnterpriseCacheSessionDAO { private static final Log log = Log.getLog(OnlineSessionDao.class); //定义sessionDao缓存的前缀,可以通过 Redis.use().getJedis().keys(OnlineSessionDao.cacheNamePrefix + "*") 获取到sessionDao缓存的所有session
public static final String cacheNamePrefix = "shiro_sessionDao_cache:"; private void set(String key, Object value){
Redis.use().set(cacheNamePrefix + key, value);
} private Object get(String key){
return Redis.use().get(cacheNamePrefix + key);
} private void remove(String key){
Redis.use().del(cacheNamePrefix + key);
} /**
* 创建session
*/
@Override
public Serializable doCreate(Session session) {
Serializable sessionId = super.doCreate(session);
log.info("创建 Session:"+session.getHost() + ";" + session.getId());
set(session.getId().toString(), sessionToByte(session));
return sessionId;
} /**
* 删除session
*/
@Override
public void doDelete(Session session) {
log.info("删除 Session:"+session.getHost() + ";" + session.getId());
remove(session.getId().toString());
super.doDelete(session);
} /**
* 更新session的最后一次访问时间
*/
@Override
public void doUpdate(Session session) throws UnknownSessionException {
log.info("更新 Session:"+session.getHost() + ";" + session.getId());
set(session.getId().toString(), sessionToByte(session));
super.doUpdate(session); } /**
* 获取session
*/
@Override
protected Session doReadSession(Serializable sessionId) {
Session session = super.doReadSession(sessionId);
if(session == null){
byte[] bytes = (byte[]) get(sessionId.toString());
if(bytes != null && bytes.length > 0){
session = byteToSession(bytes);
}
}
return session;
} // 把session对象转化为byte保存到缓存中
public byte[] sessionToByte(Session session){
ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] bytes = null;
try {
ObjectOutputStream oo = new ObjectOutputStream(bo);
oo.writeObject(session);
bytes = bo.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return bytes;
} // 把byte还原为session
public Session byteToSession(byte[] bytes){
ByteArrayInputStream bi = new ByteArrayInputStream(bytes);
ObjectInputStream in;
SimpleSession session = null;
try {
in = new ObjectInputStream(bi);
session = (SimpleSession) in.readObject();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} return session;
}
}

  

package com.test.shiro;

import com.jfinal.log.Log;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import redis.clients.jedis.Jedis; import java.util.*; public class RedisCache <K, V> implements Cache<K, V> { Log log = Log.getLog(RedisCache.class); private RedisManage redisManage; public RedisCache(RedisManage redisManage){
this.redisManage = redisManage;
} private com.jfinal.plugin.redis.Cache getCache(){
log.info("user cache :" + redisManage.getPrefix());
return redisManage.getCache();
} public void clear() throws CacheException {
// TODO Auto-generated method stub
getCache().getJedis().flushDB();
} public V get(K key) throws CacheException {
// TODO Auto-generated method stub
return getCache().get(redisManage.getPrefix() + key);
} @SuppressWarnings("unchecked")
public Set<K> keys() {
// TODO Auto-generated method stub
Jedis jedis = getCache().getJedis();
Set<String> keys = jedis.keys(redisManage.getPrefix() + "*");
Set<K> ks = new HashSet<K>();
for (String key : keys) {
ks.add((K)key);
}
return ks;
} public V put(K key, V value) throws CacheException {
// TODO Auto-generated method stub
getCache().set(redisManage.getPrefix() + key, value);
return value;
} public V remove(K key) throws CacheException {
// TODO Auto-generated method stub
V value = getCache().get(redisManage.getPrefix() + key);
getCache().del(redisManage.getPrefix() + key);
return value;
} public int size() {
// TODO Auto-generated method stub
return keys().size();
} public Collection<V> values() {
// TODO Auto-generated method stub
Set<K> ks = keys();
List<V> vs = new ArrayList<V>();
for (K k : ks) {
vs.add(get(k));
}
return vs;
} }
package com.test.shiro;

import com.jfinal.log.Log;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager; import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap; public class RedisCacheManage implements CacheManager {
private static final Log log = Log.getLog(RedisCacheManage.class); private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>(); public <K, V> Cache<K, V> getCache(String name) throws CacheException {
// TODO Auto-generated method stub
log.info(String.format("获取redis %s 实例", name));
if(caches.containsKey(name)){
return caches.get(name);
}
RedisCache<K, V> redisCache = new RedisCache<K, V>(new RedisManage(name));
caches.put(name, redisCache);
return redisCache;
}
}
package com.test.shiro;

import com.jfinal.plugin.redis.Redis;

public class RedisManage {
private com.jfinal.plugin.redis.Cache cache; //用于区分shiro不同的cache name
private String prefix; public RedisManage(String cachename) {
// TODO Auto-generated constructor stub
this.prefix = cachename + ":";
} public com.jfinal.plugin.redis.Cache getCache() {
if(cache == null){
//在jfinalConfig中添加redis插件 me.add(new RedisPlugin(Constant.REDIS_SHIROMANAGE_CACHE, "127.0.0.1", 6379));
//cache = Redis.use(Constant.REDIS_SHIROMANAGE_CACHE);
cache = Redis.use("jfinalShiro");
}
return cache;
} public String getPrefix(){
return this.prefix;
}
}
package com.test.shiro;

import com.test.common.model.AuthUser;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection; public class ShiroDbRealm extends AuthorizingRealm {
/**
* 认证回调函数,登录时调用.
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
AuthUser user = AuthUser.dao.findByName(token.getUsername());
if (user != null) {
return new SimpleAuthenticationInfo(new ShiroUser(user), user.getPassword(), getName());
} else {
return null;
}
} /**
* 授权查询回调函数, 进行鉴权但缓存中无用户的授权信息时调用.
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
ShiroUser user = (ShiroUser) principals.getPrimaryPrincipal(); SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(); return info;
} /**
* 更新用户授权信息缓存.
*/
public void clearCachedAuthorizationInfo(String principal) {
SimplePrincipalCollection principals = new SimplePrincipalCollection(principal, getName());
clearCachedAuthorizationInfo(principals);
} /**
* 清除所有用户授权信息缓存.
*/
public void clearAllCachedAuthorizationInfo() {
Cache<Object, AuthorizationInfo> cache = getAuthorizationCache();
if (cache != null) {
for (Object key : cache.keys()) {
cache.remove(key);
}
}
}
}
public void configPlugin(Plugins plugins) {

        plugins.add(new RedisPlugin("jfinalShiro", "ip", 6379,"123456"));

    }

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. windows 10 上使用pybind11进行C++和Python代码相互调用 | Interfacing C++ and Python with pybind11 on windows 10

    本文首发于个人博客https://kezunlin.me/post/8b9c051d/,欢迎阅读! Interfacing C++ and Python with pybind11 on window ...

  2. C#连接SAP【生产系统与ERP对接】

    企业如果上了ERP系统,比如SAP.用友.金蝶或者E10等等,只需要ERP里面提供相应的接口,则可以直接将PMC创建的工单信息抛转至 MTS 系统,当该工单生产完成之后,MTS 将完成数据回传至 ER ...

  3. 【Luogu P3384】树链剖分模板

    树链剖分的基本思想是把一棵树剖分成若干条链,再利用线段树等数据结构维护相关数据,可以非常暴力优雅地解决很多问题. 树链剖分中的几个基本概念: 重儿子:对于当前节点的所有儿子中,子树大小最大的一个儿子就 ...

  4. 洛谷P1402——乒乓球

    原题链接: https://www.luogu.com.cn/problem/P1042 题面简述 国际乒联现在主席沙拉拉自从上任以来就立志于推行一系列改革,以推动乒乓球运动在全球的普及.其中11分制 ...

  5. Java异常处理只有Try-Catch吗?

    今天,我们将讨论一个非常重要的主题-Java 中的异常处理.尽管有时可能会对此主题进行过多的讨论,但并非每篇文章都包含有用且相关的信息. Java 中最常见的异常处理机制通常与 try-catch 块 ...

  6. 【数据结构】之二叉树(Java语言描述)

    有关树的一些基础知识点请参考[这篇文章]. 本文主要记录Java语言描述的二叉树相关的一些操作,如创建.遍历等. 首先,我们需要一个表示树中节点的数据结构TreeNode,代码如下: public c ...

  7. Zookeeper 应用实现-配置中心

    一.目标 一个乞丐版自更新配置中心,更新配置后,能在各个服务器实现更新 二.架构 三.角色 config-web: 配置后台,主要用于管理配置,增改配置 config-agent: 监听配置,遇到变动 ...

  8. C语音I博客作业09

    ------------恢复内容开始------------ 这个作业属于那个课程|C语言程序设计II --|:--:|--: 这个作业要求在哪里|https://edu.cnblogs.com/ca ...

  9. PHP数组总汇

    数组,顾名思义,本质上就是一系列数据的组合.在这个组合中,每个数据都是独立的,可以对每个单独的数据进行分配和读取.PHP对数据的操作能力非常强大,尤其是PHP为程序开发人员提供了大量方便.易懂的数组操 ...

  10. Spring Cloud第四篇 | 客户端负载均衡Ribbon

    ​ 本文是Spring Cloud专栏的第四篇文章,了解前三篇文章内容有助于更好的理解本文: ​Spring Cloud第一篇 | Spring Cloud前言及其常用组件介绍概览 Spring Cl ...