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

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

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

昵称为空C   2021-09-29 我要评论
想了解详解SpringBoot Mongo 自增长ID有序规则的相关内容吗,昵称为空C在本文为您仔细讲解SpringBoot Mongo 自增长ID的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:SpringBoot,Mongo,自增长ID,SpringBoot+mongoDB,id自增,下面大家一起来学习吧。

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

猜您喜欢

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们