123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129 |
- /**
- *
- */
- package com.yihu.util.mapRedis;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import java.util.Map;
- import java.util.concurrent.ConcurrentHashMap;
- import net.sf.json.JSONObject;
- /**
- * 使用Map实现redis的功能
- * @author lch
- *
- */
- public class MapForRedisUtils implements Runnable,IRedisUtils {
- private static MapForRedisUtils mapForRedisUtils=null;
- private static Map<String,String> map=new ConcurrentHashMap<String,String>();
- private static Map<String,Long> expireMap=new ConcurrentHashMap<String,Long>();
-
- /**
- * 存储值
- * @param key 健
- * @param val 值
- * @param minute 过期时间(分钟)
- */
- public void setValue(String key,String val,int minute){
- map.put(key,val);
- expireMap.put(key,System.currentTimeMillis()+minute*60L*1000);
- }
-
- /**
- * 获取值
- * @param key 健
- */
- public String getValue(String key){
- try{
- return map.get(key);
- }catch(Exception e){
- e.printStackTrace();
- return null;
- }
- }
-
- /**
- * 获取过期时间(相对于1970-1-1的毫秒数)
- * @param key 健
- */
- public long getExpireTime(String key){
- try{
- return expireMap.get(key);
- }catch(Exception e){
- e.printStackTrace();
- return 0;
- }
- }
- /**
- * 设置过期时间(毫秒数)
- * @param key 健
- * @param expireMills 多少毫秒
- */
- public long setExpireTime(String key,int minute){
- try{
- return expireMap.put(key,System.currentTimeMillis()+minute*60L*1000);
- }catch(Exception e){
- e.printStackTrace();
- return 0;
- }
- }
-
- @Override
- public void run() {
- while(true){
- try{
-
- //移除过期的数据
- List<String> needRemoveKey=new ArrayList<String>();
- for (Map.Entry<String, Long> entry : MapForRedisUtils.expireMap.entrySet()) {
- if(entry.getValue()!=null&&entry.getValue()<=System.currentTimeMillis()){
- needRemoveKey.add(entry.getKey());
- }
- }
- for(String key:needRemoveKey){
- map.remove(key);
- expireMap.remove(key);
- }
-
- try {
- Thread.sleep(10000);
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- }catch(Exception e){
- try {
- Thread.sleep(1000);
- } catch (Exception e1) {
- e1.printStackTrace();
- }
- }
- }
- }
-
-
- public synchronized IRedisUtils init(){
- if(mapForRedisUtils==null){
-
- mapForRedisUtils=new MapForRedisUtils();
- Thread t1=new Thread(mapForRedisUtils);
- t1.start();
-
- }
- return mapForRedisUtils;
- }
-
- public static void main(String[] args) throws InterruptedException {
- IRedisUtils mapForRedisUtils=new MapForRedisUtils();
- mapForRedisUtils.init();//全局只要允许一次就好
- mapForRedisUtils.setValue("test", "1111111", 1);
- System.out.println(mapForRedisUtils.getValue("test"));
- Thread.sleep(2*60*1000);
- System.out.println("2 min after,val="+mapForRedisUtils.getValue("test"));
- }
- }
|