概述
本文主要介绍springboot基于mongodb有序id生成,如生成工单编号GD202109290001。单机情况下效率每秒生成5000个有序ID。
实现方式
maven
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-mongodb</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency></dependencies>
代码编写
@Document@DatapublicclassIncr{@IdprivateStringid;privateStringcollectionName;privateLongincrId;}
@ServicepublicclassIncrService{@AutowiredprivateMongoTemplatemongoTemplate;/***获取自增ID*@paramcollectionName*@return*/publicLonggetIncrId(StringcollectionName){Queryquery=newQuery(Criteria.where("collectionName").is(collectionName));Updateupdate=newUpdate();update.inc("incrId");FindAndModifyOptionsoptions=FindAndModifyOptions.options();options.upsert(true);options.returnNew(true);Incrincr=mongoTemplate.findAndModify(query,update,options,Incr.class);returnincr.getIncrId();}}
@RestController@RequestMapping(value="incr")publicclassIncrController{@AutowiredprivateIncrServiceincrService;@RequestMapping(value="test")publicObjecttest(){longstart=System.currentTimeMillis();List<String>aas=newArrayList<>();for(inti=0;i<10000;i++){aas.add(i+"");}inti=0;aas.parallelStream().forEach(aa->{incrService.getIncrId(aa+"");});System.out.println(System.currentTimeMillis()-start);returntrue;}}