关闭

java之构建自己的session

标签: java
271人阅读 评论(0) 收藏 举报
分类:
package com.ideai.service;

import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Timer;
import java.util.UUID;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;

import org.springframework.stereotype.Service;

import com.ideai.service.BaseService;

@Service
public class SessionManagerService extends BaseService {

	private int expired = 3600;// 秒
	private int checkInterval = 1800;// 秒
	private Timer timer = null;

	public int getExpired() {
		return expired;
	}

	static class DeleteJob extends java.util.TimerTask {

		Map<String, Map<String, Object>> sessions;
		Map<String, Date> sessionExpired;

		public DeleteJob(Map<String, Map<String, Object>> sessions, Map<String, Date> sessionExpired) {
			this.sessionExpired = sessionExpired;
			this.sessions = sessions;
		}

		@Override
		public void run() {
			Date now = new Date();
			for (String key : sessionExpired.keySet()) {
				if (now.after(sessionExpired.get(key))) {
					sessions.remove(key);
					sessionExpired.remove(key);
				}
			}

		}
	}

	@PostConstruct
	public void init() {
		// 删除过期的session
		DeleteJob job = new DeleteJob(sessions, sessionExpired);
		timer = new Timer(true);
		timer.schedule(job, 0, checkInterval);

	}

	@PreDestroy
	public void uninit() {
		if (timer != null) {
			try {
				timer.cancel();
			} catch (Exception e) {
				// TODO: handle exception
			}
		}

	}

	// 设置session过期时间
	public void setExpired(int expired) {
		this.expired = expired;
	}

	public final Map<String, Map<String, Object>> sessions = Collections
			.synchronizedMap(new HashMap<String, Map<String, Object>>());
	public final Map<String, Date> sessionExpired = Collections.synchronizedMap(new HashMap<String, Date>());

	// 保存session
	public synchronized void setSession(String key, Map<String, Object> session) {
		this.sessions.put(key, session);
		Date now = new Date();
		this.sessionExpired.put(key, new Date(now.getTime() + expired * 1000));
	}

	// 删除session
	public void removeSession(String key) {
		this.sessions.remove(key);
	}

	// 获取session
	public Map<String, Object> getSession(String key) {
		return this.sessions.get(key);
	}
	
	// 生成sessionid
	public String genId() {
			return UUID.randomUUID().toString();
	}

}

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:32147次
    • 积分:1184
    • 等级:
    • 排名:千里之外
    • 原创:73篇
    • 转载:17篇
    • 译文:14篇
    • 评论:2条
    最新评论