douzong5057 2017-05-14 10:31
浏览 27
已采纳

同时插入到Redis

I have three elements consisting of 1 million, 2 million and 3 million ints respectively. I want to insert them to redis such that they all happen concurrently and the total execution time is not greater than the execution time of the 3 million ints. I tried using sync.Waitgroup but it doesn't speed up the execution. Here's my basic code.

package main

import (
    "log"
    "strconv"
    "time"

    "gopkg.in/redis.v5"
)

func main() {
    oneMillion := makeRange(1, 1000000)
    twoMillion := makeRange(1000001, 3000000)
    threeMillion := makeRange(3000001, 6000000)
    elements := [][]int{oneMillion, twoMillion, threeMillion}
    client := redis.NewClient(&redis.Options{
        Addr:         "localhost:6379",
        Password:     "",
        DB:           0,
        DialTimeout:  60 * time.Second,
        WriteTimeout: 60 * time.Second,
        ReadTimeout:  60 * time.Second,
        PoolTimeout:  60 * time.Second,
    })
    pipeline := client.Pipeline()
    for _, elem := range elements {
        for i := 0; i < len(elem); i++ {
            key := "KEY:" + strconv.Itoa(elem[i])
            val := "VAL:" + strconv.Itoa(elem[i])
            cmd := pipeline.Set(key, val, 0)
            if cmd.Err() != nil {
                log.Fatal("cmd error: ", cmd.Err())
            }
        }
        _, err := pipeline.Exec()
        if err != nil {
            log.Fatal("error: ", err)
        }
    }
}

func makeRange(min, max int) []int {
    a := make([]int, max-min+1)
    for i := range a {
        a[i] = min + i
    }
    return a
}
  • 写回答

1条回答 默认 最新

  • dongliao2011 2017-05-14 12:29
    关注

    More or less every operation on redis is atomic , i.e only one operation will be executing on the redis server at any given time. So in theory if you want to do say 3 million set operations on a redis server all those operations will happen serially.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥100 嵌入式系统基于PIC16F882和热敏电阻的数字温度计
  • ¥20 BAPI_PR_CHANGE how to add account assignment information for service line
  • ¥500 火焰左右视图、视差(基于双目相机)
  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)