vitess中rpc兼容http请求的技巧

Vitess是Google的一个MySQL项目,采用Go和Python实现。该项目通过RPC方式转发MySQL请求,并巧妙地兼容了HTTP协议,使得可以利用现有的监控工具进行服务监控,方便实现查询信息功能并使用现有工具进行测试。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vitess是google的一个mysql项目,用go和python实现。https://code.google.com/p/vitess/

vitess中用rpc方式来中转mysql的请求,其中rpc的实现很有意思,兼容了http请求。

兼容http请求有明显的好处:

1.可以用现成的监控工具来监控服务是否正常,不用另外写插件

2.可以方便地实现查询信息功能,不用另外再开发工具或者界面

3.可以方便地用现成的工具测试


在vitess中很简单地实现了这个功能。client在建立连接后,第一个包是http头,而server端也会有一个200的回应。

详细见代码:

https://code.google.com/p/vitess/source/browse/py/net/gorpc.py#87

https://code.google.com/p/vitess/source/browse/go/rpcwrap/rpcwrap.go

python client:

class _GoRpcConn(object):
  def __init__(self, timeout):
    self.conn = None
    self.timeout = timeout
    self.start_time = None

  def dial(self, uri):
    parts = urlparse.urlparse(uri)
    netloc = parts.netloc.split(':')
    # NOTE(msolomon) since the deadlines are approximate in the code, set
    # timeout to oversample to minimize waiting in the extreme failure mode.
    socket_timeout = self.timeout / 10.0
    self.conn = socket.create_connection((netloc[0], int(netloc[1])),
                                         socket_timeout)
    self.conn.sendall('CONNECT %s HTTP/1.0\n\n' % parts.path)
    while True:
      data = self.conn.recv(1024)
      if not data:
        raise GoRpcError('Unexpected EOF in handshake')
      if '\n\n' in data:
        return

go server:

const (
        connected = "200 Connected to Go RPC"
)

type ClientCodecFactory func(conn io.ReadWriteCloser) rpc.ClientCodec

type BufferedConnection struct {
        *bufio.Reader
        io.WriteCloser
}

func NewBufferedConnection(conn io.ReadWriteCloser) *BufferedConnection {
        return &BufferedConnection{bufio.NewReader(conn), conn}
}

// DialHTTP connects to a go HTTP RPC server using the specified codec.
func DialHTTP(network, address, codecName string, cFactory ClientCodecFactory) (*rpc.Client, error) {
        var err error
        conn, err := net.Dial(network, address)
        if err != nil {
                return nil, err
        }
        io.WriteString(conn, "CONNECT "+GetRpcPath(codecName)+" HTTP/1.0\n\n")

        // Require successful HTTP response
        // before switching to RPC protocol.
        buffered := NewBufferedConnection(conn)
        resp, err := http.ReadResponse(buffered.Reader, &http.Request{Method: "CONNECT"})
        if err == nil && resp.Status == connected {
                return rpc.NewClientWithCodec(cFactory(buffered)), nil
        }
        if err == nil {
                err = errors.New("unexpected HTTP response: " + resp.Status)
        }
        conn.Close()
        return nil, &net.OpError{"dial-http", network + " " + address, nil, err}
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值