欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2022-08-18 12:03:16
概述:本文主要介绍springboot基于mongodb有序id生成,如生成工单编号gd202109290001。单机情况下效率每秒生成5000个有序id。实现方式如下maven

概述:本文主要介绍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
@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;
    }
}

到此这篇关于详解springboot mongo 自增长id有序规则的文章就介绍到这了,更多相关springboot mongo 自增长id内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!