94 lines
2.5 KiB
Go
94 lines
2.5 KiB
Go
package main
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/nacos-group/nacos-sdk-go/clients"
|
|
"github.com/nacos-group/nacos-sdk-go/clients/naming_client"
|
|
"github.com/nacos-group/nacos-sdk-go/common/constant"
|
|
"github.com/nacos-group/nacos-sdk-go/vo"
|
|
"io/ioutil"
|
|
"log"
|
|
"net/http"
|
|
)
|
|
|
|
var nameClient naming_client.INamingClient
|
|
|
|
func initNacos() {
|
|
sc := []constant.ServerConfig{
|
|
*constant.NewServerConfig("nacos", 8848),
|
|
}
|
|
cc := constant.ClientConfig{
|
|
AppName: "gateway",
|
|
//NamespaceId: "e56f939e-6d22-449c-97d2-39a8ae5afd58", //namespace id
|
|
NamespaceId: "",
|
|
TimeoutMs: 5000,
|
|
NotLoadCacheAtStart: true,
|
|
RotateTime: "1h",
|
|
MaxAge: 3,
|
|
LogLevel: "debug",
|
|
}
|
|
client, err := clients.NewNamingClient(
|
|
vo.NacosClientParam{
|
|
ClientConfig: &cc,
|
|
ServerConfigs: sc,
|
|
},
|
|
)
|
|
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
success, _ := client.RegisterInstance(vo.RegisterInstanceParam{
|
|
//Ip: "172.30.0.90",
|
|
Port: 8889,
|
|
Weight: 10,
|
|
ServiceName: "gateway",
|
|
})
|
|
log.Println("Nacos注册结果: ", success)
|
|
nameClient = client
|
|
}
|
|
|
|
func get(method, url string) string {
|
|
info, err := nameClient.SelectAllInstances(vo.SelectAllInstancesParam{
|
|
ServiceName: "api1",
|
|
})
|
|
if err != nil {
|
|
return "获取服务异常:" + err.Error()
|
|
}
|
|
log.Println("获取到实例数量:", len(info))
|
|
instance, err := nameClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
|
|
ServiceName: "api1",
|
|
//GroupName: "Micro", // 默认值DEFAULT_GROUP
|
|
//Clusters: []string{pojo.InitConf.CurVersion}, // 默认值DEFAULT
|
|
})
|
|
if err != nil {
|
|
return "获取服务异常:" + err.Error()
|
|
}
|
|
apiUrl := fmt.Sprintf("http://%v:%v%v", instance.Ip, instance.Port, url)
|
|
response, err := http.Get(apiUrl)
|
|
if err != nil {
|
|
log.Fatalf("请求异常: %v", err)
|
|
}
|
|
content, err := ioutil.ReadAll(response.Body)
|
|
respBody := string(content)
|
|
return respBody
|
|
}
|
|
|
|
func post(url string) string {
|
|
instance, err := nameClient.SelectOneHealthyInstance(vo.SelectOneHealthInstanceParam{
|
|
ServiceName: "api1",
|
|
//GroupName: "Micro", // 默认值DEFAULT_GROUP
|
|
//Clusters: []string{pojo.InitConf.CurVersion}, // 默认值DEFAULT
|
|
})
|
|
if err != nil {
|
|
return "获取服务异常:" + err.Error()
|
|
}
|
|
apiUrl := fmt.Sprintf("http://%v:%v%v", instance.Ip, instance.Port, url)
|
|
response, err := http.Post(apiUrl, "application/json", nil)
|
|
if err != nil {
|
|
log.Fatalf("请求异常: %v", err)
|
|
}
|
|
content, err := ioutil.ReadAll(response.Body)
|
|
respBody := string(content)
|
|
return respBody
|
|
}
|