自定义缓存

198 阅读1分钟

接口定义:

public interface IStore {

    String get(String key) throws Exception;
    
    void put(String key, String value, int expire, TimeUnit timeUnit) throws Exception;
}

默认实现:


import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class DefaultStore implements IStore {
    private ConcurrentMap<String, Value> cm;

    public DefaultStore() {
        this.cm = new ConcurrentHashMap<>(64);
    }

    @Override
    public String get(String key) {
        log.debug("get key:{}", key);
        Value v = this.cm.get(key);
        if (v == null || new Date().after(v.end)) {
            return "";
        }
        return v.value;
    }

    @Override
    public void put(String key, String value, int expire, TimeUnit timeUnit) {
        log.debug("put key:{}, value:{}, expire:{} second", key, value, timeUnit.toSeconds(expire));
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.SECOND, (int) timeUnit.toSeconds(expire));
        Value v = new Value(value, calendar.getTime());
        this.cm.put(key, v);
    }

    static class Value {
        String value;
        Date end;

        public Value(String value, Date time) {
            this.value = value;
            this.end = time;
        }
    }
}