Golang 简单的读负责均衡

栏目: IT技术 · 发布时间: 6年前

内容简介:作者:王清培(趣头条 Tech Leader)

read-loadbalance

master-slave(n) 读库集群负载均衡器(简单轮询)+时间间隔错峰。

github 地址:https://github.com/Plen-wang/read-loadbalance

使用场景

1.一般我们会有多个从库,需要在从库的读取上做负载均衡。

2.在数仓拉取数据的时候经常对产线DB造成影响,所以会独立一个从库专门用来拉取,但是这个从库的利用率非常低。

数仓拉取数据一般在业务低峰期进行,iops峰值较高,但是持续时间很短。我们可以错开这个时间段,让这台从库的利用率最大化。

Golang 简单的读负责均衡
package main

import (
    "database/sql"
    "fmt"
    _ "github.com/go-sql-driver/mysql"
    "github.com/gocraft/dbr"
    "github.com/read-loadbalance/lb"
    "log"
)

var slaveLB *lb.SlaveLoadBalancer

func main() {
    //构造数据源
    creator := func() *sql.DB {
        dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&autocommit=1", "root", 123456, "localhost", 3306, "test", "utf8mb4")
        conn, er := sql.Open("mysql", dsn)
        if er != nil {
            log.Fatalf("create db conn error:%v", er.Error())
        }
        return conn
    }

    slave1 := creator()
    slave2 := creator()

    //构造slave-lb
    slaveLB = lb.BuildSlaveLoadBalancer(1, 2, 1, slave1, slave2)

    //获取数据源
    _, _, conn := slaveLB.GetPollingNode()

    //放入任意orm中,这里举例dbr
    orm := &dbr.Connection{DB: conn}
    orm.NewSession(nil).SelectBySql("select id from tb_orders limit 1")

}

作者:王清培(趣头条 Tech Leader)


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。

Beginning PHP and MySQL 5

Beginning PHP and MySQL 5

W. Jason Gilmore / Apress / 2006-01-23 / USD 44.99

Beginning PHP and MySQL 5: From Novice to Professional, Second Edition offers comprehensive information about two of the most prominent open source technologies on the planet: the PHP scripting langua......一起来看看 《Beginning PHP and MySQL 5》 这本书的介绍吧!

JS 压缩/解压工具
JS 压缩/解压工具

在线压缩/解压 JS 代码

URL 编码/解码
URL 编码/解码

URL 编码/解码

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具