如何使用ehcache+redis 怎么存进去 session 又如何取值呢
可以说一下 nutzcn 或者 nutzwk 是怎么用的呢
@wendal 简单粗略 可以说一下调用逻辑么
用户登陆Session 是存储到redis,服务器要重启的时候 再存入ehcache吗
还是登陆存redis 同时也存到ehcache
@tonyyule 存入时先存ehcache,然后存redis
取出时,先从ehcache查,查不到再到redis查
@wendal shiro.ini配置了以后 怎么把subject存入redis呢
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionManager.sessionDAO = $sessionDAO
securityManager.sessionManager = $sessionManager
securityManager.cacheManager = $cacheManager
@tonyyule 对用户代码是透明的.
@wendal 怎么持久化session
如何把shiro的session 存入ehcache 然后存redis
@wendal
登陆日志如下
17:39:00.268 DEBUG (UrlMappingImpl.java:101) get - Found mapping for [POST] path=/user/login : UserModule.login(UserModule.java:148)
17:39:00.268 DEBUG (NutIoc.java:151) get - Get 'jedisPool'<class redis.clients.jedis.JedisPool>
17:39:00.269 DEBUG (NutIoc.java:151) get - Get 'userModule'<class net.wendal.nutzbook.module.UserModule>
17:39:00.269 DEBUG (NutIoc.java:177) get - >> Load definition name=userModule
17:39:00.269 DEBUG (ComboIocLoader.java:169) load - Found IocObject(userModule) in AnnotationIocLoader(packages=[net.wendal.nutzbook])
17:39:00.269 DEBUG (NutIoc.java:209) get - >> Make...'userModule'<class net.wendal.nutzbook.module.UserModule>
17:39:00.270 DEBUG (NutIoc.java:151) get - Get 'txREAD_COMMITTED'<interface org.nutz.aop.MethodInterceptor>
17:39:00.270 DEBUG (NutIoc.java:177) get - >> Load definition name=txREAD_COMMITTED
17:39:00.270 DEBUG (MapLoader.java:67) load - Loading define for name=txREAD_COMMITTED
17:39:00.271 DEBUG (ComboIocLoader.java:169) load - Found IocObject(txREAD_COMMITTED) in TransIocLoader@901304940
17:39:00.271 DEBUG (NutIoc.java:209) get - >> Make...'txREAD_COMMITTED'<interface org.nutz.aop.MethodInterceptor>
17:39:00.271 DEBUG (ScopeContext.java:64) save - Save object 'txREAD_COMMITTED' to [app]
17:39:00.271 DEBUG (NutIoc.java:151) get - Get 'txREAD_COMMITTED'<interface org.nutz.aop.MethodInterceptor>
17:39:00.274 DEBUG (ScopeContext.java:64) save - Save object 'userModule' to [app]
17:39:00.277 DEBUG (NutIoc.java:151) get - Get 'dao'<interface org.nutz.dao.Dao>
17:39:00.277 DEBUG (NutIoc.java:151) get - Get 'emailService'<interface net.wendal.nutzbook.service.EmailService>
17:39:00.277 DEBUG (NutIoc.java:151) get - Get 'cacheManager'<class net.sf.ehcache.CacheManager>
17:39:00.277 DEBUG (NutIoc.java:151) get - Get 'conf'<>
17:39:00.278 DEBUG (NutIoc.java:151) get - Get 'userMessageService'<class net.wendal.nutzbook.service.UserMessageService>
17:39:00.278 DEBUG (NutIoc.java:151) get - Get 'yvrService'<class net.wendal.nutzbook.service.yvr.YvrService>
17:39:00.278 DEBUG (NutIoc.java:151) get - Get 'conf'<>
17:39:00.278 DEBUG (NutIoc.java:151) get - Get 'conf'<>
17:39:00.279 DEBUG (NutIoc.java:151) get - Get 'userService'<class net.wendal.nutzbook.service.UserService>
17:39:00.287 DEBUG (NutIoc.java:151) get - Get 'dao'<interface org.nutz.dao.Dao>
17:39:00.288 DEBUG (NutDaoExecutor.java:388) printSQL - SELECT * FROM t_user WHERE id=?
| 1 |
|---|
| 1 |
For example:> "SELECT * FROM t_user WHERE id=1"
17:39:00.292 DEBUG (DaoTimeInterceptor.java:28) filter - time=2ms, sql=SELECT * FROM t_user WHERE id=1
17:39:00.294 DEBUG (AuthenticatingRealm.java:569) getAuthenticationInfo - Looked up AuthenticationInfo [1] from doGetAuthenticationInfo
17:39:00.295 DEBUG (AuthenticatingRealm.java:507) cacheAuthenticationInfoIfPossible - AuthenticationInfo caching is disabled for info [1]. Submitted token: [org.nutz.integration.shiro.SimpleShiroToken@4ad34b93].
17:39:00.295 DEBUG (AbstractAuthenticator.java:233) authenticate - Authentication successful for token [org.nutz.integration.shiro.SimpleShiroToken@4ad34b93]. Returned account [1]
17:39:00.295 DEBUG (DefaultSubjectContext.java:102) resolveSecurityManager - No SecurityManager available in subject context map. Falling back to SecurityUtils.getSecurityManager() lookup.
17:39:00.295 DEBUG (DefaultSubjectContext.java:102) resolveSecurityManager - No SecurityManager available in subject context map. Falling back to SecurityUtils.getSecurityManager() lookup.
17:39:00.296 DEBUG (RedisCache.java:55) put - SET name=shiro-activeSessionCache key=7iekq8ardci6bpasjm3jqi6klv
17:39:00.298 DEBUG (LCache.java:100) fire - fire channel=LCache:shiro-activeSessionCache msg=20si70qte0gmhqri4c7art0i4s:7iekq8ardci6bpasjm3jqi6klv
17:39:00.299 DEBUG (CachePubSub.java:15) onPMessage - channel=LCache:shiro-activeSessionCache, msg=20si70qte0gmhqri4c7art0i4s:7iekq8ardci6bpasjm3jqi6klv
17:39:00.299 DEBUG (RedisCache.java:55) put - SET name=shiro-activeSessionCache key=7iekq8ardci6bpasjm3jqi6klv
17:39:00.300 DEBUG (LCache.java:100) fire - fire channel=LCache:shiro-activeSessionCache msg=20si70qte0gmhqri4c7art0i4s:7iekq8ardci6bpasjm3jqi6klv
17:39:00.301 DEBUG (CachePubSub.java:15) onPMessage - channel=LCache:shiro-activeSessionCache, msg=20si70qte0gmhqri4c7art0i4s:7iekq8ardci6bpasjm3jqi6klv
17:39:00.305 DEBUG (AbstractRememberMeManager.java:290) onSuccessfulLogin - AuthenticationToken did not indicate RememberMe is requested. RememberMe functionality will not be executed for corresponding account.
17:39:00.305 DEBUG (RedisCache.java:55) put - SET name=shiro-activeSessionCache key=7iekq8ardci6bpasjm3jqi6klv
17:39:00.307 DEBUG (LCache.java:100) fire - fire channel=LCache:shiro-activeSessionCache msg=20si70qte0gmhqri4c7art0i4s:7iekq8ardci6bpasjm3jqi6klv
17:39:00.308 DEBUG (CachePubSub.java:15) onPMessage - channel=LCache:shiro-activeSessionCache, msg=20si70qte0gmhqri4c7art0i4s:7iekq8ardci6bpasjm3jqi6klv
17:39:00.308 DEBUG (RedisCache.java:55) put - SET name=shiro-activeSessionCache key=7iekq8ardci6bpasjm3jqi6klv
17:39:00.312 DEBUG (LCache.java:100) fire - fire channel=LCache:shiro-activeSessionCache msg=20si70qte0gmhqri4c7art0i4s:7iekq8ardci6bpasjm3jqi6klv
17:39:00.313 DEBUG (CachePubSub.java:15) onPMessage - channel=LCache:shiro-activeSessionCache, msg=20si70qte0gmhqri4c7art0i4s:7iekq8ardci6bpasjm3jqi6klv
17:39:00.317 DEBUG (LogTimeProcessor.java:24) process - [POST]URI=/user/login 200 49ms
17:39:00.342 DEBUG (UrlMappingImpl.java:101) get - Found mapping for [GET] path=/yvr/list : YvrModule.list(YvrModule.java:127)
17:39:00.343 DEBUG (NutIoc.java:151) get - Get 'yvrModule'<class net.wendal.nutzbook.module.yvr.YvrModule>
17:39:00.361 DEBUG (LogTimeProcessor.java:24) process - [GET ]URI=/yvr/list 200 19ms
17:39:00.861 DEBUG (UrlMappingImpl.java:101) get - Found mapping for [GET] path=/yvr/u/admin/avatar : YvrUserModule.userAvatar(YvrUserModule.java:112)
17:39:00.861 DEBUG (NutIoc.java:151) get - Get 'jedisPool'<class redis.clients.jedis.JedisPool>
17:39:00.866 DEBUG (NutIoc.java:151) get - Get 'yvrUserModule'<class net.wendal.nutzbook.module.yvr.YvrUserModule>
17:39:00.883 DEBUG (MemoryStore.java:180) <init> - Initialized net.sf.ehcache.store.MemoryStore for t_oauth_user
17:39:00.886 DEBUG (Cache.java:1262) initialise - Initialised cache: t_oauth_user
17:39:00.886 DEBUG (ConfigurationHelper.java:364) createDefaultCacheDecorators - CacheDecoratorFactory not configured for defaultCache. Skipping for 't_oauth_user'.
17:39:00.886 DEBUG (NutDaoExecutor.java:388) printSQL - SELECT * FROM t_oauth_user WHERE u_id=? LIMIT 0, 1
| 1 |
|---|
| 1 |
For example:> "SELECT * FROM t_oauth_user WHERE u_id=1 LIMIT 0, 1 "
17:39:00.889 DEBUG (DaoTimeInterceptor.java:28) filter - time=2ms, sql=SELECT * FROM t_oauth_user WHERE u_id=1 LIMIT 0, 1
17:39:00.892 DEBUG (LogTimeProcessor.java:24) process - [GET ]URI=/yvr/u/admin/avatar 304 31ms
17:39:00.978 DEBUG (NutIoc.java:151) get - Get 'nutzbookWebsocket'<class net.wendal.nutzbook.websocket.NutzbookWebsocket>
17:39:01.038 DEBUG (NutzbookWsStringHandler.java:64) join - session(id=o4kbqq5glkhesr75fl066tlt26) join room(name=home)
看不懂 txREAD_COMMITTED是哪里来的 AOP么 哪里配置的
@tonyyule 只需要关心shiro.ini里面cache字样相关的类
@wendal
配置文件这样配置 session就会自动从ehcache存入redis了吗 那获取也是自动获取么? 首页是怎么验证cookie的呢?
#Session
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
# Session Cache
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionManager.sessionDAO = $sessionDAO
securityManager.sessionManager = $sessionManager
# use R.UU32()
sessionIdGenerator = org.nutz.integration.shiro.UU32SessionIdGenerator
securityManager.sessionManager.sessionDAO.sessionIdGenerator = $sessionIdGenerator
cacheManager_ehcache = org.apache.shiro.cache.ehcache.EhCacheManager
cacheManager_ehcache.cacheManagerConfigFile=classpath:ehcache.xml
cacheManager_redis = net.wendal.nutzbook.shiro.cache.RedisCacheManager
cacheManager = net.wendal.nutzbook.shiro.cache.LCacheManager
cacheManager.level1 = $cacheManager_ehcache
cacheManager.level2 = $cacheManager_redis
securityManager.cacheManager = $cacheManager
nutzdao_realm = net.wendal.nutzbook.shiro.realm.SimpleAuthorizingRealm
# cookie
sessionIdCookie=org.apache.shiro.web.servlet.SimpleCookie
sessionIdCookie.name=sid
sessionIdCookie.maxAge=946080000
sessionIdCookie.httpOnly=true
sessionManager.sessionIdCookie=$sessionIdCookie
sessionManager.sessionIdCookieEnabled=true
sessionManager.globalSessionTimeout=946080000
@tonyyule 由LCacheManager完成
@wendal 如何设置redis一分钟提交一次
登陆日志
2016-10-08 11:46:14,484 nuoshang.bluejay.common.shiro.cache.RedisCache.put(RedisCache.java:54) DEBUG - SET name=shiro-activeSessionCache key=5eu29l0c7ugr3rspv792j0rmhk
2016-10-08 11:46:14,485 nuoshang.bluejay.common.shiro.cache.LCache.fire(LCache.java:95) DEBUG - fire channel=LCache:shiro-activeSessionCache msg=t0kigbs5tcgppofpufhm89g125:5eu29l0c7ugr3rspv792j0rmhk
2016-10-08 11:46:14,486 nuoshang.bluejay.common.shiro.cache.CachePubSub.onPMessage(CachePubSub.java:15) DEBUG - channel=LCache:shiro-activeSessionCache, msg=t0kigbs5tcgppofpufhm89g125:5eu29l0c7ugr3rspv792j0rmhk
2016-10-08 11:46:14,487 org.nutz.mvc.impl.UrlMappingImpl.get(UrlMappingImpl.java:101) DEBUG - Found mapping for [POST] path=/app/app_users/login : AppUserModules.login(AppUserModules.java:62)
2016-10-08 11:46:14,491 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:151) DEBUG - Get 'permission'<class nuoshang.bluejay.common.shiro.view.Permission>
2016-10-08 11:46:14,492 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:151) DEBUG - Get 'dateUtil'<class nuoshang.bluejay.common.util.DateUtil>
2016-10-08 11:46:14,492 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:151) DEBUG - Get 'stringUtil'<class nuoshang.bluejay.common.util.StringUtil>
2016-10-08 11:46:14,492 org.nutz.ioc.impl.NutIoc.get(NutIoc.java:151) DEBUG - Get 'appUserModules'<class nuoshang.bluejay.modules.app.controllers.AppUserModules>
2016-10-08 11:46:14,492 nuoshang.bluejay.modules.app.controllers.AppUserModules.login(AppUserModules.java:62) DEBUG - Input params - name:
hamming
2016-10-08 11:46:14,492 nuoshang.bluejay.modules.app.controllers.AppUserModules.login(AppUserModules.java:63) DEBUG - Input params - password:
123456
2016-10-08 11:46:14,493 org.nutz.dao.impl.sql.run.NutDaoExecutor.printSQL(NutDaoExecutor.java:388) DEBUG - SELECT * FROM app_user WHERE loginname=? OR phone=? LIMIT 0, 1
| 1 | 2 |
|---------|---------|
| hamming | hamming |
For example:> "SELECT * FROM app_user WHERE loginname='hamming' OR phone='hamming' LIMIT 0, 1 "
2016-10-08 11:46:14,493 org.nutz.plugins.cache.dao.CachedNutDaoExecutor.exec(CachedNutDaoExecutor.java:147) DEBUG - sql = SELECT * FROM app_user WHERE loginname=? OR phone=? LIMIT 0, 1 , tables = [app_user]
2016-10-08 11:46:14,493 org.nutz.plugins.cache.dao.CachedNutDaoExecutor.exec(CachedNutDaoExecutor.java:177) DEBUG - not good for cache >> SELECT * FROM app_user WHERE loginname=? OR phone=? LIMIT 0, 1
2016-10-08 11:46:14,499 nuoshang.bluejay.common.processor.LogTimeProcessor.process(LogTimeProcessor.java:26) DEBUG - [POST]URI=/app/app_users/login 12ms
参考nutzbook的shiro.ini配置如
[main]
#ehcache
cacheManager_ehcache = org.apache.shiro.cache.ehcache.EhCacheManager
cacheManager_ehcache.cacheManagerConfigFile=classpath:ehcache.xml
cacheManager_redis = nuoshang.bluejay.common.shiro.cache.RedisCacheManager
cacheManager = nuoshang.bluejay.common.shiro.cache.LCacheManager
cacheManager.level1 = $cacheManager_ehcache
cacheManager.level2 = $cacheManager_redis
securityManager.cacheManager = $cacheManager
# Session
sessionManager = org.apache.shiro.web.session.mgt.DefaultWebSessionManager
sessionDAO = org.apache.shiro.session.mgt.eis.EnterpriseCacheSessionDAO
sessionDAO.cacheManager=$cacheManager
sessionDAO.activeSessionsCacheName=shiro-activeSessionCache
sessionManager.sessionDAO = $sessionDAO
securityManager.sessionManager = $sessionManager
# use R.UU32()
sessionIdGenerator = org.nutz.integration.shiro.UU32SessionIdGenerator
securityManager.sessionManager.sessionDAO.sessionIdGenerator = $sessionIdGenerator
# Cookie
sessionIdCookie=org.apache.shiro.web.servlet.SimpleCookie
sessionIdCookie.name=sid
#sessionIdCookie.domain=admin
#sessionIdCookie.path=
sessionIdCookie.maxAge=946080000
sessionIdCookie.httpOnly=true
sessionManager.sessionIdCookie=$sessionIdCookie
sessionManager.sessionIdCookieEnabled=true
sessionManager.globalSessionTimeout=946080000
#bak...
#sessionManager=org.apache.shiro.web.session.mgt.DefaultWebSessionManager
#sessionListener1 = nuoshang.bluejay.common.shiro.listener.MySessionListener
#sessionManager.sessionListeners = $sessionListener1
#sessionManager.globalSessionTimeout=50000
#securityManager.sessionManager=$sessionManager
rememberMeCookie = org.apache.shiro.web.servlet.SimpleCookie
rememberMeCookie.name=remember
rememberMeCookie.maxAge = 604800
rememberMeCookie.httpOnly = true
rememberMeManager = org.apache.shiro.web.mgt.CookieRememberMeManager
rememberMeManager.cookie = $rememberMeCookie
sha256Matcher = org.apache.shiro.authc.credential.Sha256CredentialsMatcher
sha256Matcher.storedCredentialsHexEncoded = false
sha256Matcher.hashIterations = 1024
sha256Matcher.hashSalted = true
shiroDbRealm = nuoshang.bluejay.common.shiro.realm.NutDaoRealm
shiroDbRealm.credentialsMatcher = $sha256Matcher
securityManager.realms = $shiroDbRealm
authcStrategy = nuoshang.bluejay.common.shiro.authc.pam.AnySuccessfulStrategy
securityManager.authenticator.authenticationStrategy = $authcStrategy
securityManager.cacheManager = $cacheManager
securityManager.rememberMeManager = $rememberMeManager
authc = nuoshang.bluejay.common.shiro.filter.SimpleAuthenticationFilter
authc.loginUrl = /private/login
logout.redirectUrl= /private/login
[urls]
/private/doLogin = anon
/assets/** = anon
/app/** = anon
/upload/** = anon
/** = anon
/private/** = authc
为何我把本地服务器停了 再启动 token无效了呢 subject 没有存入redis吗
@wendal 只有redis.windows.conf
redis.windows-service.conf
修改了 一分钟 还是没有保存
@tonyyule 要重启redis.conf才会生效的
@tonyyule 啥???
启动redis 它显示 配置文件的位置在这个路径 怎么找
t config. In order to specify a config file use F:\Software\redis-64.3.0.503\redis-server.exe /path/to/redis.conf
@tonyyule 论坛源码里面有redis.conf
@wendal 恩 这个配置文件 如果拷贝到项目路径下面 就能用吗
IOC可以控制redis的提交时间吗
var ioc = {
// 参考 https://github.com/xetorthio/jedis/wiki/Getting-started
jedisPoolConfig : {
type : "redis.clients.jedis.JedisPoolConfig",
fields : {
testWhileIdle : true, // 空闲时测试,免得redis连接空闲时间长了断线
maxTotal : 100 // 一般都够了吧
}
},
jedisPool : {
type : "redis.clients.jedis.JedisPool",
args : [
{refer : "jedisPoolConfig"},
// 从配置文件中读取redis服务器信息
{java : "$conf.get('redis.host', 'localhost')"},
{java : "$conf.getInt('redis.port', 6379)"},
{java : "$conf.getInt('redis.timeout', 2000)"},
{java : "$conf.get('redis.password')"},
],
fields : {},
events : {
depose : "destroy" // 关闭应用时必须关掉呢
}
}
};
@wendal 我把论坛源码里面redis.conf 拷贝到我的项目下面 修改如下地方 重启redis 重新启动项目 但是 还是没有一分钟提交一次 是哪里配置不对吗
save 900 1
save 300 10
save 60 1
@wendal 如下代码生成token验证token,APP用户登陆以后 会生成一个token APP记录 当服务器重启以后 重新验证appid token 就失败了 这个是为什么呢 redis没有吧subject存入吗
package cn.wizzer.modules.back.sys.services;
import cn.wizzer.common.base.Service;
import cn.wizzer.modules.back.sys.models.Sys_api;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import io.jsonwebtoken.impl.crypto.MacProvider;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.log.Log;
import org.nutz.log.Logs;
import java.security.Key;
import java.util.Date;
/**
* Created by wizzer on 2016/8/11.
*/
@IocBean(args = {"refer:dao"})
public class ApiService extends Service<Sys_api> {
private static final Log log = Logs.get();
public ApiService(Dao dao) {
super(dao);
}
public static Key key;
/**
* 生成token
*
* @param date 失效时间
* @param appId AppId
* @return
*/
public String generateToken(Date date, String appId) {
if (key == null)
key = MacProvider.generateKey();
return Jwts.builder()
.setSubject(appId)
.signWith(SignatureAlgorithm.HS512, key)
.setExpiration(date)
.compact();
}
/**
* 验证token
* @param appId AppId
* @param token token
* @return
*/
public boolean verifyToken(String appId, String token) {
try {
Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject().equals(appId);
return true;
} catch (Exception e) {
log.debug(e.getMessage());
return false;
}
}
}
@wendal 那论坛nutz-book-project接口API的AccessToken是如何创建和验证的呢
@wendal
这里只是去redis里面查看了一下 并没有验证token的正确性吧
int uid = yvrService.getUserByAccessToken(at);
if (uid < 1) {
return BaseModule.HTTP_403;
}
SecurityUtils.getSubject().getSession().setAttribute("me", uid);
@wendal
重置了AccessToken 再验证 还是返回-1
@Aop("redis")
public void resetAccessToken(String loginname) {
String at = jedis().hget(RKEY_USER_ACCESSTOKEN, loginname); {
jedis().hdel(RKEY_USER_ACCESSTOKEN, loginname);
jedis().hdel(RKEY_USER_ACCESSTOKEN2, at);
jedis().hdel(RKEY_USER_ACCESSTOKEN3, at);
}
}
@Aop("redis")
public int getUserByAccessToken(String at) {
String uid_str = jedis().hget(RKEY_USER_ACCESSTOKEN3, at);
if (uid_str == null)
return -1;
return Integer.parseInt(uid_str);
}
@wendal 跑偏了 我就想生成一个shiro的token 通过redis存储。存入redis的同时也设置一个redis的过期时间
那如何把这个生成的token 换成shiro生成的token呢 设置过期时间呢
/**
* 生成token
*
* @param date 失效时间
* @param appId AppId
* @return
*/
public String generateToken(Date date, String appId) {
if (key == null)
key = MacProvider.generateKey();
return Jwts.builder()
.setSubject(appId)
.signWith(SignatureAlgorithm.HS512, key)
.setExpiration(date)
.compact();
}
/**
* 验证token
* @param appId AppId
* @param token token
* @return
*/
public boolean verifyToken(String appId, String token) {
try {
Jwts.parser().setSigningKey(key).parseClaimsJws(token).getBody().getSubject().equals(appId);
return true;
} catch (Exception e) {
log.debug(e.getMessage());
return false;
}
}
@tonyyule 这代码跟shiro没有毛线关系
带过期时间保存token,直接走redis
// 存,120秒失效
jedis().setex(key,value,120);
//取
String value = jedis().get(key);
@wendal 那如何把Jwts.builder()存入缓存再 存入redis
Jwts获取到
@tonyyule 直接存redis,上面已给代码
@tonyyule 没看nutzbook?配好redis aop才能用jedis()
@Aop("redis")