论坛每个帖子都有一个id号,从1开始增长,每新增一个帖子,id增1
假设帖子有三项,id,文本和时间
在后端,设计一个类Article,类里就有三项:id, text, time
现在这个id增长有两种思路:
1) 利用数据库自增,id设为主键,启动数据库自增
2) 页面帖子前,利用ajax请求,取得数据库当前最大号maxid,然后帖子的id设为maxid+1
2)的思路在高并发的时候有问题,有可能多人同时发帖从而ajax请求获得同样的id,然后他们的帖子都是id+1
但是如果是1),那么提交帖子的时候,帖子数据只有两项,text和time
这样的话,后端可能就要设计两个类
一个Article有三项,id, text, time,另一个只ArticleWithoutID有两项 text, time
因为前端用户如果查看帖子,那么后端就要返回id, text, time三项了
但是要设计两个类,又感觉怪怪的
大家怎么看?
It must be added automatically on the server side, otherwise it may conflict.
You may ask, why are there conflicts even though I have chosen the largest one? If you know why databases have the concept of locks, you won't be confused here.
When the concurrency is large, it may be the maximum ID obtained at the same time. When submitting, one before the other, it will cause one submission to fail.
In addition, front-end data can be forged. As a programmer, you must be skeptical about front-end data and verify it
Relational databases can set auto-increment fields. You don’t need to specify them when entering data. The database handles the auto-increment ID by itself
It is certain that the ID database side will auto-increment, and the front-end auto-increment concurrency will definitely be over, there is no doubt about it. Depending on your needs, a class can completely handle it, it’s not that complicated. (The solution of self-increasing ID is not good and is not recommended for high concurrency)
1. The front end sends an article object to the server, including text and time.
2. The server stores this object in the database, and the database automatically increments to generate an id. There is concurrent processing on the database side.
3. After successful deposit, you can return the entire data or the ID to the front end.
4. The front end receives the success message and displays the current post in the list. At this point, the ID of the post has been obtained and can be queried based on the ID.
====
It is recommended to generate random IDs on the front end, so that high concurrency on the database side will not cause performance loss due to the auto-increment problem.