IdAlgorithmRegister.java 2.3 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
package com.kx.utils.id;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

/**
 * id算法注册器
 * @author kongxiang
 */
@Component
@Slf4j
public class IdAlgorithmRegister {
    /**
     * 获取所有类型是 IdGenerator
     */
    @Autowired
    private List<? extends IdGenerator> idGeneratorList;

    protected Map<String ,IdGenerator> algorithmMap = new ConcurrentHashMap<>(8);

    @PostConstruct
    public void  init(){
        if (idGeneratorList!= null ){
            idGeneratorList.forEach(idGenerator -> {
                algorithmMap.put(idGenerator.getAlgorithm(),idGenerator);
                log.info(">> Load id generator successful -- : algorithm :  [ {} ] ", idGenerator.getAlgorithm());
            });
        }
    }


    /**
     * 注册生成算法
     * @param algorithm
     * @param idGenerator
     * @return 注册结果
     */
    protected boolean register(String algorithm, IdGenerator idGenerator){
        boolean registerStatus = false;
        if (!StringUtils.isEmpty(algorithm) && idGenerator != null ){
            algorithmMap.put(algorithm,idGenerator);
            registerStatus = true;
        }
        return registerStatus;
    }

    /**
     * 获取算法生成器类
     * @param algorithm 算法
     * @return 算法生成器
     */
    public IdGenerator getAlgorithm(String algorithm){
        IdGenerator idGenerator = this.algorithmMap.get(algorithm);
        if (idGenerator == null ){
            throw new UnsupportedOperationException("id generate is not supported : " + algorithm);
        }
        return idGenerator;
    }

    /**
     * 是否存有算法生成器
     * @param algorithm 算法
     * @return
     */
    protected boolean containAlgorithm(String algorithm){
        return this.algorithmMap.containsKey(algorithm);
    }

    /**
     * 列出所有支持的算法
     * @return
     */
    protected Set<String> supportAlgorithms(){
        return this.algorithmMap.keySet();
    }

}