当前位置: 代码迷 >> 综合 >> 自定义缓存实现Session
  详细解决方案

自定义缓存实现Session

热度:69   发布时间:2023-10-08 17:33:31.0

缓存接口 :

package com.example.demo.learn.servlet.session.cache;/*** 缓存接口*/
public interface CacheManageService {void put(String key, Object value, Long timeout);void put(String key, Object value);void remove(String key);Object get(String key);int size();boolean containsKey(String key);boolean isEmpty();/*** 定时检查,删除过期的值*/void checkValidityData();}

缓存实现类:

package com.example.demo.learn.servlet.session.cache;import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;@Service
public class CacheManageServiceImpl implements CacheManageService {private Logger logger = LoggerFactory.getLogger(CacheManageServiceImpl.class);private Map<String, CacheEntity> cacheMap = new ConcurrentHashMap<>();/*** 缓存存放值** @param key     键* @param value   值* @param timeout 超时时间*/public void put(String key, Object value, Long timeout) {CacheEntity cacheEntity = new CacheEntity();cacheEntity.setKey(key);cacheEntity.setValue(value);if (timeout != null) {// 保存的是有效期的整个毫秒数cacheEntity.setTimeout(System.currentTimeMillis() + timeout);if (logger.isInfoEnabled()) {logger.info("设置缓存key:{}, timeout:{}", key, timeout);}}cacheMap.put(key, cacheEntity);}/*** 缓存存放值, 没有过期时间** @param key   键* @param value 值*/public void put(String key, Object value) {put(key, value, null);}/*** 删除缓存键** @param key 键*/@Overridepublic void remove(String key) {cacheMap.remove(key);}/*** 获得缓存中的值** @param key 键* @return 值*/@Overridepublic synchronized Object get(String key) {CacheEntity cacheEntity = cacheMap.get(key);if (cacheEntity != null) {return cacheEntity.getValue();}return null;}/*** 缓存的大小** @return size*/@Overridepublic int size() {return cacheMap.size();}/*** 是否包含某个键** @param key 键* @return 是否包含*/@Overridepublic boolean containsKey(String key) {return cacheMap.containsKey(key);}/*** 是否为空** @return 缓存map是否为空*/@Overridepublic boolean isEmpty() {return cacheMap.isEmpty();}/*** 定时检查,删除过期的值*/@Overridepublic void checkValidityData() {for (Map.Entry<String, CacheEntity> entry : cacheMap.entrySet()) {String key = entry.getKey();CacheEntity cacheEntity = entry.getValue();// 之前存放的毫秒数long timeout = cacheEntity.getTimeout();// 当前毫秒数long currentTime = System.currentTimeMillis();if (currentTime - timeout > 0) {// 已过期,删除cacheMap.remove(key);if (logger.isInfoEnabled()) {logger.info("缓存过期key:{}, 删除该键", key);}}}}
}

缓存实体类: 

package com.example.demo.learn.servlet.session.cache;/**** 自定义缓存实体类** 自定义session:*  首先是用Map集合装数据, 唯一不重复的字符串作为key,简称sessionId**  session有效期,如何去清除操作?*     线程池, 定时的线程池*/
public class CacheEntity {// 键private String key;// 值private Object value;// 有效期private long timeout;public String getKey() {return key;}public void setKey(String key) {this.key = key;}public Object getValue() {return value;}public void setValue(Object value) {this.value = value;}public long getTimeout() {return timeout;}public void setTimeout(long timeout) {this.timeout = timeout;}@Overridepublic String toString() {return "CacheEntity{" +"key='" + key + '\'' +", value=" + value +", timeout=" + timeout +'}';}
}

测试类:

package com.example.demo.learn.servlet.session.cache;import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;/*** 测试缓存框架*/
public class Test {private static CacheManageService cacheManageService = new CacheManageServiceImpl();public static void main(String[] args) throws InterruptedException {// 主线程 放入过期键cacheManageService.put("name", "song", 5000L);System.out.println("过期键保存成功......");// 开启一个线程检查有效期ScheduledExecutorService scheduledThreadPool = Executors.newScheduledThreadPool(5);scheduledThreadPool.schedule(new Runnable() {@Overridepublic void run() {cacheManageService.checkValidityData();}}, 5000, TimeUnit.MILLISECONDS);// 等待5秒Thread.sleep(5000);System.out.println(cacheManageService.get("name"));}
}

自定义实现session:

package com.example.demo.learn.servlet.session.utils;import com.example.demo.learn.servlet.session.cache.CacheManageService;
import com.example.demo.learn.servlet.session.cache.CacheManageServiceImpl;public class SessionUtils {private static CacheManageService cacheManageService = new CacheManageServiceImpl();/*** 获取值** @param name 键* @return 值*/public static Object getAttribute(String name) {return cacheManageService.get(name);}/*** 保存数据键后,生成一个sessionId** @param name  键* @param value 值*/public static String setAttribute(String name, Object value) {// 生成一个sessionIdString sessionId = TokenUtils.getToken();cacheManageService.put(sessionId, value);return sessionId;}public static void main(String[] args) {String sessionId = setAttribute("age", 20);System.out.println("生成sessionId: " + sessionId);System.out.println(getAttribute(sessionId));}
}

 随机生成字符串:

package com.example.demo.learn.servlet.session.utils;import java.util.UUID;public class TokenUtils {public static String getToken() {return UUID.randomUUID().toString().replaceAll("-","");}public static void main(String[] args) {System.out.println(getToken());}
}

 

  相关解决方案