How to use Go language and Redis to implement an online voting system
Overview:
The online voting system is a common application scenario and can be used in various situations , such as elections, questionnaires, selections, etc. This article will introduce how to use Go language and Redis to implement a simple online voting system. We will use Go language as the back-end development language and Redis as data storage and cache.
package main import ( "fmt" "log" "github.com/go-redis/redis" ) func main() { // 连接到Redis服务器 client := redis.NewClient(&redis.Options{ Addr: "localhost:6379", Password: "", DB: 0, }) // 检查连接是否成功 pong, err := client.Ping().Result() if err != nil { log.Fatal(err) } fmt.Println(pong) // 设置初始投票选项及其票数 options := map[string]int{ "Option1": 0, "Option2": 0, "Option3": 0, } // 将选项及其票数保存到Redis中 for option, count := range options { err := client.HSet("votes", option, count).Err() if err != nil { log.Fatal(err) } } // 投票 option := "Option1" err = client.HIncrBy("votes", option, 1).Err() if err != nil { log.Fatal(err) } // 获取每个选项的票数 votes, err := client.HGetAll("votes").Result() if err != nil { log.Fatal(err) } // 打印投票结果 for option, count := range votes { fmt.Printf("%s: %s ", option, count) } }
In the above code, we first create a Redis client end, and then connect to the Redis server. If the connection is successful, we set the initial voting options and their number of votes and save them to the Redis hash table. Next, we simulate a user voting process and add 1 to the number of votes for the option. Finally, we use the HGetAll command to get the number of votes for each option and print the voting results.
The above is the detailed content of How to implement an online voting system using Go language and Redis. For more information, please follow other related articles on the PHP Chinese website!