美文网首页
java.util.ServiceLoader加载服务实现类

java.util.ServiceLoader加载服务实现类

作者: 主君_05c4 | 来源:发表于2019-04-26 18:41 被阅读0次
    1、ServiceLoader 简介
    public final class ServiceLoader<S> extends Object implements Iterable<S>
    

    用于加载服务提供者。

    服务通常是一组接口或者抽象类,服务提供者是服务的特定实现。服务提供者中的类通常实现了接口,并子类化了在服务接口中定义的类。服务提供者以可扩展的形式安装在 Java 平台的实现中,也就是将 jar 文件放入任意常用的扩展目录中,也可通过将提供者加入应用程序类路径,或者通过其他某些特定于平台的方式使其可用。

    为了方便加载,服务一般使用单个类型表示,即单个接口或抽象类(可以使用实现类,但不建议这么做)。一个给定服务的提供者包含一个或多个实现类,这些类继承了此服务类型,具有特定于服务提供者的数据和代码。服务提供者类通常是一个代理,它包含足够的信息来决定提供者是否能满足特定请求,根据编码创建实际的服务提供者。提供者类的详细信息特定于服务;任何单个类或接口都不能统一它们,因此这里没有定义任何这种类型。此设施唯一强制要求的是,提供者类必须具有不带参数的构造方法,以便它们可以在加载中被实例化。

    通过在资源目录 META-INF/services 中放置提供者配置文件 来标识服务提供者。文件名称是服务类型的完全限定二进制名称。该文件包含一个具体提供者类的完全限定二进制名称列表,每行一个。忽略各名称周围的空格、制表符和空行。注释字符为 '#' ('\u0023', NUMBER SIGN);忽略每行第一个注释字符后面的所有字符。文件必须使用 UTF-8 编码。

    如果在多个配置文件中指定了一个特定的具体提供者类,或在同一配置文件中多次被指定,则忽略重复的指定。指定特定提供者的配置文件不必像提供者本身一样位于同一个 jar 文件或其他的分布式单元中。提供者必须可以从最初为了定位配置文件而查询的类加载器访问;注意,这不一定是实际加载文件的类加载器。

    以延迟方式查找和实例化提供者,也就是说根据需要进行。服务加载器维护到目前为止已经加载的提供者缓存。每次调用 iterator 方法返回一个迭代器,它首先按照实例化顺序生成缓存的所有元素,然后以延迟方式查找和实例化所有剩余的提供者,依次将每个提供者添加到缓存。可以通过 reload 方法清除缓存。

    服务加载器始终在调用者的安全上下文中执行。受信任的系统代码通常应当从特权安全上下文内部调用此类中的方法,以及它们返回的迭代器的方法。

    此类的实例用于多个并发线程是不安全的。

    除非另有指定,否则将 null 参数传递给此类中的任何方法都会导致抛出 NullPointerException。

    示例假定服务类型为 com.example.CodecSet,它用来表示某些协议的编解码器集合。在这种情况下,它是一个具有两种抽象方法的抽象类:

    public abstract Encoder getEncoder(String encodingName);
    public abstract Decoder getDecoder(String encodingName);
    

    每种方法都返回一个相应的对象;如果提供者不支持给定编码,则返回 null。典型的提供者支持一种以上的编码。
    如果 com.example.impl.StandardCodecs 是 CodecSet 服务的实现,则其 jar 文件还包含一个指定如下的文件:META-INF/services/com.example.CodecSet
    此文件包含一行:

    com.example.impl.StandardCodecs    # Standard codecs
    

    CodecSet 类在初始化时创建并保存一个服务实例:

    private static ServiceLoader<CodecSet> codecSetLoader = ServiceLoader.load(CodecSet.class);
    

    为了查找给定编码名称的编码器,它定义了一个静态工厂方法,该方法迭代所有已知并可用的提供者,只在找到适当的编码器或迭代完提供者时返回。

    public static Encoder getEncoder(String encodingName) {
        for (CodecSet cp :codecSetLoader) {
            Encoder enc = cp.getEncoder(encodingName);
            if (enc != null)
                return enc;
            }
            return null;
     }
    

    getDecoder 方法的定义类似。

    使用注意事项 如果用于提供者加载的类加载器的类路径包含远程网络 URL,则这些 URL 将在搜索提供者配置文件的过程中被取消引用。

    此活动是正常的,尽管它可能导致在 Web 服务器日志中创建一些令人迷惑的条目。但是,如果 Web 服务器配置不正确,那么此活动可能导致提供者加载算法意外失败。

    如果请求的资源不存在,则 Web 服务器应返回 HTTP 404 (Not Found) 响应。但有时会错误地将 Web 服务器配置为返回 HTTP 200 (OK) 响应,并伴有这种情况下的 HTML 错误帮助页面。这会导致在此类尝试将 HTML 页面作为提供者配置文件进行解析时抛出 ServiceConfigurationError。此问题的最佳解决方案是修复配置错误的 Web 服务器,以返回正确的响应代码 (HTTP 404) 以及 HTML 错误页面。

    2、ServiceLoader 示例
    服务接口
    package com.zyf.study.service;
    
    public interface FileSystem {
        public void getFileSystem();
    }
    
    服务实现1
    package com.zyf.study.service.impl;
    
    import com.zyf.study.service.FileSystem;
    
    public class LocalFileSystem implements FileSystem{
    
        @Override
        public void getFileSystem() {
            System.out.println("Local FileSystem");
        }
    }
    
    服务实现2
    package com.zyf.study.service.impl;
    
    import com.zyf.study.service.FileSystem;
    
    public class DistributedFileSystem implements FileSystem{
    
        @Override
        public void getFileSystem() {
            System.out.println("HDFS FileSystem");
        }
    }
    
    程序运行入口
    package com.zyf.study.service;
    
    import java.util.ServiceLoader;
    
    public class Main {
    
        public static void main(String[] args) {
            ServiceLoader<FileSystem> serviceLoader = ServiceLoader.load(FileSystem.class);
            serviceLoader.forEach(f -> {
                f.getFileSystem();
            });
        }
    }
    

    src/main/java下面新增目录META-INF/services,目录下新增文件com.zyf.study.service.FileSystem,文件内容如下:

    com.zyf.study.service.impl.LocalFileSystem
    com.zyf.study.service.impl.DistributedFileSystem
    

    运行程序,输出如下:

    Local FileSystem
    HDFS FileSystem
    

    :IDEA下面代码编译后,META-INF不会拷贝到target/classes下面,手动拷贝可观察到效果

    3、Hadoop文件系统实现加载

    1)先获取uri的scheme,根据scheme作为key查找缓存是否已存在对应FileSystem

      public static FileSystem get(URI uri, Configuration conf) throws IOException {
        String scheme = uri.getScheme();
        String authority = uri.getAuthority();
    
        if (scheme == null && authority == null) {     // use default FS
          return get(conf);
        }
    
        if (scheme != null && authority == null) {     // no authority
          URI defaultUri = getDefaultUri(conf);
          if (scheme.equals(defaultUri.getScheme())    // if scheme matches default
              && defaultUri.getAuthority() != null) {  // & default has authority
            return get(defaultUri, conf);              // return default
          }
        }
        String disableCacheName = String.format("fs.%s.impl.disable.cache", scheme);
        if (conf.getBoolean(disableCacheName, false)) {
          LOGGER.debug("Bypassing cache to create filesystem {}", uri);
          return createFileSystem(uri, conf);
        }
    
        return CACHE.get(uri, conf);
      }
    

    2)若已缓存对应FileSystem,则返回对应FileSystem,否则创建

      private static FileSystem createFileSystem(URI uri, Configuration conf)
          throws IOException {
        Tracer tracer = FsTracer.get(conf);
        try(TraceScope scope = tracer.newScope("FileSystem#createFileSystem")) {
          scope.addKVAnnotation("scheme", uri.getScheme());
          Class<?> clazz = getFileSystemClass(uri.getScheme(), conf);
          FileSystem fs = (FileSystem)ReflectionUtils.newInstance(clazz, conf);
          fs.initialize(uri, conf);
          return fs;
        }
      }
    

    3)根据uri scheme查找对应FileSystem实现

    public static Class<? extends FileSystem> getFileSystemClass(String scheme,
          Configuration conf) throws IOException {
        if (!FILE_SYSTEMS_LOADED) {
          loadFileSystems();
        }
    
        Class<? extends FileSystem> clazz = null;
        if (conf != null) {   
          String property = "fs." + scheme + ".impl";
          clazz = (Class<? extends FileSystem>) conf.getClass(
              property, null);
        } else {
          LOGGER.debug("No configuration: skipping check for fs.{}.impl", scheme);
        }
        if (clazz == null) {   //用户未指定自定义FileSystem实现
          LOGGER.debug("Looking in service filesystems for implementation class");
          clazz = SERVICE_FILE_SYSTEMS.get(scheme);
        } else {
          LOGGER.debug("Filesystem {} defined in configuration option", scheme);
        }
        if (clazz == null) {
          throw new UnsupportedFileSystemException("No FileSystem for scheme "
              + "\"" + scheme + "\"");
        }
        LOGGER.debug("FS for {} is {}", scheme, clazz);
        return clazz;
      }
    
    private static void loadFileSystems() {
        synchronized (FileSystem.class) {
          if (!FILE_SYSTEMS_LOADED) {
            ServiceLoader<FileSystem> serviceLoader = ServiceLoader.load(FileSystem.class);
            Iterator<FileSystem> it = serviceLoader.iterator();
            while (it.hasNext()) {
              FileSystem fs;
              try {
                fs = it.next();
                try {
                  SERVICE_FILE_SYSTEMS.put(fs.getScheme(), fs.getClass());
                } catch (Exception e) {
                }
              } catch (ServiceConfigurationError ee) {
              }
            }
            FILE_SYSTEMS_LOADED = true;
          }
        }
      }
    
    FileSystem实现配置-1.png
    FileSystem实现配置-2.png
    4)DistributedFileSystem初始化过程
      public void initialize(URI uri, Configuration conf) throws IOException {
        super.initialize(uri, conf);
        setConf(conf);
    
        String host = uri.getHost();
        if (host == null) {
          throw new IOException("Incomplete HDFS URI, no host: "+ uri);
        }
        homeDirPrefix = conf.get(
            HdfsClientConfigKeys.DFS_USER_HOME_DIR_PREFIX_KEY,
            HdfsClientConfigKeys.DFS_USER_HOME_DIR_PREFIX_DEFAULT);
    
        this.dfs = new DFSClient(uri, conf, statistics);
        this.uri = URI.create(uri.getScheme()+"://"+uri.getAuthority());
        this.workingDir = getHomeDirectory();
    
        storageStatistics = (DFSOpsCountStatistics) GlobalStorageStatistics.INSTANCE
            .put(DFSOpsCountStatistics.NAME,
              new StorageStatisticsProvider() {
                @Override
                public StorageStatistics provide() {
                  return new DFSOpsCountStatistics();
                }
              });
      }
    

    a.调用父类初始化方法;
    b.获取home目录,查找是否配置dfs.user.home.dir.prefix,若无,则默认/user
    c.创建DFSClient

    4、总结

    ServiceLoader非常方便接口的多实现类加载。

    相关文章

      网友评论

          本文标题:java.util.ServiceLoader加载服务实现类

          本文链接:https://www.haomeiwen.com/subject/ocdfnqtx.html