docker-compose.yml
version: "3"
services:
consul:
image: "consul"
container_name: consul
restart: always
ports:
- "8500:8500"
- "8600:8600/tcp"
- "8600:8600/udp"
command: agent -server -bootstrap-expect=1 -node=consul-node-1 -bind=0.0.0.0 -client=0.0.0.0 -datacenter=dc1 -ui -config-dir=/consul/config
volumes:
- "./data:/consul/data"
- "./config:/consul/config"
networks:
- default
networks:
default:
external:
name: xxxxx
config/consul-acl.json
{
"acl": {
"enabled": true,
"default_policy": "deny",
"down_policy": "extend-cache",
"enable_token_persistence": true
}
}
获取acl token
docker exec -it consul sh
consul acl bootstrap
下面的SecretID就是权限最高的token
AccessorID: 359eb4f0-74b5-927d-bb8d-e9ef3c0d9b46
SecretID: 07337e1f-d88d-b018-90b4-2f4402a2b369
Description: Bootstrap Token (Global Management)
Local: false
Create Time: 2023-04-12 11:14:30.111459155 +0000 UTC
Policies:
00000000-0000-0000-0000-000000000001 - global-management
服务端注册服务
import (
capi "github.com/hashicorp/consul/api"
)
func register() {
conf := capi.DefaultConfig()
conf.Token = "token-xxxxx"
conf.Address = "xxx.xxx.xxx:8500"
check := &capi.AgentServiceCheck{
HTTP: fmt.Sprintf("http://%s:%d/health", "serviceAddr", 80),
Timeout: "5s",
Interval: "10s",
DeregisterCriticalServiceAfter: "30s",
}
regGrpc := &capi.AgentServiceRegistration{
ID: "serviceIdxxx",
Name: "serviceNamexxx",
Port: 9000,
Address: "serviceAddr",
Tags: []string{"grpc"},
Check: check,
Meta: map[string]string{
"WebPort": strconv.Itoa(80),
},
}
clientGrpc, err := capi.NewClient(conf)
if err != nil {
logrus.Panic(err)
}
if err = clientGrpc.Agent().ServiceRegister(regGrpc); err != nil {
panic(err)
}
}
客户端发现服务
package main
import (
"fmt"
"log"
capi "github.com/hashicorp/consul/api"
)
func main() {
config := capi.DefaultConfig()
config.Token = "xxxxxxxxxx"
config.Address = "xxx.xxx.com:8500"
// Get a new client
client, err := capi.NewClient(config)
if err != nil {
panic(err)
}
services, _, err := client.Health().Service("usersrv", "", true, nil)
if err != nil {
log.Panic("error retrieving instances from Consul:", err)
}
for _, service := range services {
fmt.Println("service.Service.Address:", service.Service.Address, "service.Service.Port:", service.Service.Port)
fmt.Printf("mate:%+v\n", service.Service.Meta)
}
}