接口需要提供给其他业务组访问,但是 RPC 协议不同无法内调,对方问能否走 HTTP 接口 有时候,我们服务都需要同时支持 grpc 跟 http(restful)协议,但是我们又不想多端口开放
原理主要是通过共用listener
模式 通过Accept()
入口来区分协议内容
package main
import (
"github.com/soheilhy/cmux"
)
func Run(){
// 起服务
// Create the main listener.
l, err := net.Listen("tcp", ":23456")
if err != nil {
log.Fatal(err)
}
// Create a cmux.
m := cmux.New(l)
// First grpc, then HTTP, and otherwise Go RPC/TCP.
grpcL := m.MatchWithWriters(cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc"))
go grpcS.Serve(grpcL)// Use the muxed listeners for your servers.
httpL := m.Match(cmux.HTTP1Fast())
httpS := &http.Server{
Handler: &helloHTTP1Handler{},
}
go httpS.Serve( httpL)
// Start serving!
m.Serve()
}
package main
import (
"github.com/soheilhy/cmux"
)
func Run(){
// 起服务
l, err := net.Listen("tcp", ":23456")
m := cmux.New(l)
// grpc
grpcL := m.MatchWithWriters(cmux.HTTP2MatchHeaderFieldSendSettings("content-type", "application/grpc"))
grpcS := grpc.NewServer()
grpchello.RegisterGreeterServer(grpcS, &server{})
go grpcS.Serve(grpcL)
// http
router := gin.Default()
go func (){
httpL := m.Match(cmux.HTTP1Fast())
router.RunListener( httpL)
}()
// Start serving!
m.Serve()
}
1
fucUup 2021-02-24 20:46:05 +08:00 via Android
Cmux 这个开源库比较多 bug,小心
|
2
echowuhao 2021-02-24 22:06:54 +08:00
放到不同路径下不更简单么
|
3
mooyo 2021-02-25 00:23:35 +08:00 via iPhone
为啥不通过域名或者路径来区分呢
|
5
julyclyde 2021-02-25 12:05:45 +08:00
gRPC 不就是 HTTP/2 么?
|
6
leeyuzhe 2021-02-25 13:46:11 +08:00
对啊,路径区分多简单
|
7
coderxy 2021-02-25 14:54:20 +08:00
grpc gateway ?
|
8
LanLiang 2021-03-16 12:55:25 +08:00
为啥不考虑多端口+路径路由方式?
|