자바 SPI 와 cooma(dubbo 마이크로 용기 개량 품)--1

자바 SPI 와 cooma(dubbo 마이크로 용기 개량 품)--1
자바 의 spi(Service provider interface)는 주로 프레임 워 크 의 확장 과 구성 요소 교 체 를 위해 만들어 진 것 으로 현재 유행 하 는 IOC 개념 과 유사 합 니 다.
    자바 spi 의 실현:
java. util.ServiceLoader< S>
A simple service-provider loading facility.
A service is a well-known set of interfaces and (usually abstract) classes. Aservice provider is a specific implementation of a service. The classes in a provider typically implement the interfaces and subclass the classes defined in the service itself. Service providers can be installed in an implementation of the Java platform in the form of extensions, that is, jar files placed into any of the usual extension directories. Providers can also be made available by adding them to the application's class path or by some other platform-specific means.
For the purpose of loading, a service is represented by a single type, that is, a single interface or abstract class. (A concrete class can be used, but this is not recommended.) A provider of a given service contains one or more concrete classes that extend this service type with data and code specific to the provider. The provider class is typically not the entire provider itself but rather a proxy which contains enough information to decide whether the provider is able to satisfy a particular request together with code that can create the actual provider on demand. The details of provider classes tend to be highly service-specific; no single class or interface could possibly unify them, so no such type is defined here. The only requirement enforced by this facility is that provider classes must have a zero-argument constructor so that they can be instantiated during loading.
A service provider is identified by placing aprovider-configuration file in the resource directory META-INF/services. The file's name is the fully-qualifiedbinary name of the service's type. The file contains a list of fully-qualified binary names of concrete provider classes, one per line. Space and tab characters surrounding each name, as well as blank lines, are ignored. The comment character is '#' ('\u0023', NUMBER SIGN); on each line all characters following the first comment character are ignored. The file must be encoded in UTF-8.
If a particular concrete provider class is named in more than one configuration file, or is named in the same configuration file more than once, then the duplicates are ignored. The configuration file naming a particular provider need not be in the same jar file or other distribution unit as the provider itself. The provider must be accessible from the same class loader that was initially queried to locate the configuration file; note that this is not necessarily the class loader from which the file was actually loaded.
Providers are located and instantiated lazily, that is, on demand. A service loader maintains a cache of the providers that have been loaded so far. Each invocation of the iterator method returns an iterator that first yields all of the elements of the cache, in instantiation order, and then lazily locates and instantiates any remaining providers, adding each one to the cache in turn. The cache can be cleared via the reload method.
Service loaders always execute in the security context of the caller. Trusted system code should typically invoke the methods in this class, and the methods of the iterators which they return, from within a privileged security context.
Instances of this class are not safe for use by multiple concurrent threads.
Unless otherwise specified, passing a null argument to any method in this class will cause a NullPointerException to be thrown.
Example Suppose we have a service typecom.example.CodecSet which is intended to represent sets of encoder/decoder pairs for some protocol. In this case it is an abstract class with two abstract methods:
 public abstract Encoder getEncoder(String encodingName);
 public abstract Decoder getDecoder(String encodingName);

Each method returns an appropriate object or
null if the provider does not support the given encoding. Typical providers support more than one encoding.
If com.example.impl.StandardCodecs is an implementation of the CodecSet service then its jar file also contains a file named
 META-INF/services/com.example.CodecSet

This file contains the single line:
 com.example.impl.StandardCodecs    # Standard codecs

The CodecSet class creates and saves a single service instance at initialization:
 private static ServiceLoader codecSetLoader
     = ServiceLoader.load(CodecSet.class);

To locate an encoder for a given encoding name it defines a static factory method which iterates through the known and available providers, returning only when it has located a suitable encoder or has run out of providers.
 public static Encoder getEncoder(String encodingName) {
     for (CodecSet cp : codecSetLoader) {
         Encoder enc = cp.getEncoder(encodingName);
         if (enc != null)
             return enc;
     }
     return null;
 }

A getDecoder method is defined similarly.
Usage Note If the class path of a class loader that is used for provider loading includes remote network URLs then those URLs will be dereferenced in the process of searching for provider-configuration files.
This activity is normal, although it may cause puzzling entries to be created in web-server logs. If a web server is not configured correctly, however, then this activity may cause the provider-loading algorithm to fail spuriously.
A web server should return an HTTP 404 (Not Found) response when a requested resource does not exist. Sometimes, however, web servers are erroneously configured to return an HTTP 200 (OK) response along with a helpful HTML error page in such cases. This will cause a ServiceConfigurationError to be thrown when this class attempts to parse the HTML page as a provider-configuration file. The best solution to this problem is to fix the misconfigured web server to return the correct response code (HTTP 404) along with the HTML error page.
Type Parameters:
The type of the service to be loaded by this loader
Since:
1.6
Author:
Mark Reinhold
  구현 문서 에 따라 demo 를 썼 습 니 다.
인터페이스:
package com.doctor.spi.service;

/**
 * @author sdcuike
 *
 *         Created on 2016 7 24    10:21:37
 */
public interface Car {
    void run();
}

두 가지 실현:
package com.doctor.spi.service.impl;

import com.doctor.spi.service.Car;

/**
 * @author sdcuike
 *
 *         Created on 2016 7 24    10:22:28
 */
public class RacingCar implements Car {

    @Override
    public void run() {
        System.out.println("RacingCar Running...");
    }

}
package com.doctor.spi.service.impl;

import com.doctor.spi.service.Car;

/**
 * 
 * @author sdcuike
 *
 *         Created on 2016 7 24    10:23:11
 */
public class SportCar implements Car {

    @Override
    public void run() {
        System.out.println("SportCar Running...");
    }
}

요구 에 따라 파일:META-INF\services\com.doctor.spi.service.car 에는 다음 과 같은 내용 이 있 습 니 다.
com.doctor.spi.service.impl.RacingCar
com.doctor.spi.service.impl.SportCar

즉,인터페이스의 실현 류 정보.
main 실행 방법:
package com.doctor.spi;

import java.util.ServiceLoader;

import com.doctor.spi.service.Car;

/**
 * @author sdcuike
 *
 *         Created on 2016 7 24    10:20:45
 */
public class SPIDemo {

    public static void main(String[] args) {
        ServiceLoader serviceLoader = ServiceLoader.load(Car.class);

        serviceLoader.forEach(SPIDemo::runCar);
    }

    static void runCar(Car car) {
        System.out.println(car);
        car.run();
    }
}

실행 결과:
com.doctor.spi.service.impl.RacingCar@1fb3ebeb
RacingCar Running...
com.doctor.spi.service.impl.SportCar@548c4f57
SportCar Running...

약속대로 설정 하면 인터페이스의 실현 클래스 를 목적 파일 에 설정 하면'주입'할 수 있 습 니 다.
실현 류 보기:189 줄:
private static final String PREFIX = "META-INF/services/";

읽 은 프로필 은 이 디 렉 터 리 에 있어 야 합 니 다.Maven 과 철학 처럼 설정 보다 약속 이 많 습 니 다.
클래스 의 실례 화 실현:370 줄 과 380 줄:
                c = Class.forName(cn, false, loader);
                S p = service.cast(c.newInstance());
                providers.put(cn, p);

? java. lang. Class.newInstance() throws InstantiationException, IllegalAccessException 인터페이스 구현 클래스 에 기본 구조 함수(즉 매개 변수 가 없 는 구조 함수)가 있어 야 오류 가 발생 하지 않 습 니 다.
자바 는 좋 은 IOC 구현 원형 을 주 었 습 니 다.프레임 워 크 확장 과 구성 요소 교체 가 상대 적 으로 쉬 우 나 자바 자체 spi 구현
그렇게 유연 하지 않 습 니 다.예 를 들 어 spring ioc 의 쉬 운 의존 주입 은 유형 이나 by name 에 따라 주입 할 수 있 습 니 다.spring ioc 의 개념 에 더욱 가 까 워 지기 위해 dubbo 는 자바 spi 의 실현 체제 원형 에서 dubbo 자체 만 의 확장 기능 수 요 를 결합 하여 자신의 마이크로 용 기 를 실현 합 니 다.
그러나 dubbo 의 마이크로 용 기 는 RPC 와 같은 기능 이외 의 많은 것들 을 결합 시 켰 다.그래서 아 리 계 에 하나 생 겼 어 요.
https://github.com/alibaba/cooma
계속
참고:
https://en.wikipedia.org/wiki/Service_provider_interface
https://github.com/alibaba/cooma
https://en.wikipedia.org/wiki/Service_provider_interface

좋은 웹페이지 즐겨찾기