服务发现

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

Nacos配置:

  1. yoyogo:
  2. application:
  3. name: demo_dev
  4. metadata: "develop"
  5. cloud:
  6. discovery:
  7. cache:
  8. ttl: 30 # seconds 服务列表缓存时间 (秒)
  9. type: "etcd"
  10. metadata:
  11. address:
  12. - "localhost:32379"
  13. namespace: "public"
  14. ttl: 60
  15. auth:
  16. enable: true
  17. username: "root"
  18. password: "5z1fLbYw8A"

获取服务实例

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

  1. type UserController struct {
  2. mvc.ApiController
  3. discoveryClient serverdiscovery.IServerDiscovery
  4. }
  5. func NewUserController(sd serverdiscovery.IServerDiscovery) *UserController {
  6. return &UserController{ discoveryClient: sd}
  7. }
  8. func (controller UserController) GetSD() mvc.ApiResult {
  9. serviceList := controller.discoveryClient.GetAllInstances("demo_dev")
  10. return controller.OK(serviceList)
  11. }