main.cpp 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4. #include "consul.h"
  5. /*
  6. * @介绍:consul服务注册与发现示例程序
  7. *
  8. */
  9. int main(int argc, char* argv[]) {
  10. if (argc < 3) {
  11. printf("Usage: consul_cli subcmd ServiceName [ServiceAddress ServicePort] [NodeIP NodePort]\n");
  12. printf("subcmd=[register,deregister,discover]\n");
  13. return -10;
  14. }
  15. const char* subcmd = argv[1];
  16. const char* ServiceName = argv[2];
  17. const char* ServiceAddress = "127.0.0.1";
  18. int ServicePort = 0;
  19. const char* NodeIP = "127.0.0.1";
  20. int NodePort = 8500;
  21. if (argc > 3) {
  22. ServiceAddress = argv[3];
  23. }
  24. if (argc > 4) {
  25. ServicePort = atoi(argv[4]);
  26. }
  27. if (argc > 5) {
  28. NodeIP = argv[5];
  29. }
  30. if (argc > 6) {
  31. NodePort = atoi(argv[6]);
  32. }
  33. consul_node_t node;
  34. strncpy(node.ip, NodeIP, sizeof(node.ip));
  35. node.port = NodePort;
  36. consul_service_t service;
  37. strncpy(service.name, ServiceName, sizeof(service.name));
  38. strncpy(service.ip, ServiceAddress, sizeof(service.ip));
  39. service.port = ServicePort;
  40. consul_health_t health;
  41. if (strcmp(subcmd, "register") == 0) {
  42. // 注册服务
  43. int ret = register_service(&node, &service, &health);
  44. printf("register_service retval=%d\n", ret);
  45. goto discover;
  46. }
  47. else if (strcmp(subcmd, "deregister") == 0) {
  48. // 注销服务
  49. int ret = deregister_service(&node, &service);
  50. printf("deregister_service retval=%d\n", ret);
  51. goto discover;
  52. }
  53. else if (strcmp(subcmd, "discover") == 0) {
  54. discover:
  55. // 发现服务
  56. std::vector<consul_service_t> services;
  57. discover_services(&node, ServiceName, services);
  58. for (auto& service : services) {
  59. printf("name=%s ip=%s port=%d\n", service.name, service.ip, service.port);
  60. }
  61. }
  62. else {
  63. printf("subcmd error!\n");
  64. return -20;
  65. }
  66. return 0;
  67. }