聊聊如何感知项目引入哪些功能特性

2024/5/29 23:02:43

本文主要是介绍聊聊如何感知项目引入哪些功能特性,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

前言

使用过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);

    }

查看控制台
1d8bad5ee39e3bdf9fb4eaae051daeaf_1d9e18c3e11b368de7297c56340cf412.png

这边发现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再访问下
69e2b1d98de2be26ef1b16a6983fd179_fc169a222708d24bc02a180d3f6a206c.png

可以发现version和vendor都有值了

HasFeatures的实现原理

HasFeatures是spring cloud提供的一种机制。各个功能组件仅需利用HasFeatures将功能组件的核心类封装起来,并注入到spring容器,spring cloud就会从spring容器中获取所有的HasFeatures类并传递到FeaturesEndpoint,调用"/actuator/features"时,便转成Features对象返回注册的功能特性

总结

HasFeatures在简单的项目中,可能用处不大,但是在涉及到很多功能组件时,可以利用HasFeatures机制,让我们快速了解项目引入的功能组件,便于我们快速熟悉项目

demo链接

https://github.com/lyb-geek/springboot-learning/tree/master/springboot-has-features



这篇关于聊聊如何感知项目引入哪些功能特性的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程