服务发现

  1. app.NewWebHostBuilder().
  2. UseConfiguration(configuration).
  3. ConfigureServices(func(serviceCollection *dependencyinjection.ServiceCollection) {
  4. // 依赖注入 Consul 服务发现组件
  5. Consul.UseServiceDiscovery(serviceCollection)
  6. }).Build().Run()

consul配置:

  1. yoyogo:
  2. application:
  3. name: demo_dev
  4. metadata: "develop"
  5. cloud:
  6. discovery:
  7. cache:
  8. ttl: 30 # seconds 服务列表缓存时间 (秒)
  9. type: "consul"
  10. metadata:
  11. address: "localhost:8500"
  12. health_check: "/actuator/health"
  13. tags: [""]

获取服务实例

新建一个Controller,并在GetSD函数中获取demo_dev服务的所有实例

  1. type SDController struct {
  2. mvc.ApiController
  3. discoveryCache servicediscovery.Cache
  4. discoveryClient servicediscovery.IServiceDiscoveryClient
  5. }
  6. func NewSDController(sd servicediscovery.IServiceDiscoveryClient, cache servicediscovery.Cache) *SDController {
  7. return &SDController{discoveryClient: sd, discoveryCache: cache}
  8. }
  9. func (controller SDController) GetSD() mvc.ApiResult {
  10. serviceList := controller.discoveryClient.GetAllInstances("yoyogo_demo_dev")
  11. return controller.OK(serviceList)
  12. }
  13. func (controller SDController) GetServices() mvc.ApiResult {
  14. serviceList, _ := controller.discoveryClient.GetAllServices()
  15. return controller.OK(serviceList)
  16. }