发布时间:2024-11-22 00:03:48
package main
import (
"fmt"
"log"
"net/http"
"github.com/hashicorp/consul/api"
)
func main() {
// 创建Consul客户端
client, err := api.NewClient(api.DefaultConfig())
if err != nil {
log.Fatal(err)
}
// 创建一个新的服务实例
reg := &api.AgentServiceRegistration{
ID: "example-service-1",
Name: "service-1",
Port: 8080,
}
// 向Consul注册服务
err = client.Agent().ServiceRegister(reg)
if err != nil {
log.Fatal(err)
}
// 检查Consul中已注册的服务
services, _, err := client.Catalog().Service("service-1", "", nil)
if err != nil {
log.Fatal(err)
}
// 打印已注册的服务信息
for _, service := range services {
fmt.Printf("Service ID: %s, Service Name: %s, Address: %s, Port: %d\n",
service.ServiceID, service.ServiceName, service.Address, service.ServicePort)
}
// 使用HTTP启动一个简单的服务
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte("Hello, world!"))
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
package main
import (
"fmt"
"log"
"github.com/hashicorp/consul/api"
)
func main() {
// 创建Consul客户端
client, err := api.NewClient(api.DefaultConfig())
if err != nil {
log.Fatal(err)
}
// 从Consul中读取配置
kv := client.KV()
pair, _, err := kv.Get("example-config-key", nil)
if err != nil {
log.Fatal(err)
}
// 输出配置值
fmt.Printf("Config Value: %s\n", pair.Value)
}
package main
import (
"log"
"time"
"github.com/hashicorp/consul/api"
)
func main() {
// 创建Consul客户端
client, err := api.NewClient(api.DefaultConfig())
if err != nil {
log.Fatal(err)
}
// 创建一个新的健康检查实例
check := &api.AgentServiceCheck{
CheckID: "example-health-check",
TTL: "10s",
DeregisterCriticalServiceAfter: "1m",
}
// 向Consul注册健康检查
err = client.Agent().CheckRegister(check)
if err != nil {
log.Fatal(err)
}
// 定期发送心跳请求
for {
err = client.Agent().PassTTL("example-health-check", "Service is healthy")
if err != nil {
log.Fatal(err)
}
time.Sleep(5 * time.Second)
}
}