詳解SpringBoot Mongo 自增長ID有序規(guī)則
更新時間:2021年09月29日 15:39:39 作者:昵稱為空C
本文主要介紹springboot基于mongodb有序id生成,文中通過示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
概述:本文主要介紹springboot基于mongodb有序id生成,如生成工單編號GD202109290001。單機情況下效率每秒生成5000個有序ID。
實現(xiàn)方式如下
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
@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();
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();
}
}
@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;
}
}
到此這篇關(guān)于詳解SpringBoot Mongo 自增長ID有序規(guī)則的文章就介紹到這了,更多相關(guān)SpringBoot Mongo 自增長ID內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
解決SpringCloud Config結(jié)合github無法讀取配置的問題
這篇文章主要介紹了解決SpringCloud Config結(jié)合github無法讀取配置的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-02-02

