Field avoid duplication Mysql case of concurrent modification

Field avoid duplication Mysql case of concurrent modification

One, Scene

     When multiple users simultaneously modify a user name, a user name of the same present case, since the business needs, the same user name is not permitted, the need to avoid duplication.

Second, the problem

     Examples sql statement (pseudo code):

	If(name not exited)		(1)
	{
		Update name;		(2)
	}

     We will first try to determine whether there is a user name, if not, will go to update the database. However, these two statements are segmented, if there are two threads simultaneously performing the two ends of this operation, the thread may be performed simultaneously over 2 (1) statement, the same name at this time is determined conditions have been gone through, two threads execute update name, it will lead to the same user name exists. Note: these two sql statements combined into one, but also the implementation of internal segments, and can not solve the problem.

Third, the solution

     For a single server, this problem is relatively simple, we do not consider multiport simultaneous operation of the database. Can be created directly in the cache memory of the server, user name, and the existing user name information stored in each update, the request is received when the front end insert or update a user name, first checking the local cache, and the same name, The decision to update the database.
     For distributed server, you can not simply rely on the local server program synchronization and atomic operations, and we need to start from the database itself, there are two ways:
(1) LOCK TABLE
     in this way will lock the entire table, leading to concurrent performance degradation in addition, if there is abnormal, it can cause the lock can not be released between lOCK TABLE and UNLOCK TABLE, but according to the service, if you can not add a unique constraint, it can only be achieved by this means locking, or create a separate lock table.

(2) set a unique constraint field
     when a field is set in a database table is unique, then the additions and changes in this field is operating, the database memory will help us ensure the uniqueness of the field, if there is a conflict will return the database to perform error . This program is useful to the actual project, measured 500 TPS scene.

发布了78 篇原创文章 · 获赞 79 · 访问量 6万+

Guess you like

Origin blog.csdn.net/bajianxiaofendui/article/details/104575350