Java实现简单的Redis

package com.demo.map;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Predicate;

import static java.lang.Thread.sleep;

/**
 * @author RuanZG
 * @date 2024/1/16 13:45
 * 摘要:
 */
public class MyRedis {
    private static final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
        public static void main(String[] args) throws InterruptedException {
        Redis redis = Redis.getInstance();

            for (int i = 0; i < 10; i++) {
                new Thread(()->{
                    for (int j = 0; j < 100; j++) {
                        redis.set("key"+j,"value"+j);
                    }
                }).start();
            }
            sleep(1000);
            System.out.println(redis.getMap().size());

    }
}

class Redis{

    private final Map<String,RedisValue<String>> map = new ConcurrentHashMap<>();

    private static final int DEFAULT_EXPIRE_TIME = 1000;//默认过期时间

    private static final ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(10, r -> {
        Thread thread = new Thread(r);
        thread.setName("schedule-thread" + thread.getId());
        return thread;
    });

    //单例实例化必须放在最后,防止初始化时,其他属性还未初始化
    private static final Redis redis = new Redis();


    private Redis(){
        scheduledExecutorService.scheduleWithFixedDelay(()->{
            long now = System.currentTimeMillis();
            map.entrySet().removeIf(entry -> now > entry.getValue().getExpireTime());
        },0,100, TimeUnit.MILLISECONDS);
    }
    public static Redis getInstance(){
        return redis;
    }
    public void set(String key,String value){
        RedisValue<String> redisValue = new RedisValue<String>(value, System.currentTimeMillis() + DEFAULT_EXPIRE_TIME);
        map.put(key,redisValue);
    }
    public String get(String key){
        return map.get(key)==null?
                null: map.get(key).getValue();
    }
    public Map getMap(){
        return map;
    }
}
class RedisValue<T>{
    private final T value;
    private final long expireTime;

    public RedisValue(T value,long expireTime){
        this.value = value;
        this.expireTime = expireTime;
    }
    public T getValue(){
        return value;
    }
    public long getExpireTime(){
        return expireTime;
    }
}

你可能感兴趣的:(java,redis,开发语言)