java实现INT自增主键

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

public class SnowIdUtils {
    private static Map<String, AtomicInteger> keyMap;
    private static final Logger logger = LoggerFactory.getLogger(SnowIdUtils.class);

    public static int idKey(String keyName) {
        AtomicInteger atomicInteger = keyMap.get(keyName);
        if (atomicInteger == null) {
            atomicInteger = new AtomicInteger(1);
            keyMap.put(keyName, atomicInteger);
        }
        return atomicInteger.getAndIncrement();
    }

    static {
        try {
            File file = new File(System.getProperty("user.dir") + "/snow.txt");
            if (file.exists()) {
                BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file)));
                keyMap = reader.lines().collect(Collectors.toConcurrentMap(str -> str.split(":")[0],
                        str -> new AtomicInteger(Integer.parseInt(str.split(":")[1]))));
                logger.info("id列表初始化完毕");
            } else {
                keyMap = new ConcurrentHashMap<>();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public static void shotDown() {
        try {
            File file = new File(System.getProperty("user.dir") + "/snow.txt");
            BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            keyMap.forEach((key, value) -> {
                try {
                    writer.write(key + ":" + value.getAndIncrement() + "\r\n");
                } catch (IOException e) {
                    logger.error("写文件io异常:" + e.getMessage());
                }
            });
            writer.close();
            logger.info("id持久化完毕");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        Runtime.getRuntime().addShutdownHook(new Thread(SnowIdUtils::shotDown));
        for (int i = 0; i < 4; i++) {
            System.out.println(idKey("userKey"));
        }
    }
}

拿着用就行了,这个东西比较简单。没啥写的,勿喷

你可能感兴趣的:(java基础)