概述:本文主要介绍springboot基于mongodb有序id生成,如生成工单编号GD202109290001。单机情况下效率每秒生成5000个有序ID。
实现方式如下
maven
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
< 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 >
|
代码编写
1
2
3
4
5
6
7
8
9
10
11
|
@Document
@Data
public class Incr {
@Id
private String id;
private String collectionName;
private Long incrId;
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
@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();
update.inc( "incrId" );
FindAndModifyOptions options = FindAndModifyOptions.options();
options.upsert( true );
options.returnNew( true );
Incr incr = mongoTemplate.findAndModify(query,update,options,Incr. class );
return incr.getIncrId();
}
}
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
|
@RestController
@RequestMapping (value = "incr" )
public class IncrController {
@Autowired
private IncrService incrService;
@RequestMapping (value = "test" )
public Object test(){
long start = System.currentTimeMillis();
List<String> 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 ;
}
}
|
到此这篇关于详解SpringBoot Mongo 自增长ID有序规则的文章就介绍到这了,更多相关SpringBoot Mongo 自增长ID内容请搜索服务器之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持服务器之家!
原文链接:https://juejin.cn/post/7013175299638575135