詳解SpringBoot Mongo 自增長ID有序規(guī)則
概述:本文主要介紹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)文章
Java使用ThreadLocal實現(xiàn)當(dāng)前登錄信息的存取功能
ThreadLocal和其他并發(fā)工具一樣,也是用于解決多線程并發(fā)訪問,下這篇文章主要給大家介紹了關(guān)于Java使用ThreadLocal實現(xiàn)當(dāng)前登錄信息的存取功能,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下2023-02-02關(guān)于Java的HashMap多線程并發(fā)問題分析
HashMap是采用鏈表解決Hash沖突,因為是鏈表結(jié)構(gòu),那么就很容易形成閉合的鏈路,這樣在循環(huán)的時候只要有線程對這個HashMap進行g(shù)et操作就會產(chǎn)生死循環(huán),本文針對這個問題進行分析,需要的朋友可以參考下2023-05-05MyBatis如何處理MySQL字段類型date與datetime
這篇文章主要介紹了MyBatis如何處理MySQL字段類型date與datetime問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2024-01-01Java Hutool工具實現(xiàn)驗證碼生成及Excel文件的導(dǎo)入和導(dǎo)出
Hutool是一個小而全的Java工具類庫,通過靜態(tài)方法封裝,降低相關(guān)API的學(xué)習(xí)成本,提高工作效率,本文主要介紹了使用Hutool工具實現(xiàn)驗證碼生成和excel文件的導(dǎo)入、導(dǎo)出,需要的朋友可參考一下2021-11-11