Overview: This paper mainly introduces springboot based on mongodb order ID generation, such as generating work order number GD202109290001. The efficiency generates 5000 ordered ids per second in single machine case.

The implementation is as follows

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>Copy the code

The code

@Document
@Data
public class Incr {

    @Id
    private String id;

    private String collectionName;

    private Long incrId;
}
Copy the code
@Service public class IncrService { @Autowired private MongoTemplate mongoTemplate; 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(); }}Copy the code
@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; }}Copy the code