JAVA SPI實現機制與原理分析

前言

       最近要做業務接口,需要在多個模塊根據需要調用不同的實現,立馬就想到了SPI機制,但是Java自帶的SPI又不能滿足要求,使用dubbo的SPI就能達到目的,但這樣就需要強依賴dubbo的jar,就想自己定製一個簡單的實現,首先看看java的SPI如何實現。

1. demo

public interface SPInterface {

    void hello();
}

public class Hello1 implements SPInterface {
    public void hello() {
        System.out.println("111111111111111111111111111");
    }
}

public class Hello2 implements SPInterface {
    public void hello() {
        System.out.println("222222222222222222222222222");
    }
}

main方法

import java.util.ServiceLoader;

public class MainClass {
    public static void main(String[] args) {
        ServiceLoader<SPInterface> loader = ServiceLoader.load(SPInterface.class, Thread.currentThread().getContextClassLoader());
        for (SPInterface spInterface : loader) {
            spInterface.hello();
        }
    }
}

指定class loader很重要,否則動態加載的jar或者class就會不能使用SPI。

需要配置在classpath下創建

META-INF/services/${package.interfaceName}

文件,etg

運行main方法

 說明SPI已生效,這種方式開發非常常見,典型的是數據庫驅動

比如MySQL

package com.mysql.cj.jdbc;

import java.sql.SQLException;

/**
 * The Java SQL framework allows for multiple database drivers. Each driver should supply a class that implements the Driver interface
 * 
 * <p>
 * The DriverManager will try to load as many drivers as it can find and then for any given connection request, it will ask each driver in turn to try to
 * connect to the target URL.
 * 
 * <p>
 * It is strongly recommended that each Driver class should be small and standalone so that the Driver class can be loaded and queried without bringing in vast
 * quantities of supporting code.
 * 
 * <p>
 * When a Driver class is loaded, it should create an instance of itself and register it with the DriverManager. This means that a user can load and register a
 * driver by doing Class.forName("foo.bah.Driver")
 */
public class Driver extends NonRegisteringDriver implements java.sql.Driver {

2. 原理分析

本質就是通過文本文件加載class實現面向接口編程,核心是ServiceLoader

 我們反編譯Main方法,可以看到for each是用迭代器實現的。

//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by Fernflower decompiler)
//

package com.feng.spi.demo;

import com.feng.spi.demo.hello.SPInterface;
import java.util.Iterator;
import java.util.ServiceLoader;

public class MainClass {
    public MainClass() {
    }

    public static void main(String[] args) {
        ServiceLoader<SPInterface> loader = ServiceLoader.load(SPInterface.class, Thread.currentThread().getContextClassLoader());
        Iterator var2 = loader.iterator();

        while(var2.hasNext()) {
            SPInterface spInterface = (SPInterface)var2.next();
            spInterface.hello();
        }

    }
}

而ServiceLoader實現了迭代接口

public final class ServiceLoader<S>
    implements Iterable<S>

    //前綴地址
    private static final String PREFIX = "META-INF/services/";

    // The class or interface representing the service being loaded
    //SPI的接口類
    private final Class<S> service;

    // The class loader used to locate, load, and instantiate providers
    //類加載器
    private final ClassLoader loader;

    // The access control context taken when the ServiceLoader is created
    //訪問控制上下文
    private final AccessControlContext acc;

    // Cached providers, in instantiation order
    //緩存SPI的實現bean,key是完整類名
    private LinkedHashMap<String,S> providers = new LinkedHashMap<>();

    // The current lazy-lookup iterator
    //懶迭代器,ServiceLoader就是使用它實現懶加載的,需要的時候加載,配合緩存提高效率
    private LazyIterator lookupIterator;

看看幾個屬性,已經說的很明顯了。看看load方法

    public static <S> ServiceLoader<S> load(Class<S> service,
                                            ClassLoader loader)
    {
        //每次load,創建一個對象
        return new ServiceLoader<>(service, loader);
    }

    public static <S> ServiceLoader<S> load(Class<S> service) {
        ClassLoader cl = Thread.currentThread().getContextClassLoader();
        return ServiceLoader.load(service, cl);
    }

就是new ServiceLoader對象,參數是接口class與classloader

    public void reload() {
        //清理緩存
        providers.clear();
        //初始化懶迭代器
        lookupIterator = new LazyIterator(service, loader);
    }

    private ServiceLoader(Class<S> svc, ClassLoader cl) {
        //not null
        service = Objects.requireNonNull(svc, "Service interface cannot be null");
        //找到class loader
        loader = (cl == null) ? ClassLoader.getSystemClassLoader() : cl;
        //訪問控制器上下文
        acc = (System.getSecurityManager() != null) ? AccessController.getContext() : null;
        reload();
    }

ServiceLoader實現了迭代接口,下面看看

iterator()

方法

    public Iterator<S> iterator() {
        return new Iterator<S>() {

            Iterator<Map.Entry<String,S>> knownProviders
                = providers.entrySet().iterator();

            public boolean hasNext() {
                //緩存hasNext
                if (knownProviders.hasNext())
                    return true;
                //緩存沒有,使用懶迭代器
                return lookupIterator.hasNext();
            }

            public S next() {
                //同理,緩存獲取
                if (knownProviders.hasNext())
                    return knownProviders.next().getValue();
                //然後懶迭代器
                return lookupIterator.next();
            }

            //不能刪除
            public void remove() {
                throw new UnsupportedOperationException();
            }

        };
    }

原理都是通過懶迭代器實現的,通過上面的代碼reload裏面初始化的

    public void reload() {
        providers.clear();
        lookupIterator = new LazyIterator(service, loader);
    }

追蹤LazyIterator

private class LazyIterator
        implements Iterator<S>
    {
        //接口類
        Class<S> service;
        //類加載器
        ClassLoader loader;
        //讀取文件URL
        Enumeration<URL> configs = null;
        //緩存文件的實現類
        Iterator<String> pending = null;
        //迭代的緩存next方法的實現類,加快迭代
        String nextName = null;

        private LazyIterator(Class<S> service, ClassLoader loader) {
            this.service = service;
            this.loader = loader;
        }

        private boolean hasNextService() {
            //緩存了,所以直接true
            if (nextName != null) {
                return true;
            }
            if (configs == null) {
                try {
                    //文件的路徑,前綴+接口完整名稱
                    String fullName = PREFIX + service.getName();
                    //載入URL,傳入classloader,否則使用系統的
                    if (loader == null)
                        configs = ClassLoader.getSystemResources(fullName);
                    else
                        configs = loader.getResources(fullName);
                } catch (IOException x) {
                    fail(service, "Error locating configuration files", x);
                }
            }
            //尚未緩存實現類名稱
            while ((pending == null) || !pending.hasNext()) {
                //判斷是否讀取到文件
                if (!configs.hasMoreElements()) {
                    return false;
                }
                //緩存文件讀取的實現類名稱
                pending = parse(service, configs.nextElement());
            }
            //緩存next方法迭代的實現類,提高效率
            nextName = pending.next();
            return true;
        }

        private S nextService() {
            //校驗
            if (!hasNextService())
                throw new NoSuchElementException();
            //使用緩存
            String cn = nextName;
            //清理緩存next的實現類名稱
            nextName = null;
            Class<?> c = null;
            try {
                //創建類
                c = Class.forName(cn, false, loader);
            } catch (ClassNotFoundException x) {
                fail(service,
                     "Provider " + cn + " not found");
            }
            //如果不是接口的實現
            if (!service.isAssignableFrom(c)) {
                fail(service,
                     "Provider " + cn  + " not a subtype");
            }
            try {
                //創建實現類的實例,轉換接口類型
                S p = service.cast(c.newInstance());
                //本地緩存,使用完整類名做key,緩存實例
                providers.put(cn, p);
                return p;
            } catch (Throwable x) {
                fail(service,
                     "Provider " + cn + " could not be instantiated",
                     x);
            }
            throw new Error();          // This cannot happen
        }

        //hasNext,不解釋
        public boolean hasNext() {
            //訪問控制上下文,默認null;通過System.setSecurityManager(final SecurityManager s)設置
            if (acc == null) {
                return hasNextService();
            } else {
                PrivilegedAction<Boolean> action = new PrivilegedAction<Boolean>() {
                    public Boolean run() { return hasNextService(); }
                };
                return AccessController.doPrivileged(action, acc);
            }
        }

        //迭代器next
        public S next() {
            //訪問控制上下文,默認是沒有控制的
            if (acc == null) {
                return nextService();
            } else {
                PrivilegedAction<S> action = new PrivilegedAction<S>() {
                    public S run() { return nextService(); }
                };
                return AccessController.doPrivileged(action, acc);
            }
        }

        //不能刪除
        public void remove() {
            throw new UnsupportedOperationException();
        }

    }

cast,判斷後強轉

    public T cast(Object obj) {
        if (obj != null && !isInstance(obj))
            throw new ClassCastException(cannotCastMsg(obj));
        return (T) obj;
    }

下面看看解析文件方法

parse(service, configs.nextElement());

    private Iterator<String> parse(Class<?> service, URL u)
        throws ServiceConfigurationError
    {
        InputStream in = null;
        BufferedReader r = null;
        //這個就是緩存的實現類完整名稱列表
        ArrayList<String> names = new ArrayList<>();
        try {
            //讀取幷包裝流
            in = u.openStream();
            r = new BufferedReader(new InputStreamReader(in, "utf-8"));
            int lc = 1;
            while ((lc = parseLine(service, u, r, lc, names)) >= 0);
        } catch (IOException x) {
            fail(service, "Error reading configuration file", x);
        } finally {
            try {
                if (r != null) r.close();
                if (in != null) in.close();
            } catch (IOException y) {
                fail(service, "Error closing configuration file", y);
            }
        }
        return names.iterator();
    }

核心調用

parseLine(service, u, r, lc, names)

    private int parseLine(Class<?> service, URL u, BufferedReader r, int lc,
                          List<String> names)
        throws IOException, ServiceConfigurationError
    {
        //按行讀取
        String ln = r.readLine();
        if (ln == null) {
            return -1;
        }
        //去#
        int ci = ln.indexOf('#');
        if (ci >= 0) ln = ln.substring(0, ci);
        ln = ln.trim();
        int n = ln.length();
        if (n != 0) {
            if ((ln.indexOf(' ') >= 0) || (ln.indexOf('\t') >= 0))
                fail(service, u, lc, "Illegal configuration-file syntax");
            int cp = ln.codePointAt(0);
            //鑑定是否Java類名
            if (!Character.isJavaIdentifierStart(cp))
                fail(service, u, lc, "Illegal provider-class name: " + ln);
            for (int i = Character.charCount(cp); i < n; i += Character.charCount(cp)) {
                cp = ln.codePointAt(i);
                if (!Character.isJavaIdentifierPart(cp) && (cp != '.'))
                    fail(service, u, lc, "Illegal provider-class name: " + ln);
            }
            //緩存沒有,加入緩存
            if (!providers.containsKey(ln) && !names.contains(ln))
                names.add(ln);
        }
        return lc + 1;
    }

總結

       Java的SPI非常簡單,實現類解耦的思想,讓接口與實現分離,通過協議(配置文件)來達到調用的目的。缺陷也很明顯

1. 不能按需加載實現類,必須迭代

2. 獲取提供的實現,不能安裝參數獲取,還是要迭代

3. 沒有線程安全的考慮

ServiceLoader每次load會新創建一個對象,當多個線程對迭代時,裏面使用的緩存都是非線程安全的ArrayList與LinkedHashMap,不保證原子性。

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章