Recently,I have a project which is set on the distributed server.As we know,the normal session is just holding on the one server in one machine,means that the session can't be share on the distributed server,session is a convenient way to check out our request,so that I want to implement my own session on the distributed environment.
Fortunately,we use the memcache server to be the cache in our project,so I can just build the session by the memcached.
First of all,I drew out the flow diagram.
as we have seen,the session is base on the cookies,the step are:
1. server received the request
2. check the sessionid in the request
3. if the sessionid is not existed,create one and new a session object save in the memcached,the key is the sessionid and the value is the session object
4. use the sessionid to find out the session object from the memcached
5. deserialize the session object
About the Session Class
public class SMSession implements Serializable{ /** * 序列化号 */ private static final long serialVersionUID = 1L; private HashMap<String, Object> cache; public SMSession(){ cache = new HashMap<String, Object>(); } public void set(String key,Object value){ this.cache.put(key, value); } public Object get(String key){ return cache.get(key); } }It's very simple class,and you can consummate it by yourself.
About the Testing
It's time to set up a memcahce server,you can find out the set up tutorial on the internet,so here I will use the BaeMemcache(You can find the information about Bae on the internet,too)
About the Overtime
The memcache is use the LRU,so in my opinion,we can't let the memcache to resolve the session overtime problem.
I have to idea about this problem:
1.Build a thread to observe the user list,clean the value in the memcached when the user time is over.
2.Just use the cookie overtime,and clean up the memcached in appoint time.
In my project,I choose the second way.It's easier to manage our program,and easier to implement.
Suddenly find out a problem!!If the cookies have be stolen by others,memcache can't delete the KV in time,it's very dangerous!!!(update at 2013/10/6)
About the Session Encryption Algorithm
Sessionid is the key to get the session from the server,using the encryption algorithm can keep the session safe.In my project,I use the tomcat session encryption algorithm(You can find it on the internet too,lol)
Conclution
I use the simple way to build my own session,of course you can consummate it by yourself,enjoy it~