itstamen/rop

Session manage recommendation

itstamen opened this issue · 0 comments

Rop user SessionManager to manage the session, You can use standalone server just like redis or memcached and so on to manage the session status.Not recommend us servlet HttpSession to manage the session, cause it can't make you architecture be horizontal scale.

the following is example which using redis to manage the session data:

import com.google.common.collect.Maps;
import com.rop.session.Session;
import com.rop.session.SessionManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisTemplate;
import redis.clients.jedis.Jedis;

import java.util.Date;
import java.util.Map;

/**

  • @author : chenxh(itstamen@163.com)

  • @Date: 13-10-16
    */
    public class AppSessionManager implements SessionManager {

    private RedisTemplate redisTemplate;

    private static Map<String,Long> lastTimeMap = Maps.newHashMap();

    @OverRide
    public void addSession(String key, Session session) {
    redisTemplate.opsForValue().set(key,session);
    redisTemplate.expireAt(key, getSessionExpireDate());
    lastTimeMap.put(key,System.currentTimeMillis());
    }

    @OverRide
    public Session getSession(String key) {
    Session session = (Session) redisTemplate.opsForValue().get(key);
    Long lastTime = lastTimeMap.get(key);
    //5分钟后重新设置过期时间
    if(lastTime!=null && System.currentTimeMillis()-lastTime>5_60_1000){
    redisTemplate.expireAt(key, getSessionExpireDate());
    lastTimeMap.put(key,System.currentTimeMillis());
    }
    return session;
    }

    @OverRide
    public void removeSession(String key) {
    redisTemplate.delete(key);
    lastTimeMap.remove(key);
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate redisTemplate) {
    this.redisTemplate = redisTemplate;
    }

    /**

    • 登录一个小时 session自动失效
    • @return
      _/
      private Date getSessionExpireDate(){
      return new Date(getCurrentTimeMillis() + 60_60* 1000);
      }

    /**

    • 取redis当前时间
    • @return
      */
      public long getCurrentTimeMillis() {
      RedisConnection conn = redisTemplate.getConnectionFactory().getConnection();
      try{
      Jedis jedis = (Jedis) conn.getNativeConnection();
      Object resultObj = jedis.eval("return redis.call('time')[1]");
      return Long.parseLong(resultObj.toString()) * 1000;
      }
      finally {
      conn.close();
      }
      }
      }