求助|这个类现在我要调用1000万次他会很耗时,求优化
简介
是一个单服务器部署的一个项目
代码介绍
这个Java类 UniqueIdGenerator 的主要目的是生成一个唯一的8位数ID。
然后通过调用 appuserMapper.selectYzaAppuserByMainnum(uniqueId+"") 来检查数据库中是否存在该ID。如果不存在,直接返回这个ID;如果存在,则递归调用 generateUniqueId() 方法重新生成。
这个类现在我要调用1000万次他会很耗时并且每一个都会查询一下数据库,这使调用数据库非常频繁,各位大佬有没有办法,帮我优化一下。给跪了
@Service public class UniqueIdGenerator { @Autowired private YzaAppuserMapper appuserMapper; private static final long START_TIMESTAMP = 1577836800000L; private static final int BIT_SIZE = 8; private static final long MAX_NUM = (1 << BIT_SIZE) - 1; private static Random random = new Random(); public synchronized String generateUniqueId() { long currentTimestamp = System.currentTimeMillis() - START_TIMESTAMP; long randomNum = random.nextInt((int) MAX_NUM + 1); long uniqueId = (currentTimestamp << BIT_SIZE) | randomNum; if (uniqueId<0){ uniqueId = uniqueId * -1L; } //查询看他有没有 YzaAppuser appuser = appuserMapper.selectYzaAppuserByMainnum(uniqueId+""); if (Objects.isNull(appuser)){ //如果为空 直接生成 return uniqueId+""; } return generateUniqueId(); } }#23届找工作求助阵地##我的失利项目复盘#