consul_cli.cpp 1.8 KB

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