2 Star 6 Fork 4

Jason的雷哥 / apigw-quickstart

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
main.go 4.16 KB
一键复制 编辑 原始数据 按行查看 历史
package main
import (
"context"
"encoding/json"
"io"
"io/ioutil"
"net/http"
"strings"
"time"
"gitee.com/jason_elva8325/apigw-quickstart/common"
"gitee.com/jason_elva8325/apigw-quickstart/config"
"github.com/afex/hystrix-go/hystrix"
"github.com/go-kit/kit/circuitbreaker"
"github.com/go-kit/kit/endpoint"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/sd"
"github.com/go-kit/kit/sd/etcdv3"
"github.com/go-kit/kit/sd/lb"
"github.com/gorilla/mux"
)
func init() {}
func main() {}
// AdapterRegistry 适配器注册方法,方法名及参数不能修改,否则无法注册
func AdapterRegistry(router *mux.Router, logger log.Logger, client etcdv3.Client, srdPrefix string, adapters map[string]config.Adapter) {
// 获取适配器配置
cbc := hystrix.CommandConfig{}
var prefixURI, version string
if cbs, ok := adapters["say-goodby-http"]; ok {
prefixURI = cbs.PrefixURI
version = cbs.Version
if cb, ok := cbs.Hystries["hystrix"]; ok {
cbc.Timeout = cb.Timeout
cbc.SleepWindow = cb.SleepWindow
cbc.ErrorPercentThreshold = cb.ErrorPercentThreshold
cbc.MaxConcurrentRequests = cb.MaxConcurrentRequests
cbc.RequestVolumeThreshold = cb.RequestVolumeThreshold
}
}
router.HandleFunc("/"+version+prefixURI+"/goodby/{lang}", func(w http.ResponseWriter, r *http.Request) {
// 声明最终返回对象
var httpResponse = common.GenericResponse{}
// 解析HTTP请求
vars := mux.Vars(r)
lang, ok := vars["lang"]
if !ok {
return
}
target := r.URL.Query().Get("target")
//创建实例例管理理器器, 此管理理器器会Watch监听etc中prefix的⽬目录变化更更新缓存的服务实例例数据
instancer, err := etcdv3.NewInstancer(client, srdPrefix+"Say/HTTP/", logger)
if err != nil {
logger.Log("Service watcher on ETCD server create fail", err, "sessionid", r.Header.Get("Sessionid"))
return
}
//创建端点管理理器器, 此管理理器器根据Factory和监听的到实例例创建endPoint并订阅instancer的变化
endpointer := sd.NewEndpointer(instancer, func(instanceAddr string) (endpoint.Endpoint, io.Closer, error) {
return func(ctx context.Context, request interface{}) (interface{}, error) {
logger.Log("http call addr", instanceAddr, "sessionid", r.Header.Get("Sessionid"))
rs := map[string]interface{}{} // 定义http.Response.Body的结构对象
client := &http.Client{}
req, err := http.NewRequest("GET", instanceAddr+"/say/goodby/"+lang+"?target="+target, strings.NewReader(""))
if err != nil {
logger.Log("HTTP request object create fail", err, "sessionid", r.Header.Get("Sessionid"))
return nil, err
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Sessionid", r.Header.Get("Sessionid")) // 追加sessionid到HTTP的Header信息中,用于服务链路追踪
resp, err := client.Do(req)
if err != nil {
logger.Log("HTTP request execute fail", err, "sessionid", r.Header.Get("Sessionid"))
return nil, err
}
defer resp.Body.Close()
resBody, err := ioutil.ReadAll(resp.Body)
if err != nil {
logger.Log("HTTP response body read fail", err, "sessionid", r.Header.Get("Sessionid"))
return nil, err
}
json.Unmarshal(resBody, &rs)
logger.Log("Function", "SayHello", "Execute", "success", "sessionid", r.Header.Get("Sessionid"))
return rs, nil
}, nil, nil
}, logger)
//创建负载均衡器器
balancer := lb.NewRoundRobin(endpointer)
reqEndPoint := lb.Retry(2, 3*time.Second, balancer)
//创建服务熔断
// 可通过关闭服务端予以测试
commandName := "my-endpoint"
hystrix.ConfigureCommand(commandName, cbc)
reqEndPoint = circuitbreaker.Hystrix(commandName)(reqEndPoint)
//通过 endPoint 发起请求
ereq := struct{}{}
eres, err := reqEndPoint(context.Background(), ereq)
if err != nil {
logger.Log("Backend service call fail", err, "sessionid", r.Header.Get("Sessionid"))
httpResponse.Err = err.Error()
w.WriteHeader(http.StatusExpectationFailed)
} else {
w.WriteHeader(http.StatusOK)
}
httpResponse.V = eres
// 返回HTTP结果
json.NewEncoder(w).Encode(&httpResponse)
}).Methods("GET")
logger.Log("Loaded adapter", "say-goodby-"+version)
}
Go
1
https://gitee.com/jason_elva8325/apigw-quickstart.git
git@gitee.com:jason_elva8325/apigw-quickstart.git
jason_elva8325
apigw-quickstart
apigw-quickstart
v0.3.0

搜索帮助