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 idGeneratorList; protected Map 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 supportAlgorithms(){ return this.algorithmMap.keySet(); } }