下载地址
# 官方下载地址
https://go.dev/dl/
# 下载解压
wget https://go.dev/dl/go1.21.5.linux-amd64.tar.gz
tar xf go1.21.5.linux-amd64.tar.gz -C /usr/local/go117
环境变量
# cat /etc/profile.d/go.sh
export GOROOT=/usr/local/go117
export GOPATH=/data/go_path
export PATH=$GOPATH/bin:$GOROOT/bin:$PATH
export GOPROXY="https://goproxy.cn,direct"
###加载环境变量
# source /etc/profile.d/go.sh
# go env
并发示例
cat xiecheng_redis.go
//8个协程,并发读写100w个key
package main
import (
"fmt"
"log"
"sync"
"context"
"github.com/go-redis/redis/v8"
)
func main() {
// 创建Redis客户端
ctx := context.Background()
// client := redis.NewClient(&redis.Options{
// Addr: "127.0.0.1:7001",
// Password: "xxxxxxxxxx", // 如果有密码,则填写密码
// DB: 0, // 使用默认的数据库
// })
client := redis.NewClusterClient(&redis.ClusterOptions{
Addrs: []string{"redis-node1:7001", "redis-node2:7001", "redis-node3:7001"}, // 替换为你的Redis集群节点地址
Password: "xxxxxxxxxx", // 如果有密码,则填写密码
})
// 创建等待组
var wg sync.WaitGroup
// 设置并发数
concurrency := 8
// 每个协程处理的key数量
keysPerRoutine := 1000000 / concurrency
// 并发写入key
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func(startIndex int) {
defer wg.Done()
for j := startIndex; j < startIndex+keysPerRoutine; j++ {
key := fmt.Sprintf("key%d", j)
value := fmt.Sprintf("value%d", j)
err := client.Set(ctx, key, value, 0).Err()
if err != nil {
log.Printf("Failed to set key %s: %v", key, err)
}
}
}(i * keysPerRoutine)
}
// 等待所有协程完成写入操作
wg.Wait()
// 并发读取key
for i := 0; i < concurrency; i++ {
wg.Add(1)
go func(startIndex int) {
defer wg.Done()
for j := startIndex; j < startIndex+keysPerRoutine; j++ {
key := fmt.Sprintf("key%d", j)
value, err := client.Get(ctx, key).Result()
if err != nil {
log.Printf("Failed to get key %s: %v", key, err)
} else {
log.Printf("Key: %s, Value: %s", key, value)
}
}
}(i * keysPerRoutine)
}
// 等待所有协程完成读取操作
wg.Wait()
}