前言
使用过springcloud全家桶朋友,应该知道springcloud涉及的组件很多,为了让开发者快速了解项目引入了springcloud哪些组件,springcloud引入了HasFeatures,配合Actuator,可以让开发者感知到项目引入的组件功能类型、名称、版本以及对应的开发商。今天我们就利用这个特性,自己实现一把
示例
**注:**示例模拟短信发送的例子
1、项目中pom引入spring-cloud-common gav
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-commons</artifactId>
<version>${spring-cloud-commons.version}</version>
</dependency>
2、定义短信接口以及实现类
public interface SmsService {
void send(String phone, String content);
}
public class AliyunSmsService implements SmsService {
@Override
public void send(String phone, String content) {
System.out.printf("send to %s content %s used aliyun sms%n", phone, content);
}
}
3、定义HasFeatures
@Configuration
public class SmsAutoConfiguration {
@Bean
public HasFeatures smsFeatures(){
HasFeatures features = HasFeatures.abstractFeatures(SmsService.class);
features.getNamedFeatures().add(new NamedFeature("sms auto configuration",SmsAutoConfiguration.class ));
return features;
}
}
注: HasFeatures提供2种功能特性。一种是抽象功能,它主要是通过接口或者抽象类去spring上下文,查询具体实现。另外一种是命名功能,该功能不需要实现特定的接口或者抽象类,仅需提供一个name名称和spring bean类型
4、访问/actuator/features,查看相应的功能特性
注: 这边有个细节点,就是需要开启/actuator/features端点。这边为了演示方便,就把所有/actuator端点全部开启
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: always
通过http请求访问/actuator/features
@Autowired
private InetUtils inetUtils;
@EventListener
public void listener(WebServerInitializedEvent webServerInitializedEvent){
int port = webServerInitializedEvent.getWebServer().getPort();
String ip = inetUtils.findFirstNonLoopbackHostInfo().getIpAddress();
String featuresUrl = "http://" + ip + ":" + port + "/actuator/features";
String result = new RestTemplate().getForObject(featuresUrl, String.class);
PrintUtils.print(result);
}
查看控制台
这边发现version和vendor都为空,是因为version和vendor是META-INF/MANIFEST.MF文件内容。而该文件在我们打成jar时,会自动生成。因此我们可以打成jar再访问。这里有个小细节就是vendor的获取,需在pom文件配置organization标签,才能读取到。示例如下
<organization>
<name>lyb-geek</name>
<url>https://github.com/lyb-geek</url>
</organization>
我们将项目打成jar再访问下
可以发现version和vendor都有值了
HasFeatures的实现原理
HasFeatures是spring cloud提供的一种机制。各个功能组件仅需利用HasFeatures将功能组件的核心类封装起来,并注入到spring容器,spring cloud就会从spring容器中获取所有的HasFeatures类并传递到FeaturesEndpoint,调用"/actuator/features"时,便转成Features对象返回注册的功能特性
总结
HasFeatures在简单的项目中,可能用处不大,但是在涉及到很多功能组件时,可以利用HasFeatures机制,让我们快速了解项目引入的功能组件,便于我们快速熟悉项目
前端的世界总是在不断变化,作为开发者,我们需要保持好奇心和学习热情,不断探索新的技术,只有这样,我们才能在这个快速发展的时代中立于不败之地。低代码也是一个值得我们深入探索的领域,让我们拭目以待,它将给前端世界带来怎样的变革。
介绍一款程序员都应该知道的软件JNPF快速开发平台,很多人都尝试用过它,它是功能的集大成者,任何信息化系统都可以基于它开发出来。
JNPF可以实现应用从创建、配置、开发、测试到发布、运维、升级等完整生命周期的管理。减少了传统应用程序的代码编写量,通过图形化、可视化的界面,以拖放组件的方式,即可快速生成应用程序的产品,大幅降低了开发企业管理类软件的难度。
希望这篇文章对你有所帮助~