Java使用reids,以及redis与shiro集成
package org.calonlan.security.component; import java.util.Iterator;
import java.util.Set; import org.springframework.beans.factory.annotation.Value; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; /**
* @author Administrator
* redismanager主要用来给用户提供一个设计完备的,通过jedis的jar包来管理redis内存数据库的各种方法
*/
public class RedisManager { // ip和port属性都定义在了properties文件中,这里通过spring的注解方式来直接使用
@Value("${redis.ip}")
private String host;
@Value("${redis.port}")
private int port; // 设置为0的话就是永远都不会过期
private int expire = 0; // 定义一个管理池,所有的redisManager共同使用。
private static JedisPool jedisPool = null; public RedisManager() {
} /**
*
* 初始化方法,在这个方法中通过host和port来初始化jedispool。
*
* */ public void init() {
if (null == host || 0 == port) {
System.out.println("请初始化redis配置文件");
throw new NullPointerException("找不到redis配置");
}
if (jedisPool == null) {
jedisPool = new JedisPool(new JedisPoolConfig(), host, port);
}
} /**
* get value from redis
*
* @param key
* @return
*/
public byte[] get(byte[] key) {
byte[] value = null;
Jedis jedis = jedisPool.getResource();
try {
value = jedis.get(key);
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* get value from redis
*
* @param key
* @return
*/
public String get(String key) {
String value = null;
Jedis jedis = jedisPool.getResource();
try {
value = jedis.get(key);
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* set
*
* @param key
* @param value
* @return
*/
public byte[] set(byte[] key, byte[] value) {
Jedis jedis = jedisPool.getResource();
try {
jedis.set(key, value);
if (this.expire != 0) {
jedis.expire(key, this.expire);
}
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* set
*
* @param key
* @param value
* @return
*/
public String set(String key, String value) {
Jedis jedis = jedisPool.getResource();
try {
jedis.set(key, value);
if (this.expire != 0) {
jedis.expire(key, this.expire);
}
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* set
*
* @param key
* @param value
* @param expire
* @return
*/
public byte[] set(byte[] key, byte[] value, int expire) {
Jedis jedis = jedisPool.getResource();
try {
jedis.set(key, value);
if (expire != 0) {
jedis.expire(key, expire);
}
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* set
*
* @param key
* @param value
* @param expire
* @return
*/
public String set(String key, String value, int expire) {
Jedis jedis = jedisPool.getResource();
try {
jedis.set(key, value);
if (expire != 0) {
jedis.expire(key, expire);
}
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* del
*
* @param key
*/
public void del(byte[] key) {
Jedis jedis = jedisPool.getResource();
try {
jedis.del(key);
} finally {
jedisPool.returnResource(jedis);
}
} /**
* del
*
* @param key
*/
public void del(String key) {
Jedis jedis = jedisPool.getResource();
try {
jedis.del(key);
} finally {
jedisPool.returnResource(jedis);
}
} /**
* flush
*/
public void flushDB() {
Jedis jedis = jedisPool.getResource();
try {
jedis.flushDB();
} finally {
jedisPool.returnResource(jedis);
}
} /**
* size
*/
public Long dbSize() {
Long dbSize = 0L;
Jedis jedis = jedisPool.getResource();
try {
dbSize = jedis.dbSize();
} finally {
jedisPool.returnResource(jedis);
}
return dbSize;
} /**
* keys
*
* @param regex
* @return
*/
public Set<byte[]> keys(String pattern) {
Set<byte[]> keys = null;
Jedis jedis = jedisPool.getResource();
try {
keys = jedis.keys(pattern.getBytes());
} finally {
jedisPool.returnResource(jedis);
}
return keys;
} public void dels(String pattern) {
Set<byte[]> keys = null;
Jedis jedis = jedisPool.getResource();
try {
keys = jedis.keys(pattern.getBytes());
Iterator<byte[]> ito = keys.iterator();
while (ito.hasNext()) {
jedis.del(ito.next());
}
} finally {
jedisPool.returnResource(jedis);
}
} public String getHost() {
return host;
} public void setHost(String host) {
this.host = host;
} public int getPort() {
return port;
} public void setPort(int port) {
this.port = port;
} public int getExpire() {
return expire;
} public void setExpire(int expire) {
this.expire = expire;
}
}
这里的redisManager是通过spring来进行管理的,所以直接使用了@value来读取properties文件中的属性。properties文件的内容如下:
<span style="white-space:pre"> </span>redis.ip=127.0.0.1
<span style="white-space:pre"> </span> redis.port=6379
ip定义为本机的ip,端口是redis默认的6379端口。
<bean id="propertyConfigurer"
class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:/config/jdbc.properties</value>
<value>classpath:/config/redis.properties</value>
</list>
</property>
</bean>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util-3.0.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/jee
http://www.springframework.org/schema/jee/spring-jee-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd"
default-lazy-init="false"> <!-- 缓存管理器 -->
<bean id="cacheManager" class="org.calonlan.security.spring.SpringCacheManagerWrapper">
<property name="cacheManager" ref="springCacheManager" />
</bean> <!-- 凭证匹配器 -->
<bean id="credentialsMatcher"
class="org.calonlan.security.credentials.RetryLimitHashedCredentialsMatcher">
<constructor-arg ref="cacheManager" />
<property name="hashAlgorithmName" value="md5" />
<property name="hashIterations" value="2" />
<property name="storedCredentialsHexEncoded" value="true" />
</bean> <!-- Realm实现 -->
<bean id="userRealm" class="org.calonlan.security.realm.UserRealm">
<property name="credentialsMatcher" ref="credentialsMatcher" />
<property name="cachingEnabled" value="true" />
<!--<property name="authenticationCachingEnabled" value="true"/> -->
<!--<property name="authenticationCacheName" value="authenticationCache"/> -->
<!--<property name="authorizationCachingEnabled" value="true"/> -->
<!--<property name="authorizationCacheName" value="authorizationCache"/> -->
</bean> <!-- 会话ID生成器 -->
<bean id="sessionIdGenerator"
class="org.apache.shiro.session.mgt.eis.JavaUuidSessionIdGenerator" /> <!-- 会话Cookie模板 -->
<bean id="sessionIdCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="sid" />
<property name="httpOnly" value="true" />
<property name="maxAge" value="-1" />
</bean> <bean id="rememberMeCookie" class="org.apache.shiro.web.servlet.SimpleCookie">
<constructor-arg value="rememberMe" />
<property name="httpOnly" value="true" />
<property name="maxAge" value="2592000" /><!-- 30天 -->
</bean> <!-- rememberMe管理器 -->
<bean id="rememberMeManager" class="org.apache.shiro.web.mgt.CookieRememberMeManager">
<!-- rememberMe cookie加密的密钥 建议每个项目都不一样 默认AES算法 密钥长度(128 256 512 位) -->
<property name="cipherKey"
value="#{T(org.apache.shiro.codec.Base64).decode('4AvVhmFLUs0KTA3Kprsdag==')}" />
<property name="cookie" ref="rememberMeCookie" />
</bean> <!-- 会话DAO -->
<bean id="sessionDAO"
class="org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO">
<property name="activeSessionsCacheName" value="shiro-activeSessionCache" />
<property name="sessionIdGenerator" ref="sessionIdGenerator" />
</bean> <!-- 会话验证调度器 -->
<bean id="sessionValidationScheduler"
class="org.apache.shiro.session.mgt.quartz.QuartzSessionValidationScheduler">
<property name="sessionValidationInterval" value="1800000" />
<property name="sessionManager" ref="sessionManager" />
</bean> <!-- 会话管理器 -->
<bean id="sessionManager"
class="org.apache.shiro.web.session.mgt.DefaultWebSessionManager">
<property name="globalSessionTimeout" value="1800000" />
<property name="deleteInvalidSessions" value="true" />
<property name="sessionValidationSchedulerEnabled" value="true" />
<property name="sessionValidationScheduler" ref="sessionValidationScheduler" />
<property name="sessionDAO" ref="<span style="color:#ff0000;">customShiroSessionDAO</span>" /> //这里指定shiro的sessionManager使用我们指定的存储方式来存放session信息
<property name="sessionIdCookieEnabled" value="true" />
<property name="sessionIdCookie" ref="sessionIdCookie" />
</bean> <span style="color:#ff0000;"><bean id="customShiroSessionDAO" class="org.calonlan.security.component.CustomShiroSessionDao">
<property name="shiroSessionRepository" ref="jedisShiroSessionRepository" />//自己定义的sessiondao
</bean></span> <span style="color:#ff0000;"> <bean id="jedisShiroSessionRepository"
class="org.calonlan.security.component.JedisShiroSessionRepository">
<property name="redisManager" ref="redisManager"></property>
</bean></span>
<span style="color:#ff0000;"><bean id="redisManager" class="org.calonlan.security.component.RedisManager"></bean>//注册上面实现的redisManager到spring中</span> <span style="background-color: rgb(255, 0, 0);"><bean id="jedisShiroCacheManager" class="org.calonlan.security.component.JedisShiroCacheManager">
<property name="redisManager" ref="redisManager"></property>
</bean></span><span style="background-color: rgb(255, 255, 255);">
</span>
<span style="color:#ff0000;"> <bean id="customShiroCacheManager" class="org.calonlan.security.component.CustomShiroCacheManager">
<property name="shrioCacheManager" ref="jedisShiroCacheManager"></property>
</bean></span>
<!-- 安全管理器 -->
<bean id="securityManager" class="org.apache.shiro.web.mgt.DefaultWebSecurityManager">
<property name="realm" ref="userRealm" />
<property name="sessionManager" ref="sessionManager" />
<property name="cacheManager" ref="<span style="color:#ff0000;">customShiroCacheManager</span>" />
<property name="rememberMeManager" ref="rememberMeManager" />
</bean> <!-- 相当于调用SecurityUtils.setSecurityManager(securityManager) -->
<bean
class="org.springframework.beans.factory.config.MethodInvokingFactoryBean">
<property name="staticMethod"
value="org.apache.shiro.SecurityUtils.setSecurityManager" />
<property name="arguments" ref="securityManager" />
</bean> <!-- 基于Form表单的身份验证过滤器 -->
<bean id="formAuthenticationFilter"
class="org.apache.shiro.web.filter.authc.FormAuthenticationFilter">
<property name="usernameParam" value="username" />
<property name="passwordParam" value="password" />
<property name="rememberMeParam" value="rememberMe" />
<property name="loginUrl" value="/login" />
</bean> <bean id="sysUserFilter" class="org.calonlan.security.web.shiro.filter.SysUserFilter" /> <!-- Shiro的Web过滤器 -->
<bean id="shiroFilter" class="org.apache.shiro.spring.web.ShiroFilterFactoryBean">
<property name="securityManager" ref="securityManager" />
<!-- 逻辑上正确,不起作用 -->
<property name="loginUrl" value="/login" />
<property name="successUrl" value="/admin/index" />
<property name="filters">
<util:map>
<entry key="authc" value-ref="formAuthenticationFilter" />
<entry key="sysUser" value-ref="sysUserFilter" />
</util:map>
</property>
<property name="filterChainDefinitions">
<value>
/img/** =anon
/ueditor/jsp/upload/** =anon
/login = authc
/authenticated = authc
/css/** = anon
/common/** = anon
/js/** = anon
/admin/** = user,sysUser
//*=anon
</value>
</property>
</bean> <!-- Shiro生命周期处理器 -->
<bean id="lifecycleBeanPostProcessor" class="org.apache.shiro.spring.LifecycleBeanPostProcessor" />
</beans>
package org.calonlan.security.component; import java.io.Serializable;
import java.util.Collection; import org.apache.shiro.session.Session;
import org.apache.shiro.session.UnknownSessionException;
import org.apache.shiro.session.mgt.eis.AbstractSessionDAO; public class CustomShiroSessionDao extends AbstractSessionDAO { private ShiroSessionRepository shiroSessionRepository; public ShiroSessionRepository getShiroSessionRepository() {
return shiroSessionRepository;
} public void setShiroSessionRepository(
ShiroSessionRepository shiroSessionRepository) {
this.shiroSessionRepository = shiroSessionRepository;
} @Override
public void delete(Session session) {
if (session == null) {
System.out.println("错误");
return;
}
Serializable id = session.getId();
if (id != null)
getShiroSessionRepository().deleteSession(id); } @Override
public Collection<Session> getActiveSessions() {
return getShiroSessionRepository().getAllSessions();
} @Override
public void update(Session session) throws UnknownSessionException {
getShiroSessionRepository().saveSession(session);
} @Override
protected Serializable doCreate(Session session) {
Serializable sessionId = this.generateSessionId(session);
this.assignSessionId(session, sessionId);
getShiroSessionRepository().saveSession(session);
return sessionId;
} @Override
protected Session doReadSession(Serializable sessionId) {
return getShiroSessionRepository().getSession(sessionId);
} }
这里我们是继承了shiro的AbstractSessionDAO,然后仿照shiro的模式,给他一个shiroSessionRepository,来进行详细的session存储操作。
package org.calonlan.security.component; import java.io.Serializable;
import java.util.Collection; import org.apache.shiro.session.Session; public interface ShiroSessionRepository { void saveSession(Session session); void deleteSession(Serializable sessionId); Session getSession(Serializable sessionId); Collection<Session> getAllSessions();
}
package org.calonlan.security.component; import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set; import org.apache.shiro.session.Session; public class JedisShiroSessionRepository implements ShiroSessionRepository { /**
*
* redis session key 前缀
*
* */
private final String REDIS_SHIRO_SESSION = "shiro-session"; private RedisManager redisManager; @Override
public void saveSession(Session session) {
redisManager.init();
if (session == null || session.getId() == null) {
System.out.println("session 或者 session ID 为空");
}
byte[] key = SerializeUtils.serialize(getRedisSessionKey(session
.getId()));
byte[] value = SerializeUtils.serialize(session); Long timeOut = session.getTimeout() / 1000;
redisManager.set(key, value, Integer.parseInt(timeOut.toString())); } @Override
public void deleteSession(Serializable sessionId) {
redisManager.init();
if (sessionId == null) {
System.out.println("id为空");
}
redisManager.del(SerializeUtils
.serialize(getRedisSessionKey(sessionId))); } @Override
public Session getSession(Serializable sessionId) {
redisManager.init();
if (null == sessionId) {
System.out.println("id为空");
return null;
}
Session session = null;
byte[] value = redisManager.get(SerializeUtils
.serialize(getRedisSessionKey(sessionId)));
if (null == value)
return null;
session = (Session) SerializeUtils.deserialize(value);
return session;
} @Override
public Collection<Session> getAllSessions() {
redisManager.init();
Set<Session> sessions = new HashSet<Session>();
Set<byte[]> byteKeys = redisManager
.keys(this.REDIS_SHIRO_SESSION + "*");
if (byteKeys != null && byteKeys.size() > 0) {
for (byte[] bs : byteKeys) {
Session s = (Session) SerializeUtils.deserialize(redisManager
.get(bs));
sessions.add(s);
}
}
return sessions;
} /**
* 获取redis中的session key
*
* @param sessionId
* @return
*/
private String getRedisSessionKey(Serializable sessionId) {
return this.REDIS_SHIRO_SESSION + sessionId;
} public RedisManager getRedisManager() {
return redisManager;
} public void setRedisManager(RedisManager redisManager) {
this.redisManager = redisManager;
} public JedisShiroSessionRepository() { } // public static void main(String[] args) {
// Jedis jj = new Jedis("localhost");
// //jj.set("key2", "232323231=========");
// String ss = jj.get("key1");
// System.out.println(jj.get("key2"));
// System.out.println(ss);
// }
}
package org.calonlan.security.component; import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.util.Destroyable; public class CustomShiroCacheManager implements CacheManager, Destroyable { private ShiroCacheManager shrioCacheManager; public ShiroCacheManager getShrioCacheManager() {
return shrioCacheManager;
} public void setShrioCacheManager(ShiroCacheManager shrioCacheManager) {
this.shrioCacheManager = shrioCacheManager;
} @Override
public void destroy() throws Exception {
getShrioCacheManager().destroy();
} @Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
return getShrioCacheManager().getCache(name);
} }
package org.calonlan.security.component; import org.apache.shiro.cache.Cache; public interface ShiroCacheManager {
<K, V> Cache<K, V> getCache(String name); void destroy();
}
package org.calonlan.security.component; import org.apache.shiro.cache.Cache; public class JedisShiroCacheManager implements ShiroCacheManager { private RedisManager redisManager; public RedisManager getRedisManager() {
return redisManager;
} public void setRedisManager(RedisManager redisManager) {
this.redisManager = redisManager;
} @Override
public <K, V> Cache<K, V> getCache(String name) {
return new JedisShiroCache<K, V>(redisManager, name);
} @Override
public void destroy() {
redisManager.init();
redisManager.flushDB();
} }
package org.calonlan.security.component; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream; public class SerializeUtils { public static byte[] serialize(Object o) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try {
ObjectOutputStream outo = new ObjectOutputStream(out);
outo.writeObject(o);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} return out.toByteArray();
} public static Object deserialize(byte[] b) {
ObjectInputStream oin;
try {
oin = new ObjectInputStream(new ByteArrayInputStream(b));
try {
return oin.readObject();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
return null;
} }
}
package org.calonlan.security.component; import java.util.Iterator;
import java.util.Set; import org.springframework.beans.factory.annotation.Value; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; /**
* @author Administrator
* redismanager主要用来给用户提供一个设计完备的,通过jedis的jar包来管理redis内存数据库的各种方法
*/
public class RedisManager { // ip和port属性都定义在了properties文件中,这里通过spring的注解方式来直接使用
@Value("${redis.ip}")
private String host;
@Value("${redis.port}")
private int port; // 设置为0的话就是永远都不会过期
private int expire = 0; // 定义一个管理池,所有的redisManager共同使用。
private static JedisPool jedisPool = null; public RedisManager() {
} /**
*
* 初始化方法,在这个方法中通过host和port来初始化jedispool。
*
* */ public void init() {
if (null == host || 0 == port) {
System.out.println("请初始化redis配置文件");
throw new NullPointerException("找不到redis配置");
}
if (jedisPool == null) {
jedisPool = new JedisPool(new JedisPoolConfig(), host, port);
}
} /**
* get value from redis
*
* @param key
* @return
*/
public byte[] get(byte[] key) {
byte[] value = null;
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
value = jedis.get(key);
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* get value from redis
*
* @param key
* @return
*/
public String get(String key) {
String value = null;
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
value = jedis.get(key);
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* set
*
* @param key
* @param value
* @return
*/
public byte[] set(byte[] key, byte[] value) {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.set(key, value);
if (this.expire != 0) {
jedis.expire(key, this.expire);
}
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* set
*
* @param key
* @param value
* @return
*/
public String set(String key, String value) {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.set(key, value);
if (this.expire != 0) {
jedis.expire(key, this.expire);
}
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* set
*
* @param key
* @param value
* @param expire
* @return
*/
public byte[] set(byte[] key, byte[] value, int expire) {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.set(key, value);
if (expire != 0) {
jedis.expire(key, expire);
}
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* set
*
* @param key
* @param value
* @param expire
* @return
*/
public String set(String key, String value, int expire) {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.set(key, value);
if (expire != 0) {
jedis.expire(key, expire);
}
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* del
*
* @param key
*/
public void del(byte[] key) {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.del(key);
} finally {
jedisPool.returnResource(jedis);
}
} /**
* del
*
* @param key
*/
public void del(String key) {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.del(key);
} finally {
jedisPool.returnResource(jedis);
}
} /**
* flush
*/
public void flushDB() {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.flushDB();
} finally {
jedisPool.returnResource(jedis);
}
} /**
* size
*/
public Long dbSize() {
Long dbSize = 0L;
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
dbSize = jedis.dbSize();
} finally {
jedisPool.returnResource(jedis);
}
return dbSize;
} /**
* keys
*
* @param regex
* @return
*/
public Set<byte[]> keys(String pattern) {
Set<byte[]> keys = null;
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
System.out.println("我调用了keys方法=---shiro");
keys = jedis.keys(("*" + pattern).getBytes());
if (null != keys)
System.out.println(keys.size());
} finally {
jedisPool.returnResource(jedis);
}
return keys;
} public void dels(String pattern) {
Set<byte[]> keys = null;
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
System.out.println("我调用了dels方法=---shiro");
keys = jedis.keys(("*" + pattern).getBytes());//这里我做了修改,在redis数据库中我们的id前面还加了一堆东西,这样修改后就可以全部查看到了
Iterator<byte[]> ito = keys.iterator();
while (ito.hasNext()) {
jedis.del(ito.next());
}
} finally {
jedisPool.returnResource(jedis);
}
} public String getHost() {
return host;
} public void setHost(String host) {
this.host = host;
} public int getPort() {
return port;
} public void setPort(int port) {
this.port = port;
} public int getExpire() {
return expire;
} public void setExpire(int expire) {
this.expire = expire;
}
}
package org.calonlan.security.component; import java.io.Serializable;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set; import org.apache.shiro.session.Session; public class JedisShiroSessionRepository implements ShiroSessionRepository { /**
*
* redis session key 前缀
*
* */
private final String REDIS_SHIRO_SESSION = "shiro-session"; private RedisManager redisManager; @Override
public void saveSession(Session session) {
redisManager.init();
if (session == null || session.getId() == null) {
System.out.println("session 或者 session ID 为空");
}
byte[] key = getRedisSessionKey(session.getId()).getBytes();
byte[] value = SerializeUtils.serialize(session); Long timeOut = session.getTimeout() / 1000;
redisManager.set(key, value, Integer.parseInt(timeOut.toString())); } @Override
public void deleteSession(Serializable sessionId) {
redisManager.init();
if (sessionId == null) {
System.out.println("id为空");
}
redisManager.del(getRedisSessionKey(sessionId).getBytes()); } @Override
public Session getSession(Serializable sessionId) {
redisManager.init();
if (null == sessionId) {
System.out.println("id为空");
return null;
}
Session session = null;
byte[] value = redisManager.get(getRedisSessionKey(sessionId)
.getBytes());
if (null == value)
return null;
session = (Session) SerializeUtils.deserialize(value);
return session;
} @Override
public Collection<Session> getAllSessions() {
redisManager.init();
Set<Session> sessions = new HashSet<Session>();
Set<byte[]> byteKeys = redisManager
.keys(this.REDIS_SHIRO_SESSION + "*");
if (byteKeys != null && byteKeys.size() > 0) {
for (byte[] bs : byteKeys) {
Session s = (Session) SerializeUtils.deserialize(redisManager
.get(bs));
sessions.add(s);
}
}
return sessions;
} /**
* 获取redis中的session key
*
* @param sessionId
* @return
*/
private String getRedisSessionKey(Serializable sessionId) {
return this.REDIS_SHIRO_SESSION + sessionId;
} public RedisManager getRedisManager() {
return redisManager;
} public void setRedisManager(RedisManager redisManager) {
this.redisManager = redisManager;
} public JedisShiroSessionRepository() { } // public static void main(String[] args) {
// Jedis jj = new Jedis("localhost");
// //jj.set("key2", "232323231=========");
// String ss = jj.get("key1");
// System.out.println(jj.get("key2"));
// System.out.println(ss);
// }
}
package org.calonlan.security.component; import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set; import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException; public class JedisShiroCache<K, V> implements Cache<K, V> {
private final String REDIS_SHIRO_CACHE = "shiro-cache"; private RedisManager redisManager; private String name; public JedisShiroCache(RedisManager redisManager, String name) {
this.redisManager = redisManager;
this.name = name;
} public String getName() {
if (null == null) {
return "";
}
return name;
} public void setName(String name) {
this.name = name;
} @Override
public void clear() throws CacheException {
redisManager.init();
String keysPattern = this.REDIS_SHIRO_CACHE + "*";
redisManager.flushDB(); } @Override
public V get(K key) throws CacheException {
redisManager.init();
byte[] byteKey = getCacheKey(key).getBytes();
byte[] byteValue = redisManager.get(byteKey);
if (null == byteValue)
return null;
return (V) SerializeUtils.deserialize(byteValue);
} @Override
public Set<K> keys() {
redisManager.init();
Set<byte[]> byteSet = redisManager.keys(this.REDIS_SHIRO_CACHE + "*");
Set<K> keys = new HashSet<K>();
for (byte[] bs : byteSet) {
keys.add((K) SerializeUtils.deserialize(bs));
}
return keys;
} @Override
public V put(K key, V value) throws CacheException {
redisManager.init();
V previos = get(key);
redisManager.set(getCacheKey(key).getBytes(),
SerializeUtils.serialize(value));
return previos;
} @Override
public V remove(K key) throws CacheException {
redisManager.init();
V previos = get(key);
redisManager.del(getCacheKey(key).getBytes());
return previos;
} @Override
public int size() {
redisManager.init();
if (keys() == null)
return 0;
return keys().size();
} @Override
public Collection<V> values() {
Set<byte[]> byteSet = redisManager.keys(this.REDIS_SHIRO_CACHE + "*");
List<V> result = new LinkedList<V>();
for (byte[] bs : byteSet) {
result.add((V) SerializeUtils.deserialize(redisManager.get(bs)));
}
return result;
} private String getCacheKey(Object key) {
return this.REDIS_SHIRO_CACHE + getName() + ":" + key;
}
}
package org.calonlan.security.component; import java.util.Iterator;
import java.util.Set; import org.springframework.beans.factory.annotation.Value; import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig; /**
* @author Administrator
* redismanager主要用来给用户提供一个设计完备的,通过jedis的jar包来管理redis内存数据库的各种方法
*/
public class RedisManager { // ip和port属性都定义在了properties文件中,这里通过spring的注解方式来直接使用
@Value("${redis.ip}")
private String host;
@Value("${redis.port}")
private int port; // 设置为0的话就是永远都不会过期
private int expire = 0; // 定义一个管理池,所有的redisManager共同使用。
private static JedisPool jedisPool = null; public RedisManager() {
} /**
*
* 初始化方法,在这个方法中通过host和port来初始化jedispool。
*
* */ public void init() {
if (null == host || 0 == port) {
System.out.println("请初始化redis配置文件");
throw new NullPointerException("找不到redis配置");
}
if (jedisPool == null) {
jedisPool = new JedisPool(new JedisPoolConfig(), host, port);
}
} /**
* get value from redis
*
* @param key
* @return
*/
public byte[] get(byte[] key) {
byte[] value = null;
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
value = jedis.get(key);
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* get value from redis
*
* @param key
* @return
*/
public String get(String key) {
String value = null;
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
value = jedis.get(key);
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* set
*
* @param key
* @param value
* @return
*/
public byte[] set(byte[] key, byte[] value) {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.set(key, value);
if (this.expire != 0) {
jedis.expire(key, this.expire);
}
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* set
*
* @param key
* @param value
* @return
*/
public String set(String key, String value) {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.set(key, value);
if (this.expire != 0) {
jedis.expire(key, this.expire);
}
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* set
*
* @param key
* @param value
* @param expire
* @return
*/
public byte[] set(byte[] key, byte[] value, int expire) {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.set(key, value);
if (expire != 0) {
jedis.expire(key, expire);
}
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* set
*
* @param key
* @param value
* @param expire
* @return
*/
public String set(String key, String value, int expire) {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.set(key, value);
if (expire != 0) {
jedis.expire(key, expire);
}
} finally {
jedisPool.returnResource(jedis);
}
return value;
} /**
* del
*
* @param key
*/
public void del(byte[] key) {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.del(key);
} finally {
jedisPool.returnResource(jedis);
}
} /**
* del
*
* @param key
*/
public void del(String key) {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.del(key);
} finally {
jedisPool.returnResource(jedis);
}
} /**
* flush
*/
public void flushDB() {
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
jedis.flushDB();
} finally {
jedisPool.returnResource(jedis);
}
} /**
* size
*/
public Long dbSize() {
Long dbSize = 0L;
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
dbSize = jedis.dbSize();
} finally {
jedisPool.returnResource(jedis);
}
return dbSize;
} /**
* keys
*
* @param regex
* @return
*/
public Set<byte[]> keys(String pattern) {
Set<byte[]> keys = null;
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
System.out.println("我调用了keys方法=---shiro");
keys = jedis.keys(pattern.getBytes());
if (null != keys)
System.out.println(keys.size());
} finally {
jedisPool.returnResource(jedis);
}
return keys;
} public void dels(String pattern) {
Set<byte[]> keys = null;
Jedis jedis = jedisPool.getResource();
jedis.auth("你的密码");
try {
System.out.println("我调用了dels方法=---shiro");
keys = jedis.keys(pattern.getBytes());
Iterator<byte[]> ito = keys.iterator();
while (ito.hasNext()) {
jedis.del(ito.next());
}
} finally {
jedisPool.returnResource(jedis);
}
} public String getHost() {
return host;
} public void setHost(String host) {
this.host = host;
} public int getPort() {
return port;
} public void setPort(int port) {
this.port = port;
} public int getExpire() {
return expire;
} public void setExpire(int expire) {
this.expire = expire;
}
}
/**
* Copyright (c) 2005-2012 https://github.com/zhangkaitao
*
* Licensed under the Apache License, Version 2.0 (the "License");
*/
package org.calonlan.security.spring; import net.sf.ehcache.Ehcache;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheException;
import org.apache.shiro.cache.CacheManager;
import org.apache.shiro.util.CollectionUtils;
import org.springframework.cache.support.SimpleValueWrapper; import java.util.*; /**
* 包装Spring cache抽象
* <p>User: Zhang Kaitao
* <p>Date: 13-3-23 上午8:26
* <p>Version: 1.0
*/
public class SpringCacheManagerWrapper implements CacheManager { private org.springframework.cache.CacheManager cacheManager; /**
* 设置spring cache manager
*
* @param cacheManager
*/
public void setCacheManager(org.springframework.cache.CacheManager cacheManager) {
this.cacheManager = cacheManager;
} @Override
public <K, V> Cache<K, V> getCache(String name) throws CacheException {
org.springframework.cache.Cache springCache = cacheManager.getCache(name);
return new SpringCacheWrapper(springCache);
} static class SpringCacheWrapper implements Cache {
private org.springframework.cache.Cache springCache; SpringCacheWrapper(org.springframework.cache.Cache springCache) {
this.springCache = springCache;
} @Override
public Object get(Object key) throws CacheException {
Object value = springCache.get(key);
if (value instanceof SimpleValueWrapper) {
return ((SimpleValueWrapper) value).get();
}
return value;
} @Override
public Object put(Object key, Object value) throws CacheException {
springCache.put(key, value);
return value;
} @Override
public Object remove(Object key) throws CacheException {
springCache.evict(key);
return null;
} @Override
public void clear() throws CacheException {
springCache.clear();
} @Override
public int size() {
if(springCache.getNativeCache() instanceof Ehcache) {
Ehcache ehcache = (Ehcache) springCache.getNativeCache();
return ehcache.getSize();
}
throw new UnsupportedOperationException("invoke spring cache abstract size method not supported");
} @Override
public Set keys() {
if(springCache.getNativeCache() instanceof Ehcache) {
Ehcache ehcache = (Ehcache) springCache.getNativeCache();
return new HashSet(ehcache.getKeys());
}
throw new UnsupportedOperationException("invoke spring cache abstract keys method not supported");
} @Override
public Collection values() {
if(springCache.getNativeCache() instanceof Ehcache) {
Ehcache ehcache = (Ehcache) springCache.getNativeCache();
List keys = ehcache.getKeys();
if (!CollectionUtils.isEmpty(keys)) {
List values = new ArrayList(keys.size());
for (Object key : keys) {
Object value = get(key);
if (value != null) {
values.add(value);
}
}
return Collections.unmodifiableList(values);
} else {
return Collections.emptyList();
}
}
throw new UnsupportedOperationException("invoke spring cache abstract values method not supported");
}
}
}
RetryLimitHashedCredentialsMatcher:
package org.calonlan.security.credentials; import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager; import java.util.concurrent.atomic.AtomicInteger; /**
* <p>User: Zhang Kaitao
* <p>Date: 14-1-28
* <p>Version: 1.0
*/
public class RetryLimitHashedCredentialsMatcher extends HashedCredentialsMatcher { private Cache<String, AtomicInteger> passwordRetryCache; public RetryLimitHashedCredentialsMatcher(CacheManager cacheManager) {
passwordRetryCache = cacheManager.getCache("passwordRetryCache");
} @Override
public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {
String username = (String)token.getPrincipal();
//retry count + 1
AtomicInteger retryCount = passwordRetryCache.get(username);
if(retryCount == null) {
retryCount = new AtomicInteger(0);
passwordRetryCache.put(username, retryCount);
}
if(retryCount.incrementAndGet() > 5) {
//if retry count > 5 throw
throw new ExcessiveAttemptsException();
} boolean matches = super.doCredentialsMatch(token, info);
if(matches) {
//clear retry count
passwordRetryCache.remove(username);
}
return matches;
}
}
UserRealm:
package org.calonlan.security.realm; import org.apache.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
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.util.ByteSource;
import org.calonlan.security.entity.User;
import org.calonlan.security.service.ResourceService;
import org.calonlan.security.service.UserRoleService;
import org.calonlan.security.service.UserService; /**
* @ClassName: UserRealm
* @Description: TODO(这里用一句话描述这个类的作用)
* @author mbc
* @date 2014-6-7 上午11:49:06
*
*/
public class UserRealm extends AuthorizingRealm {
private static final Logger logger = Logger.getLogger(UserRealm.class); @javax.annotation.Resource
private UserRoleService userRoleService;
@javax.annotation.Resource
private ResourceService resourceService;
@javax.annotation.Resource
private UserService userService; /*
* (非 Javadoc) <p>Title: doGetAuthorizationInfo</p> <p>Description:权限授权 </p>
*
* @param principals
*
* @return
*
* @see
* org.apache.shiro.realm.AuthorizingRealm#doGetAuthorizationInfo(org.apache
* .shiro.subject.PrincipalCollection)
*/
@Override
protected AuthorizationInfo doGetAuthorizationInfo(
PrincipalCollection principals) { // 为空的情况直接返回null
if (null == principals) {
return null;
} SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
String username = (String) principals.getPrimaryPrincipal();
Cache<Object, AuthenticationInfo> cache = getAuthenticationCache();
System.out.println(cache == null);
logger.info("[用户:" + username + "|权限授权]"); authorizationInfo.setRoles(userRoleService
.loadRoleIdsByUsername(username));
authorizationInfo.setStringPermissions(resourceService
.loadPermissionsByUsername(username));
logger.info("[用户:" + username + "|权限授权完成]");
return authorizationInfo;
} /*
* (非 Javadoc) <p>Title: doGetAuthenticationInfo</p> <p>Description:权限认证
* </p>
*
* @param token
*
* @return
*
* @throws AuthenticationException
*
* @see
* org.apache.shiro.realm.AuthenticatingRealm#doGetAuthenticationInfo(org
* .apache.shiro.authc.AuthenticationToken)
*/
@Override
protected AuthenticationInfo doGetAuthenticationInfo(
AuthenticationToken token) throws AuthenticationException {
SimpleAuthenticationInfo authenticationInfo;
String username = (String) token.getPrincipal();
logger.info("[用户:" + username + "|系统权限认证]");
User user = userService.loadByUsername(username); if (user != null) {
if ("帐号锁定".equals(user.getState())) {
throw new LockedAccountException();// 帐号锁定
}
// 交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配,如果觉得人家的不好可以自定义实现
authenticationInfo = new SimpleAuthenticationInfo(
user.getUsername(), user.getPassword(),
ByteSource.Util.bytes(user.getCredentialsSalt()), getName());// realm
logger.info("[用户:" + username + "|系统权限认证完成]");
return authenticationInfo; // name
} else
return null; } }
Java使用reids,以及redis与shiro集成的更多相关文章
- Springboot集成mybatis(mysql),mail,mongodb,cassandra,scheduler,redis,kafka,shiro,websocket
https://blog.csdn.net/a123demi/article/details/78234023 : Springboot集成mybatis(mysql),mail,mongodb,c ...
- shiro 集成spring 使用 redis作为缓存 学习记录(六)
1.在applicationContext-redis.xml配置文件中增加如下: 申明一个cacheManager对象 用来注入到 shiro的 securityManager 属性 cac ...
- Shiro 集成Spring 使用 redis时 使用redisTemplate替代jedisPool(五)
1.添加依赖架包: <dependency> <groupId>org.springframework.data</groupId> <artifactId& ...
- Java Spring mvc 操作 Redis 及 Redis 集群
本文原创,转载请注明:http://www.cnblogs.com/fengzheng/p/5941953.html 关于 Redis 集群搭建可以参考我的另一篇文章 Redis集群搭建与简单使用 R ...
- spring-boot-2.0.3应用篇 - shiro集成
前言 上一篇:spring-boot-2.0.3源码篇 - 国际化,讲了如何实现国际化,实际上我工作用的模版引擎是freemaker,而不是thymeleaf,不过原理都是相通的. 接着上一篇,这一篇 ...
- 【从0到1,搭建Spring Boot+RESTful API+Shiro+Mybatis+SQLServer权限系统】05、Shiro集成
1.POM文件中加入Shiro和fastJSON依赖 <dependency> <groupId>org.apache.shiro</groupId> <ar ...
- cas+tomcat+shiro实现单点登录-4-Apache Shiro 集成Cas作为cas client端实现
目录 1.tomcat添加https安全协议 2.下载cas server端部署到tomcat上 3.CAS服务器深入配置(连接MYSQL) 4.Apache Shiro 集成Cas作为cas cli ...
- Java安全(权限)框架 - Shiro 功能讲解 架构分析
Java安全(权限)框架 - Shiro 功能讲解 架构分析 作者 : Stanley 罗昊 [转载请注明出处和署名,谢谢!] 简述Shiro Shiro出自公司Apache(阿帕奇),是java的一 ...
- Shiro学习笔记四(Shiro集成WEB)
这两天由于家里出了点事情,没有准时的进行学习.今天补上之前的笔记 -----没有学不会的技术,只有不停找借口的人 学习到的知识点: 1.Shiro 集成WEB 2.基于角色的权限控制 3.基于权限的控 ...
随机推荐
- C/C++——程序的内存分配
C/C++程序内存分配 一.预备知识-程序的内存分配 一个由c/C++编译的程序占用的内存分为下面几个部分 1.栈区(stack):由编译器自己主动分配释放 ,存放函数的參数值,局部变量的值等.其操作 ...
- Django模板过滤器详解
Django 模板过滤器也是我们在以后基于 Django 网站开发过程中会经常遇到的,如显示格式的转换.判断处理等.以下是 Django 过滤器列表,希望对为大家的开发带来一些方便. 一.形式:小写 ...
- Webwork【02】前端OGNL试练
1.OGNL 出现的意义 在mvc中,数据是在各个层次之间进行流转是一个不争的事实.而这种流转,也就会面临一些困境,这些困境,是由于数据在不同世界中的表现形式不同而造成的: a. 数据在页面上是一个扁 ...
- Java IO的应用之实现大文件复制
转载请注明原文地址:http://www.cnblogs.com/ygj0930/p/5827481.html 用IO进行文件复制,实质就是用FileInputStream链接要复制的文件,按一定规 ...
- [转]jquery设置select选中,赋值等操作
一.基础取值问题 例如<select class="selector"></select> 1.设置value为pxx的项选中 $(".selec ...
- java与C#、.NET AES加密、解密 解决方案
1.情景展示 Java提供的密钥,C#无法解密. 2.原因分析 在Java中,AES的实际密钥需要用到KeyGenerator 和 SecureRandom,但是C#和.NET 里面没有这2个类, ...
- VBA 一个很神奇的东西
百度经验参考:http://jingyan.baidu.com/article/4ae03de32663953efe9e6b47.html 今天奇迹般的发现了VBA,都怪自己平时使用excle不够多, ...
- python之实现ftp上传下载代码(含错误处理)
# -*- coding: utf-8 -*- #python 27 #xiaodeng #python之实现ftp上传下载代码(含错误处理) #http://www.cnblogs.com/kait ...
- Ubuntu 安装asciidoc时默认推荐了巨大的安装包
$ sudo apt-get install asciidocReading package lists... DoneBuilding dependency tree Reading s ...
- 使用nmap查看web服务支持的http methods
安装nmap yum install nmap 查看web server支持的http methods u02 ~]$ nmap -p --script http-methods www.somewh ...