Skip to content

Commit 2269edf

Browse files
committed
first commit
0 parents  commit 2269edf

File tree

9 files changed

+938
-0
lines changed

9 files changed

+938
-0
lines changed

.gitignore

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
.vscode/

client.go

Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
package goconsul
2+
3+
import (
4+
"strconv"
5+
"sync"
6+
7+
"github.com/hashicorp/consul/api"
8+
)
9+
10+
type Client struct {
11+
api.Client
12+
insMap sync.Map
13+
}
14+
15+
func DefaultClient() *Client {
16+
return &Client{}
17+
}
18+
19+
func NewClient(host string, port int, token string) (*Client, error) {
20+
21+
c := &Client{}
22+
23+
if err := c.Connect(host, port, token); err != nil {
24+
return nil, err
25+
}
26+
27+
return c, nil
28+
}
29+
30+
func (c *Client) Connect(host string, port int, token string) error {
31+
config := api.DefaultConfig()
32+
if len(host) > 3 && port > 0 && port <= 65535 {
33+
config.Address = host + ":" + strconv.Itoa(port)
34+
}
35+
36+
config.Token = token
37+
client, err := api.NewClient(config)
38+
if err != nil {
39+
return err
40+
}
41+
42+
c.Client = *client
43+
44+
return nil
45+
}

consul.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
package goconsul

discover.go

Lines changed: 228 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,228 @@
1+
package goconsul
2+
3+
import (
4+
"fmt"
5+
6+
"github.com/gogf/gf/text/gstr"
7+
"github.com/hashicorp/consul/api"
8+
)
9+
10+
type ServiceCheck struct {
11+
api.AgentServiceCheck
12+
}
13+
14+
type IServiceInstance interface {
15+
GetName() string
16+
GetHost() string
17+
GetPort() int
18+
GetMetadata() map[string]string
19+
GetId() string
20+
GetTags() []string
21+
GetLanIps() []string
22+
GetAnnouncedIps() []string
23+
GetServiceCheck() *ServiceCheck
24+
}
25+
26+
func (c *Client) Register(instance *ServiceInstance) error {
27+
28+
// 创建注册到consul的服务到
29+
registration := new(api.AgentServiceRegistration)
30+
registration.ID = instance.GetId()
31+
registration.Name = instance.GetName()
32+
registration.Port = instance.GetPort()
33+
registration.Tags = instance.GetTags()
34+
registration.Meta = instance.GetMetadata()
35+
registration.Address = instance.GetHost()
36+
registration.TaggedAddresses = make(map[string]api.ServiceAddress)
37+
for k, v := range instance.GetLanIps() {
38+
registration.TaggedAddresses[fmt.Sprintf("Lan%v", k)] = api.ServiceAddress{
39+
Address: v,
40+
Port: instance.GetPort(),
41+
}
42+
}
43+
for k, v := range instance.GetAnnouncedIps() {
44+
registration.TaggedAddresses[fmt.Sprintf("Announced%v", k)] = api.ServiceAddress{
45+
Address: v,
46+
Port: instance.GetPort(),
47+
}
48+
}
49+
registration.Check = &instance.GetServiceCheck().AgentServiceCheck
50+
51+
// 注册服务到consul
52+
err := c.Agent().ServiceRegister(registration)
53+
if err != nil {
54+
fmt.Println(err)
55+
return err
56+
}
57+
58+
c.insMap.Store(instance.GetId(), instance)
59+
60+
return nil
61+
}
62+
63+
func (c *Client) DeregisterAll() {
64+
65+
c.insMap.Range(func(key, value interface{}) bool {
66+
c.Agent().ServiceDeregister(key.(string))
67+
c.insMap.Delete(key)
68+
return true
69+
})
70+
}
71+
72+
func (c *Client) Deregister(id string) {
73+
c.Agent().ServiceDeregister(id)
74+
c.insMap.Delete(id)
75+
}
76+
77+
func (c *Client) DiscoverCatalogInstancesWithTags(serviceName string, tags []string) ([]*ServiceInstance, error) {
78+
79+
catalogService, _, err := c.Catalog().ServiceMultipleTags(serviceName, tags, nil)
80+
if err != nil {
81+
return nil, err
82+
}
83+
84+
if len(catalogService) == 0 {
85+
return nil, fmt.Errorf("not found")
86+
}
87+
88+
result := make([]*ServiceInstance, len(catalogService))
89+
for index, server := range catalogService {
90+
announcedIps := make([]string, 0)
91+
announcedIpStr, found := server.ServiceMeta["AnnouncedIp"]
92+
if found && announcedIpStr != "" {
93+
announcedIps = gstr.Split(announcedIpStr, ",")
94+
}
95+
96+
lanIps := make([]string, 0)
97+
lanIpStr, found := server.ServiceMeta["LanIp"]
98+
if found && lanIpStr != "" {
99+
lanIps = gstr.Split(lanIpStr, ",")
100+
}
101+
102+
dataRoot, found := server.ServiceMeta["DataRoot"]
103+
if !found {
104+
dataRoot = ""
105+
}
106+
107+
s := NewInstance(
108+
server.ServiceName,
109+
server.Address,
110+
server.ServicePort,
111+
server.ServiceMeta,
112+
server.ServiceTags,
113+
server.ServiceID,
114+
lanIps,
115+
announcedIps,
116+
c,
117+
dataRoot,
118+
)
119+
120+
result[index] = s
121+
}
122+
123+
return result, nil
124+
}
125+
126+
func (c *Client) DiscoverCatalogInstancesWithName(serviceName string) ([]*ServiceInstance, error) {
127+
return c.DiscoverCatalogInstancesWithTags(serviceName, nil)
128+
}
129+
130+
func (c *Client) DiscoverCatalogInstanceWithId(name string, id string) (*ServiceInstance, error) {
131+
tags := []string{
132+
fmt.Sprintf("serviceName:%v", name),
133+
fmt.Sprintf("instanceId:%v", id),
134+
}
135+
136+
ins, err := c.DiscoverCatalogInstancesWithTags(name, tags)
137+
if err != nil {
138+
return nil, err
139+
}
140+
141+
if len(ins) == 0 {
142+
return nil, fmt.Errorf("not found")
143+
}
144+
145+
return ins[0], nil
146+
}
147+
148+
func (c *Client) DiscoverHealthInstancesWithTags(name string, tags []string, passing bool) ([]*ServiceInstance, error) {
149+
150+
servers, _, err := c.Health().ServiceMultipleTags(name, tags, passing, nil)
151+
if err != nil {
152+
return nil, err
153+
}
154+
155+
if len(servers) == 0 {
156+
return nil, fmt.Errorf("not found")
157+
}
158+
159+
result := make([]*ServiceInstance, len(servers))
160+
for index, server := range servers {
161+
announcedIps := make([]string, 0)
162+
announcedIpStr, found := server.Service.Meta["AnnouncedIp"]
163+
if found && announcedIpStr != "" {
164+
announcedIps = gstr.Split(announcedIpStr, ",")
165+
}
166+
167+
lanIps := make([]string, 0)
168+
lanIpStr, found := server.Service.Meta["LanIp"]
169+
if found && lanIpStr != "" {
170+
lanIps = gstr.Split(lanIpStr, ",")
171+
}
172+
173+
dataRoot, found := server.Service.Meta["DataRoot"]
174+
if !found {
175+
dataRoot = ""
176+
}
177+
178+
s := NewInstance(
179+
server.Service.Service,
180+
server.Service.Address,
181+
server.Service.Port,
182+
server.Service.Meta,
183+
server.Service.Tags,
184+
server.Service.ID,
185+
lanIps,
186+
announcedIps,
187+
c,
188+
dataRoot,
189+
)
190+
191+
result[index] = s
192+
}
193+
194+
return result, nil
195+
}
196+
197+
func (c *Client) DiscoverHealthInstanceWithId(name string, id string, passing bool) (*ServiceInstance, error) {
198+
tags := []string{
199+
fmt.Sprintf("instanceId:%v", id),
200+
}
201+
202+
ins, err := c.DiscoverHealthInstancesWithTags(name, tags, passing)
203+
if err != nil {
204+
return nil, err
205+
}
206+
207+
if len(ins) == 0 {
208+
return nil, fmt.Errorf("not found")
209+
}
210+
211+
return ins[0], nil
212+
}
213+
214+
func (c *Client) DiscoverInstancesWithName(name string, tags []string, passing int) ([]*ServiceInstance, error) {
215+
if passing == -1 {
216+
return c.DiscoverCatalogInstancesWithTags(name, tags)
217+
} else {
218+
return c.DiscoverHealthInstancesWithTags(name, tags, passing == 1)
219+
}
220+
}
221+
222+
func (c *Client) DiscoverInstanceWithId(name string, id string, passing int) (*ServiceInstance, error) {
223+
if passing == -1 {
224+
return c.DiscoverCatalogInstanceWithId(name, id)
225+
} else {
226+
return c.DiscoverHealthInstanceWithId(name, id, passing == 1)
227+
}
228+
}

example/main.go

Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
package main
2+
3+
import (
4+
"fmt"
5+
"goconsul"
6+
7+
"github.com/hashicorp/consul/api"
8+
)
9+
10+
func testKV(client *goconsul.Client) {
11+
12+
cmd := goconsul.NewKVCmd(client, "")
13+
if err := cmd.SetStr("key", "value"); err != nil {
14+
panic(err)
15+
}
16+
17+
var val string
18+
val, err := cmd.GetStr("key")
19+
if err != nil {
20+
panic(err)
21+
}
22+
23+
fmt.Println("get val: ", val)
24+
25+
if err := cmd.Delete("key"); err != nil {
26+
panic(err)
27+
}
28+
}
29+
30+
func testDiscovery(client *goconsul.Client) {
31+
ins := goconsul.NewInstance("test-service",
32+
"127.0.0.1",
33+
80,
34+
nil,
35+
nil,
36+
"instance-1",
37+
nil,
38+
nil,
39+
client,
40+
"test",
41+
)
42+
ins.Check = &goconsul.ServiceCheck{
43+
AgentServiceCheck: api.AgentServiceCheck{
44+
HTTP: "http://",
45+
Interval: "10s",
46+
Timeout: "5s",
47+
},
48+
}
49+
50+
if err := ins.Register(); err != nil {
51+
panic(err)
52+
}
53+
54+
insArray, err := client.DiscoverInstancesWithName("test-service", 1)
55+
if err != nil {
56+
panic(err)
57+
}
58+
59+
fmt.Println("discover services:", *insArray[0])
60+
61+
ins.Deregister()
62+
}
63+
64+
func main() {
65+
client := &goconsul.Client{}
66+
if err := client.Connect("127.0.0.1", 8500, ""); err != nil {
67+
panic(err)
68+
}
69+
70+
testKV(client)
71+
testDiscovery(client)
72+
}

go.mod

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,31 @@
1+
module goconsul
2+
3+
go 1.17
4+
5+
require (
6+
github.com/gogf/gf v1.16.6
7+
github.com/hashicorp/consul/api v1.12.0
8+
)
9+
10+
require (
11+
github.com/BurntSushi/toml v0.3.1 // indirect
12+
github.com/armon/go-metrics v0.0.0-20180917152333-f0300d1749da // indirect
13+
github.com/clbanning/mxj v1.8.5-0.20200714211355-ff02cfb8ea28 // indirect
14+
github.com/fatih/color v1.12.0 // indirect
15+
github.com/fsnotify/fsnotify v1.4.9 // indirect
16+
github.com/hashicorp/go-cleanhttp v0.5.1 // indirect
17+
github.com/hashicorp/go-hclog v0.12.0 // indirect
18+
github.com/hashicorp/go-immutable-radix v1.0.0 // indirect
19+
github.com/hashicorp/go-rootcerts v1.0.2 // indirect
20+
github.com/hashicorp/golang-lru v0.5.0 // indirect
21+
github.com/hashicorp/serf v0.9.6 // indirect
22+
github.com/mattn/go-colorable v0.1.8 // indirect
23+
github.com/mattn/go-isatty v0.0.12 // indirect
24+
github.com/mitchellh/go-homedir v1.1.0 // indirect
25+
github.com/mitchellh/mapstructure v1.1.2 // indirect
26+
go.opentelemetry.io/otel v1.0.0-RC2 // indirect
27+
go.opentelemetry.io/otel/trace v1.0.0-RC2 // indirect
28+
golang.org/x/sys v0.0.0-20210423082822-04245dca01da // indirect
29+
golang.org/x/text v0.3.6 // indirect
30+
gopkg.in/yaml.v3 v3.0.0-20210107192922-496545a6307b // indirect
31+
)

0 commit comments

Comments
 (0)