Go语言采用go-redis模块对Redis进行批量操作(MULTI和EXEC) 的示例及性能
·
go-redis对redis执行批量操作(事务transaction)的类是Pipeliner,支持全部常用命令如set,incr,expire等等,具体示例如下.
运行该示例可在redis服务端依次接收到:
- MULTI
- incr tx_pipeline_counter
- expire tx_pipeline_counter 3600
- EXEC
package main
import (
"fmt"
"github.com/go-redis/redis"
"time"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "192.168.16.242:6379",
Password: "",
DB: 0,
})
defer client.Close()
pipe := client.TxPipeline()
incr := pipe.Incr("tx_pipeline_counter")
pipe.Expire("tx_pipeline_counter", time.Hour)
// Execute
//
// MULTI
// INCR pipeline_counter
// EXPIRE pipeline_counts 3600
// EXEC
//
// using one redisdb-server roundtrip.
_, err := pipe.Exec()
fmt.Println(incr.Val(), err)
}
更复杂的命令如smembers的批量操作请见《Go语言采用go-redis模块对Redis进行批量执行smembers的示例》
性能比较:
多条命令采用批量处理不止节省网络时间,同时也节省redis服务端的处理时间。
package main
import (
"fmt"
"github.com/go-redis/redis"
"time"
)
func main() {
client := redis.NewClient(&redis.Options{
Addr: "192.168.16.242:6379",
Password: "",
DB: 0,
})
defer client.Close()
tSaved := time.Now()
test1(client)
fmt.Printf("elapse: %v\n", time.Now().Sub(tSaved))
tSaved = time.Now()
test2(client)
fmt.Printf("elapse: %v\n", time.Now().Sub(tSaved))
}
func test1(client *redis.Client) {
_, _ = client.Incr("tx_pipeline_counter").Result()
_ = client.Expire("tx_pipeline_counter", time.Hour)
}
func test2(client *redis.Client) {
pipe := client.TxPipeline()
_ = pipe.Incr("tx_pipeline_counter")
pipe.Expire("tx_pipeline_counter", time.Hour)
pipe.Exec()
}
[root@dev] go run redisPipe.go
elapse: 1.879213ms
elapse: 793.786µs
[root@dev] ping 192.168.16.242
PING 192.168.16.242 (192.168.16.242) 56(84) bytes of data.
64 bytes from 192.168.16.242: icmp_seq=1 ttl=63 time=0.436 ms
64 bytes from 192.168.16.242: icmp_seq=2 ttl=63 time=0.449 ms
64 bytes from 192.168.16.242: icmp_seq=3 ttl=63 time=0.445 ms
相关文章:
更多推荐
已为社区贡献6条内容
所有评论(0)