標籤:des blog http io ar os sp java for
在Apache Tomcat 7設定redis作為session store
在Apache Tomcat 7設定redis作為session store
redis已經有組件支援直接在tomcat7中設定下將redis作為tomcat預設的session儲存空間,下面介紹下配置過程
1.從http://redis.io/下載redis,按照redis服務端
wget http://download.redis.io/redis-stable.tar.gz
tar xvzf redis-stable.tar.gz
cd redis-stable
make
2.啟動redis
cd RedisDirectory/src
./redis-server --port 6379
3.從http://tomcat.apache.org/download-70.cgi下載tomcat7,按照tomcat7
4.從https://github.com/xetorthio/jedis/downloads下載jedis作為java的redis用戶端,
從https://github.com/jcoleman/tomcat-redis-session-manager/downloads下載tomcat的redis session manager外掛程式,
從http://commons.apache.org/proper/commons-pool/download_pool.cgi下載apache的common pool包,
將這幾個jar包拷貝到tomcat7的lib目錄下
其實這裡是有坑的,不過你們比較幸運,我幫你先踩了。如果你全部下載最新版本的話,肯定啟動不起來。我試了很久才匹配這些jar的版本。在附件中可以下載。聲明一下我用jdk是1.7的
5.修改tomcat的conf下的context.xml檔案,添加或者修改下面的配置
Java代碼
- <Valve className="com.radiadesign.catalina.session.RedisSessionHandlerValve" />
- <Manager className="com.radiadesign.catalina.session.RedisSessionManager"
- host="localhost" <!-- optional: defaults to "localhost" -->
- port="6379" <!-- optional: defaults to "6379" -->
- database="0" <!-- optional: defaults to "0" -->
- maxInactiveInterval="60" <!-- optional: defaults to "60" (in seconds) --> />
6.重啟tomcat後就可以看到session儲存到redis上了。
------------------------------------------------------------------------------------------------
Possible Issues
There is the possibility of a race condition that would cause seeming invisibility of the session immediately after your web application logs in a user: if the response has finished streaming and the client requests a new page before the valve has been able to complete saving the session into Redis, then the new request will not see the session.
This condition will be detected by the session manager and a java.lang.IllegalStateException with the message Race condition encountered: attempted to load session[SESSION_ID] which has been created but not yet serialized.will be thrown.
Normally this should be incredibly unlikely (insert joke about programmers and "this should never happen" statements here) since the connection to save the session into Redis is almost guaranteed to be faster than the latency between a client receiving the response, processing it, and starting a new request.
If you encounter errors, then you can force save the session early (before sending a response to the client) then you can retrieve the current session, and call currentSession.manager.save(currentSession) to synchronously eliminate the race condition. Note: this will only work directly if your application has the actual session object directly exposed. Many frameworks (and often even Tomcat) will expose the session in their own wrapper HttpSession implementing class. You may be able to dig through these layers to expose the actual underlying RedisSession instance--if so, then using that instance will allow you to implement the workaround.
在Apache Tomcat 7設定redis作為session store