类DirectAddressNameResolver

在类 AbstractManagedChannelImplBuilder 中有一个内部类,DirectAddressNameResolverFactory,这里实现了一个 NameResolver ,用于处理 DirectAddress。

Factory的代码

  1. private static final String DIRECT_ADDRESS_SCHEME = "directaddress";
  2. private static class DirectAddressNameResolverFactory extends NameResolver.Factory {
  3. final SocketAddress address;
  4. final String authority;
  5. // 构造函数中直接提供 address 和 authority
  6. DirectAddressNameResolverFactory(SocketAddress address, String authority) {
  7. this.address = address;
  8. this.authority = authority;
  9. }
  10. @Override
  11. public NameResolver newNameResolver(URI notUsedUri, Attributes params) {
  12. return new NameResolver() {
  13. ......// 细节后面看
  14. }
  15. }
  16. @Override
  17. public String getDefaultScheme() {
  18. // 默认的scheme是固定的 "directaddress"
  19. return DIRECT_ADDRESS_SCHEME;
  20. }
  21. }

NameResolver的实现

DirectAddressNameResolverFactory的NameResolver的实现是一个内部匿名类:

  1. public NameResolver newNameResolver(URI notUsedUri, Attributes params) {
  2. return new NameResolver() {
  3. @Override
  4. public String getServiceAuthority() {
  5. // 直接返回factory中传入并保存的authority
  6. return authority;
  7. }
  8. @Override
  9. public void start(final Listener listener) {
  10. // 不用解析,直接将 factory 中传入并保存的 address 给出去
  11. listener.onAddresses(
  12. Collections.singletonList(new EquivalentAddressGroup(address)),
  13. Attributes.EMPTY);
  14. }
  15. @Override
  16. public void shutdown() {}
  17. };
  18. }

总结

这个实现够简单,不过考虑到平时也是有需要用到直接地址的。