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} }
时间: 2024-12-03 12:57:34