当前位置:网站首页>SPI service discovery mechanism
SPI service discovery mechanism
2022-07-19 11:17:00 【TaoYuanming of the Western Wei Dynasty】

author : TaoYuanming of the Western Wei Dynasty
Blog : https://blog.springlearn.cn/
TaoYuanming of the Western Wei Dynasty
Don't laugh at the young Jianghu dream , Who doesn't dream of Jianghu
One 、 What is? SPI
SPI , Its full name is Service Provider Interface, Is a service discovery mechanism .JDK Medium SPI It is through ClassPath The next path META-INF/services Folder lookup extension file , Automatically load the classes defined in the file .
In Xiaobian's understanding , I think it is a kind of thought . That is, find the interface of the service , Famous for its name : Service discovery mechanism thought . Many open source frameworks have borrowed this idea , such as dubbo、jdbc.
Two 、SPI stay JDK How to use
SPI stay JDK in , We can use ServiceLoader Class to use .
1. The premise to prepare
public interface SpiService {
String say();
}
Two implementation classes
public class ASpiServiceImpl implements SpiService {
static {
System.out.println("static init a");
}
{
System.out.println("init a");
}
@Override
public String say() {
return "A";
}
}
public class BSpiServiceImpl implements SpiService {
static {
System.out.println("static init b");
}
{
System.out.println("init b");
}
@Override
public String say() {
return "B";
}
}
2. To configure
stay resources Created in META-INF/services Catalog

│ └── resources
│ └── META-INF
│ └── services
│ └── com.github.easylog.spi.SpiService
com.github.easylog.spi.SpiService The contents of the document
com.github.easylog.spi.impl.ASpiServiceImpl
com.github.easylog.spi.impl.BSpiServiceImpl
3. Use
adopt ServiceLoader Class we can load all configured implementation classes , And deal with the implementation class . It should be noted that , see 4 Use caution .

public class SpiTester {
public static void main(String[] args) {
ServiceLoader<SpiService> spiServices = ServiceLoader.load(SpiService.class);
Iterator<SpiService> iterator = spiServices.iterator();
while (iterator.hasNext()) {
SpiService next = iterator.next();
System.out.println(next.say());
}
}
}
4. Use caution
You can take a look at the two implementation classes previously declared in the Xiaobian , Both static and non static code blocks are defined . Normally, when this bytecode is loaded , Will execute the content in the static code block , But it is not executed in actual operation , There's a reason .

You can see that the second parameter is false. That is, no initialization is performed during loading .
3、 ... and 、Dubbo The idea of service discovery
The characteristic of service discovery is : Code is not hard coded , But configurable . Just put the implementation classes to be supported under the specified configuration file , It will be loaded automatically . Then the code only cares about use . We can use this idea to realize , Extensions to the framework , For example, as mentioned above .Dubbo Make use of SPI The mind of , Load user-defined filters .
This idea is especially suitable for service expansion . This idea is now used in most open source frameworks .
1. Define filters

@Activate(group = { Constants.PROVIDER })
public class ProviderHelloFilter implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
System.out.pringln("hello ok!");
return invoker.invoke(invocation);
}
}
2. Add configuration file
META-INF/dubbo/Interal/com.alibaba.dubbo.rpc.Filter
Default supported filters

utilize SPI principle , We customize a filter

3. Use
Actually API Follow JDK Use in ServiceLoader The way , Very similar . The only difference is Dubbo Is used in ExtensionLoader. because dubbo Some special enhancements have been made in . For example, you can customize an alias in the configuration file key. Pictured above hello Namely key. adopt getExtension(“hello”) You can get the specified implementation class .

public class SpiTester {
public static void main(String[] args) throws Exception{
ExtensionLoader<Filter> filterExtensionLoader = ExtensionLoader.getExtensionLoader(Filter.class);
Set<String> supportedExtensions = filterExtensionLoader.getSupportedExtensions();
System.out.println(supportedExtensions);
//[accesslog, activelimit, cache...]
Filter hello = filterExtensionLoader.getExtension("hello");
//[email protected]
System.out.println(hello);
}
}
** So have you learned this thought ? **

Finally, please pay attention , Request subscription , Thanks for reading !
边栏推荐
- Nombre d'entrées nombre d'entrées numériques pures limite de longueur maximale
- 要想组建敏捷团队,这些方法不可少
- web安全入门-部署Snort开源IDS/IPS系统
- MySQL autoincrement ID, UUID and snowflake ID
- 2022/7/15
- To get to the bottom: Principle Analysis of Objective-C correlation attribute
- 性能优化之@Contended减少伪共享
- Integrated network architecture and network slicing technology of air, earth and sea
- Unity high version returned low version error
- Environment variable configuration of win10
猜你喜欢

Category imbalance in classification tasks

MySQL autoincrement ID, UUID and snowflake ID

Tier defect detection using full revolutionary network

如何在 RHEL 9 中更改和重置忘记的root密码

Explanation of tree chain dissection idea + acwing 2568 Tree chain dissection (DFS sequence + mountain climbing method + segment tree)

Getting started with web security - deploy snort open source ids/ips system

今日睡眠质量记录79分
![[leetcode weekly replay] 302 weekly 20220717](/img/38/446db9b4755f8b30f9887faede7e95.png)
[leetcode weekly replay] 302 weekly 20220717

Tencent cloud server uses image to deploy WordPress personal website!

Mpu9250 ky9250 attitude, angle module and mpu9250 MPL DMA comparison
随机推荐
如何在 RHEL 9 中更改和重置忘记的root密码
The concept of data guard broker and the configuration process of data guard broker
常见分布式锁介绍
LeetCode 2325. Decrypt message (map)
Maximal semi connected subgraph (tarjan contraction + topological ordering + DP longest chain)
LeetCode 745. 前缀和后缀搜索
Whether pjudge 21652-[pr 4] has nine [digit DP]
Summary of port mirroring methods with VDS or NSX under vSphere
Rotation in unity3d
Detailed explanation of multiple linear regression
论文笔记:Mind the Gap An Experimental Evaluation of Imputation ofMissing Values Techniques in TimeSeries
Integrated network architecture and network slicing technology of air, earth and sea
设置cmd命令提示符窗口的界面语言为英文
LeetCode 2315. Statistical asterisk (string)
How much money can you make by inventing flash memory? This is a Japanese dog blood story
Second classification learning is extended to multi classification learning
树链剖分思想讲解 + AcWing 2568. 树链剖分(dfs序 + 爬山法 + 线段树)
Introduction to virtualization troubleshooting
数据库锁的介绍与InnoDB共享,排他锁
每日刷题记录 (二十六)