详解SpringBoot Mongo 自增长ID有序规则

网友投稿 779 2022-12-04

详解SpringBoot Mongo 自增长ID有序规则

详解SpringBoot Mongo 自增长ID有序规则

概述:本文主要介绍springboot基于mongodb有序id生成,如生成工单编号GD202109290001。单机情况下效率每秒生成5000个有序ID。

实现方式如下

maven

org.springframework.boot

spring-boot-starter-web

org.springframework.boot

spring-boot-starter-data-mongodb

org.springframework.boot

spring-boot-starter-test

test

代码编写

@Document

@Data

public class Incr {

@Id

private String id;

private String collectionName;

private Long incrId;

}

@Service

public class IncrService {

@Autowired

private MongoTemplate mongoTemplate;

/**

* 获取自增ID

* @param collectionName

* @return

*/

public Long getIncrId(String collectionName){

Query query = new Query(Criteria.where("collectionName").is(collectionName));

Update update = new Update();

updathttp://e.inc("incrId");

FindAndModifyOptions options = FindAndModifyOptions.options();

options.upsert(true);

options.returnNew(true);

Incr incr = mongoTemplate.findAndModify(query,update,options,Incr.class);

return incr.getIncrId();

}

}

@RestController

@RequestMapping(value = "incr")

public class IncrController {

@Autowired

private IncrService incrService;

@RequestMapping(value = "test")

public Object test(){

long start = System.currentTimeMillis();

List aas = new ArrayList<>();

for (int i=0;i<10000;i++){

aas.add(i+"");

}

int i = 0;

aas.parallelStream().forEach(aa -> {

incrService.getIncrId(aa+"");

});

System.out.println(System.currentTimeMillis()-start);

return true;

}

}

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:SpringBoot+Mybatis plus+React实现条件选择切换搜索实践
下一篇:详解spring
相关文章

 发表评论

暂时没有评论,来抢沙发吧~