java之构建自己的session
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();
	}

}

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_27194467/article/details/52383024
文章标签: java
个人分类: Java
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

java之构建自己的session

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭