First, the preparatory work
1. Download and install VMware, skip the steps.
2. Download the CentOS system iOS package: Http://isoredirect.centos.org/centos/7/isos/x86_64/CentOS-7-x86_64-Everything-1611.iso
3. Download the installation Xshell5 and omit the steps.
4. Download and install Git, skip the steps.
5.MARIADB for Golang Api:https://github.com/go-sql-driver/mysql
6.vmware Click "Create New Virtual Machine", "typical", "Setup CD image File" Select the above downloaded iOS file, and then the next step to quickly install the CentOS system.
As for why CentOS is installed, in fact other Linux versions are also available. Installation of completed CentOS systems such as:
Second, installation configuration mariadb database
The reason for choosing the MARIADB database is that the CentOS 7 version removes the MySQL database software from the default program list and replaces it with MARIADB. Fortunately MARIADB's fully compatible with MySQL API and command line, does not affect our use.
Click Applications in the upper-left corner of the screen to open terminal.
First switch to root permissions:
Input Su, enter, see password: After entering the password, note that the password will not be displayed, input finished directly enter the good.
Then enter the command to install the MARIADB database:
Yum Install mariadb Mariadb-server
All prompts for Y enter as shown in.
The final appearance of complete! indicates that the installation was successful and we will mariadb join the boot entry and start.
MARIADB Add boot entry:
Systemctl Enable Mariadb.service
MARIADB Boot:
Systemctl Start Mariadb.service
Next, for a simple configuration of mariadb, enter the command:
Mysql_secure_installation
Screen display: Enter current password for root (enter for none), the initial password is empty, we can directly enter.
The following prompts are: Set the password (if y set the password, you need to enter two passwords), whether to delete anonymous users, whether to prohibit root telnet, whether to delete the test database, whether to reload the permissions table.
I set the password to 19930309, and the second four options are N, N, N, y, respectively.
Then we configure the MARIADB character set, modify the following files in turn, the following commands may be used.
(1) Open file: VI file name. suffix
(2) Edit file: Press the keyboard "I" After opening the file
(3) Exit Edit: ESC
(4) Save changes and close files: input: Wq Enter
(5) Undo Change: Input: Undo Enter
Add under the [Mysqld] tab of the/ETC/MY.CNF file
init_connect= ' SET collation_connection = Utf8_unicode_ci '
init_connect= ' SET NAMES UTF8 '
Character-set-server=utf8
Collation-server=utf8_unicode_ci
Skip-character-set-client-handshake
Add in the [Client] tab of the/ETC/MY.CNF.D/CLIENT.CNF file
Default-character-set=utf8
added in the [MySQL] tab of the/ETC/MY.CNF.D/MYSQL-CLIENTS.CNF file
Default-character-set=utf8
After the configuration is complete, enter the command to restart MARIADB:
Systemctl Restart MARIADB
Enter MARIADB:
Mysql-u root-p
Prompt to enter a password, enter the password of my last set 19930309, note will not show, enter the end of the direct return is good.
Check out our set of character sets and enter:
Show variables like "%character%", show variables like "%collation%";
Here for ease of use, I will enter the location of the command from the virtual machine terminal replaced with Xshell, and terminal input is not different, Xshell method of use in another blog I have mentioned (http://www.cnblogs.com/ renjiashuo/p/7247388.html), do not repeat here.
Displayed as
The character set configuration is complete.
Enter a command to see the existing database:
show databases;
You can see that we now have 4 database.
Third, using database and Golang to realize leader election of distributed system
Enter the command in Xshell using the test table:
Use test
In Xshell, enter a command to grant the database extranet access:
Grant all privileges on * * to [email protected] '% ' identified by ' 19930309 ';
Where root sets the database user name for us, 19930309 is my database password.
Create a data table for the current leader records and updates:
CREATE TABLE service_election ( anchor tinyint (3) unsigned not NULL, service_id varchar (+) NOT NULL, Last_ Seen_active timestamp not NULL DEFAULT current_timestamp, PRIMARY KEY (anchor)) Engine=innodb
You can view all the tables that are contained under this test database by entering the following command:
Show tables;
Here's a look at the database tables we created:
SHOW full COLUMNS from service_election;
You can see that the table has been created successfully, as shown in.
Once the database is complete, we begin to write the Golang program.
First use Git to get the Golang to MySQL API, the following is the git command:
View Golang's Location:
which go
Set Goroot:
Export Goroot=/c/go
I put the Golang program in the D-Disk Golang folder, then set up a bit gopath:
Export gopath=/d/golang/
Get zookeeper to go API:
Go get Github.com/go-sql-driver/mysql
Under the D-Disk Golang folder to create a new two go project, write the following code to simulate the leader election process:
Package Mainimport ("Database/sql" "Fmt" _ "Github.com/go-sql-driver/mysql" "Time") Func main () {//Connect db, err: = SQL. Open ("MySQL", "root:[email protected" (192.168.40.128:3306)/test?charset=utf8 ") Checkerr (ERR)// If there is no data in the database table used to record leader, insert the data and set the process to Leaderrows, err: = db. Query ("SELECT * from Service_election for update") Checkerr (err) if rows = = nil{_, err = db. Exec ("Replace into service_election (anchor, service_id, last_seen_active) VALUES (1, ' User1 ', Now ())") Checkerr (Err)}db . Query ("commit");//Poll for {//locking rows, err: = db. Query ("select * from service_election where anchor = ' 1 ' for Update") Checkerr (Err) for rows. Next () {var anchor intvar service_id stringvar last_seen_active stringrows. Columns () Err = rows. Scan (&anchor, &service_id, &last_seen_active) checkerr (err)//fmt. PRINTLN (last_seen_active) Local, _: = time. Loadlocation ("Local") tm2, _: = time. Parseinlocation ("2006-01-02 15:04:05", last_seen_active, local)//fmt. Println (TM2. Unix ())//fmt. Println (TM2) Now: = time. Now ()//fmt. PrIntln (now. Unix ())//update the timestamp every 5 seconds, if the time stamp is found to have not been updated for more than 10 seconds, then campaign leaderif service_id = = "User1" && now. Unix ()-tm2. Unix () > 5 {//Insert data _, Err = db. Exec ("update service_election set service_id = ' User1 ', last_seen_active = Now () where anchor = ' 1 '") Checkerr (ERR)}else if Now. Unix ()-tm2. Unix () > 10 {//Insert data _, Err = db. Exec ("update service_election set service_id = ' User1 ', last_seen_active = Now () where anchor = ' 1 '") Checkerr (err)}//unlock db. Query ("Commit");} Query whether this process is leaderrows, err = db. Query ("SELECT * from Service_election") Checkerr (Err) for rows. Next () {var anchor intvar service_id stringvar last_seen_active stringrows. Columns () Err = rows. Scan (&anchor, &service_id, &last_seen_active) Checkerr (err) if service_id = = "User1" {fmt. Println ("I am the Master.")} else {fmt. Println ("I am the Slave.")}} Time. Sleep (time. Second * 5)}db. Close ()}func Checkerr (err error) {if err! = Nil {panic (err)}}
Package Mainimport ("Database/sql" "Fmt" _ "Github.com/go-sql-driver/mysql" "Time") Func main () {//Connect db, err: = SQL. Open ("MySQL", "root:[email protected" (192.168.40.128:3306)/test?charset=utf8 ") Checkerr (ERR)// If there is no data in the database table used to record leader, insert the data and set the process to Leaderrows, err: = db. Query ("SELECT * from Service_election for update") Checkerr (err) if rows = = nil{_, err = db. Exec ("Replace into service_election (anchor, service_id, last_seen_active) VALUES (1, ' User2 ', Now ())") Checkerr (Err)}db . Query ("commit");//Poll for {//locking rows, err: = db. Query ("select * from service_election where anchor = ' 1 ' for Update") Checkerr (Err) for rows. Next () {var anchor intvar service_id stringvar last_seen_active stringrows. Columns () Err = rows. Scan (&anchor, &service_id, &last_seen_active) checkerr (err)//fmt. PRINTLN (last_seen_active) Local, _: = time. Loadlocation ("Local") tm2, _: = time. Parseinlocation ("2006-01-02 15:04:05", last_seen_active, local)//fmt. Println (TM2. Unix ())//fmt. Println (TM2) Now: = time. Now ()//fmt. PrIntln (now. Unix ())//update the timestamp every 5 seconds, if the time stamp is found to have not been updated for more than 10 seconds, then campaign leaderif service_id = = "User2" && now. Unix ()-tm2. Unix () > 5 {//Insert data _, Err = db. Exec ("update service_election set service_id = ' User2 ', last_seen_active = Now () where anchor = ' 1 '") Checkerr (ERR)}else if Now. Unix ()-tm2. Unix () > 10 {//Insert data _, Err = db. Exec ("update service_election set service_id = ' User2 ', last_seen_active = Now () where anchor = ' 1 '") Checkerr (err)}//unlock db. Query ("Commit");} Query whether this process is leaderrows, err = db. Query ("SELECT * from Service_election") Checkerr (Err) for rows. Next () {var anchor intvar service_id stringvar last_seen_active stringrows. Columns () Err = rows. Scan (&anchor, &service_id, &last_seen_active) Checkerr (err) if service_id = = "User2" {fmt. Println ("I am the Master.")} else {fmt. Println ("I am the Slave.")}} Time. Sleep (time. Second * 5)}db. Close ()}func Checkerr (err error) {if err! = Nil {panic (err)}}
The difference between the two program codes is that the SERVICE_ID entry for the database table is set to User1, and the other is set to UESR2. In practical applications, we can set this to the IP of the respective physical machine.
Run two programs respectively, you can see a program continuously output "I am the Master.", another program constantly output "I am the slave.", if the master program is closed, after about 10 seconds, the slave program starts to output master, Then open the previously closed program, it has become the new slave.
Since then, the CentOS environment has implemented the leader elections for distributed systems using the MARIADB (MySQL) database with Golang.
Iv. Reference network resources
Http://www.cnblogs.com/starof/p/4680083.html
Http://www.linuxidc.com/Linux/2016-03/128880.htm
http://blog.csdn.net/a19352226/article/details/50814900
Http://code.openark.org/blog/mysql/leader-election-using-mysql
The CentOS environment uses the MARIADB (MySQL) database to implement leader elections for distributed systems using Golang