1. package main
    2. import (
    3. "fmt"
    4. "github.com/hashicorp/consul/api"
    5. )
    6. func Register(address string, port int, name string, tags []string, id string) error {
    7. cfg := api.DefaultConfig()
    8. cfg.Address = "192.168.1.103:8500"
    9. client, err := api.NewClient(cfg)
    10. if err != nil {
    11. panic(err)
    12. }
    13. //生成对应的检查对象
    14. check := &api.AgentServiceCheck{
    15. HTTP: "http://192.168.1.102:8021/health",
    16. Timeout: "5s",
    17. Interval: "5s",
    18. DeregisterCriticalServiceAfter: "10s",
    19. }
    20. //生成注册对象
    21. registration := new(api.AgentServiceRegistration)
    22. registration.Name = name
    23. registration.ID = id
    24. registration.Port = port
    25. registration.Tags = tags
    26. registration.Address = address
    27. registration.Check = check
    28. err = client.Agent().ServiceRegister(registration)
    29. if err != nil {
    30. panic(err)
    31. }
    32. return nil
    33. }
    34. func AllServices(){
    35. cfg := api.DefaultConfig()
    36. cfg.Address = "192.168.1.103:8500"
    37. client, err := api.NewClient(cfg)
    38. if err != nil {
    39. panic(err)
    40. }
    41. data, err := client.Agent().Services()
    42. if err != nil {
    43. panic(err)
    44. }
    45. for key, _ := range data{
    46. fmt.Println(key)
    47. }
    48. }
    49. func FilterSerivice(){
    50. cfg := api.DefaultConfig()
    51. cfg.Address = "192.168.1.103:8500"
    52. client, err := api.NewClient(cfg)
    53. if err != nil {
    54. panic(err)
    55. }
    56. data, err := client.Agent().ServicesWithFilter(`Service == "user-web"`)
    57. if err != nil {
    58. panic(err)
    59. }
    60. for key, _ := range data{
    61. fmt.Println(key)
    62. }
    63. }
    64. func main(){
    65. //_ = Register("192.168.1.102", 8021, "user-web", []string{"mxshop", "bobby"}, "user-web")
    66. //AllServices()
    67. FilterSerivice()
    68. }