欢迎来到 盐城市某某装饰材料业务部
全国咨询热线:020-123456789
联系我们

地址:联系地址联系地址联系地址

电话:020-123456789

传真:020-123456789

邮箱:admin@aa.com

新闻中心
最佳实践之接口规范性检查插件
  来源:盐城市某某装饰材料业务部  更新时间:2024-05-09 06:26:43

最佳实践之接口规范性检查插件

前言

本文是最佳之接针对微服务架构下各服务之间交互接口契约定义与声明规范性在实际生产中的一个最佳实践 。在经历无数次组件间和项目间的实践扯皮 、修改再修改的口规过程中 ,总结的范性一套契约规范  ,并辅之以有效的检查自动化检测手段即本文提及的检查插件  ,通过上述规范和工具统一各项目服务间的插件接口的理解 ,降低出错返工概率 ,最佳之接最终提高开发效率 ,实践节省开发成本。口规

一 、范性Maven插件是检查什么

Maven本质上是一个插件框架,它的插件核心并不执行任何具体的构建任务 ,所有这些任务都交给插件来完成 ,最佳之接例如编译源代码是实践由maven- compiler-plugin完成的。进一步说,口规每个任务对应了一个插件目标(goal),每个插件会有一个或者多个目标 ,例如maven- compiler-plugin的compile目标用来编译位于src/main/java/目录下的主源码,testCompile目标用来编译位于src/test/java/目录下的测试源码 。

用户可以通过两种方式调用Maven插件目标 。第一种方式是将插件目标与生命周期阶段(lifecycle phase)绑定,这样用户在命令行只是输入生命周期阶段而已 ,例如Maven默认将maven-compiler-plugin的compile目标与 compile生命周期阶段绑定 ,因此命令mvn compile实际上是先定位到compile这一生命周期阶段,然后再根据绑定关系调用maven-compiler-plugin的compile目标  。第二种方式是直接在命令行指定要执行的插件目标,例如mvn archetype:generate 就表示调用maven-archetype-plugin的generate目标,这种带冒号的调用方式与生命周期无关 。
目前已经积累了大量有用的插件,参考 :

  1. http://maven.apache.org/plugins/index.html
  2. http://mojo.codehaus.org/plugins.html

二 、接口定义(Yaml)

为避免从代码生成yaml再到yaml编出的代码,两者间产生不一致和歧义,如下某Rest接口返回的对象模型  :

@Gettern@Settern@NoArgsConstructorn@ToString(callSuper = true)n@EqualsAndHashCode(callSuper = true)n@ApiModel(description = "com.xxxx.node.IpL2Node")npublic class IpL2Node extends IpNode { nn @JsonProperty("admin-ip")n @ApiModelProperty(name = "admin-ip", value = "管理地址")n private String adminIp;

团队约定在编写接口代码里 ,要求遵守下列约定:

模型实体类上必须使用注解@ApiModel,并且description设置为该实体类的全路径名

模型实体类上尽量使用注解@JsonIgnoreProperties(ignoreUnknown = true)

模型实体类上必须使用注解@JsonNaming(PropertyNamingStrategy.KebabCaseStrategy.class),同时不允许使用@JsonProperty特殊指定实体类中某字段的序列化字符串

模型实体类中每个字段必须使用注解@ApiModelProperty,并且保证name定义与序列化出的JSON字符串完全一致

Rest接口不允许返回Set集合

接口代码中不允许使用注解@JsonInclud(JsonInclud.Include.NON_NULL)

Rest接口中,不要使用JAVA层面的方法重载 ,会导致生成yaml编译代码后 ,相同方法后会自动加_0参数用于区分,影响接口准确性

通过上述约定 ,基本上保证了代码输出的yaml与再次编出的代码含义一致,但不能寄希望于开发人员主观遵守,所以需要一种自动化的手段 ,能够在出错或不满足上述约定时  ,在开发阶段即通知开发人员 ,因此我们通过开发maven插件方式完成上述功能。

三、插件实现

具体插件的实现原理也十分简单 ,即配置该插件后,在代码的编译阶段,通过扫描classPath下所有类文件,通过注解或包括Json相关过滤出潜在模型类,然后按上述规则进行校验 ,并给出报错明细信息。具体代码开发逻辑记录如下 :

该插件的工程目录:

最佳实践之接口规范性检查插件

POM依赖:

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"n xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">n <modelVersion>4.0.0</modelVersion>n <groupId>com.zte.sdn.oscp.topology</groupId>n <artifactId>oscp-restapi-check</artifactId>n <packaging>maven-plugin</packaging>n <version>1.0-SNAPSHOT</version>n <name>oscp-restapi-check Maven Mojo</name>n <url>http://maven.apache.org</url>n <dependencies>n <dependency>n <groupId>org.apache.maven</groupId>n <artifactId>maven-plugin-api</artifactId>n <version>2.0</version>n </dependency>n <dependency>n <groupId>junit</groupId>n <artifactId>junit</artifactId>n <version>3.8.1</version>n </dependency>n <dependency>n <groupId>org.apache.maven</groupId>n <artifactId>maven-core</artifactId>n <version>3.3.9</version>n </dependency>n <dependency>n <groupId>org.apache.maven.plugin-tools</groupId>n <artifactId>maven-plugin-annotations</artifactId>n <version>3.4</version>n </dependency>n <dependency>n <groupId>io.swagger</groupId>n <artifactId>swagger-annotations</artifactId>n <version>1.5.3</version>n </dependency>n <dependency>n <groupId>com.fasterxml.jackson.core</groupId>n <artifactId>jackson-core</artifactId>n <version>2.9.6</version>n </dependency>n <dependency>n <groupId>com.fasterxml.jackson.core</groupId>n <artifactId>jackson-databind</artifactId>n <version>2.9.6</version>n </dependency>n </dependencies>n <build>n <plugins>n <plugin>n <groupId>org.apache.maven.plugins</groupId>n <artifactId>maven-compiler-plugin</artifactId>n <version>3.8.0</version>n <configuration>n <source>1.8</source>n <target>1.8</target>n <encoding>UTF-8</encoding>n </configuration>n </plugin>n <plugin>n <groupId>org.apache.maven.plugins</groupId>n <artifactId>maven-plugin-plugin</artifactId>n <version>3.5.2</version>n </plugin>n </plugins>n </build>n</project>

入口类RestFormatCheckMojo.java  ,设置该插件的运行在PROCESS_CLASSES生命周期 ,保证编译完源码后能够进行模型的较验。

import static org.apache.maven.plugins.annotations.LifecyclePhase.PROCESS_CLASSES;nnimport java.io.File;nimport java.lang.reflect.Field;nimport java.lang.reflect.Modifier;nimport java.util.ArrayList;nimport java.util.Arrays;nimport java.util.List;nimport java.util.Map;nimport java.util.Set;nimport java.util.stream.Collectors;nnimport io.swagger.annotations.ApiModel;nimport io.swagger.annotations.ApiModelProperty;nimport junit.framework.Assert;nimport org.apache.maven.plugin.AbstractMojo;nimport org.apache.maven.plugin.MojoExecutionException;nimport org.apache.maven.plugins.annotations.Mojo;nimport org.apache.maven.plugins.annotations.Parameter;nimport org.apache.maven.plugins.annotations.ResolutionScope;nimport org.apache.maven.project.MavenProject;nnimport com.fasterxml.jackson.annotation.JsonIgnore;nimport com.fasterxml.jackson.annotation.JsonProperty;nimport com.fasterxml.jackson.databind.ObjectMapper;nimport com.fasterxml.jackson.databind.annotation.JsonNaming;nimport com.google.common.collect.Lists;nimport com.zte.sdn.oscp.topology.annotation.IgnoreFormatCheck;nimport com.zte.sdn.oscp.topology.util.JavaClassScanner;nn@Mojo(name = "yang2bean", defaultPhase = PROCESS_CLASSES, requiresDependencyResolution = ResolutionScope.COMPILE)npublic class RestFormatCheckMojo extends AbstractMojo { nn private List<String> notCheckPkg = Lists.newArrayList();nn @Parameter(property = "skipCheckPkg")n private String skipCheckPkg;nn @Parameter(property = "outDirectory", defaultValue = "${ project.build.outputDirectory}")n private File outputDirectory;nn @Parameter(defaultValue = "${ project.basedir}")n private File baseDir;nnn @Parameter(defaultValue = "${ project}", readonly = true)n private MavenProject project;nn @Parameter(defaultValue = "${ project.build.sourceDirectory}")n private File srcDir;nn @Parameter(defaultValue = "${ project.build.outputDirectory}")n private File outDir;n @Parameter(defaultValue = "${ project.compileClasspathElements}", readonly = true, required = true)n private List<String> compilePath;nn @Overriden public void execute() throws MojoExecutionException { n if (skipCheckPkg != null && !"".equals(skipCheckPkg.trim())) { n String[] split = skipCheckPkg.split(",");n notCheckPkg = Arrays.asList(split);n }n JavaClassScanner scanner = new JavaClassScanner(project);n scanner.scan(outDir);n List<Class> clsList = scanner.getClsList();n List<Class> models = filterByCondition(clsList);n try { n check(models);n } catch (Exception e) { n e.printStackTrace();n }n }nn private void check(List<Class> models) throws Exception { n ObjectMapper objectMapper = new ObjectMapper();n for (Class<?> aClass : models) { n Assert.assertTrue("[" + aClass.getName() + "] must annotated with AipModel", aClass.isAnnotationPresent(ApiModel.class));n Assert.assertEquals(aClass.getName().replace("$", "."), ((ApiModel) aClass.getAnnotation(ApiModel.class)).description());n String serialize = objectMapper.writeValueAsString(aClass.newInstance());n if ("[]".equals(serialize)) { n continue;n }n Map jsonPropertyMap = objectMapper.readValue(serialize, new MapTypeReference());n jsonPropertyMap.remove("class");nn List<String> apiModelProperties = new ArrayList<>();n List<Field> allFields = getAllFields(aClass);n for (Field field : allFields) { n if (field.isAnnotationPresent(JsonIgnore.class)) { n continue;n }n if (Modifier.isStatic(field.getModifiers())) { n continue;n }n //严格要求,必须定义ApiModelPropertyn Assert.assertTrue("[" + field.getName() + "] in [" + aClass.getName() + "] must annotated with ApiModelProperty", field.isAnnotationPresent(ApiModelProperty.class));n String name = field.getAnnotation(ApiModelProperty.class).name();n if (name == null || "".equals(name)) { n apiModelProperties.add(field.getName());n } else { n apiModelProperties.add(name);n }n }n Assert.assertEquals(jsonPropertyMap.size(), apiModelProperties.size());n Set set = jsonPropertyMap.keySet();n Assert.assertTrue("[" + aClass.getName() + "] JSON and ApiModelPorperty not same", set.containsAll(apiModelProperties));n Assert.assertTrue("[" + aClass.getName() + "] JSON and ApiModelPorperty not same", apiModelProperties.containsAll(set));n }n }nn private List<Class> filterByCondition(List<Class> clsList) { n List<Class> result = clsList.stream().filter(p -> { n if (p.isInterface()) { n return false;n }n for (String pkg : notCheckPkg) { n if (p.getName().startsWith(pkg)) { n return false;n }n }n if (p.isAnnotationPresent(IgnoreFormatCheck.class)) { n return false;n }n if (p.isAnnotationPresent(ApiModel.class)) { n return true;n }n if (p.isAnnotationPresent(JsonNaming.class)) { n return true;n }n for (Field declaredField : p.getDeclaredFields()) { n if (declaredField.isAnnotationPresent(JsonProperty.class)) { n return true;n }n }n return false;n }).collect(Collectors.toList());n return result;n }nnn private List<Field> getAllFields(Class cls) { n List<Field> fields = new ArrayList<>();n Class current = cls;n while (current != Object.class) { n fields.addAll(Arrays.asList(current.getDeclaredFields()));n current = current.getSuperclass();n }n return fields;n }nnn}

在插件开发中  ,无法直接使用Class.forName进行类加载,需要通过动态读取目标项目所依赖的classpath并根据这些classpath生成相应的url数组,以这个url数组作为参数得到的类加载器可以实现在maven插件中动态加载目标项目类及第三方引用包的目的 ,具体可以参考:https://www.cnblogs.com/coder-chi/p/11305498.html

Please note that the plugin classloader does neither contain the dependencies of the current project nor its build output. Instead, plugins can query the project’s compile, runtime and test class path from the MavenProject in combination with the mojo annotation requiresDependencyResolution from the Mojo API Specification. For instance, flagging a mojo with @requiresDependencyResolution runtime enables it to query the runtime class path of the current project from which it could create further classloaders.

四、运行效果

如图所示 :相关不满足规范的定义已经正确拦截

最佳实践之接口规范性检查插件最佳实践之接口规范性检查插件最佳实践之接口规范性检查插件

友情链接华为汪涛:5G物联网市场规模预计2026年达402亿美元全免一“夏” 买新能源就“购”了徐工集团与京东集团宣布战略合作美股大型科技股全线走低 亚马逊跌1.44%纳米BOX上市,纯电续航331公里,售价6.57万-7.17万阿尔法S HI版开始交付 搭华为HI全栈智能方案图形说股:祥鑫科技、金智科技、京山轻机等热门高标股的主力动向特斯拉狂粉用亲女儿测自动驾驶!曾多次撞飞假人!网友:亲爹?2K拿下骁龙888旗舰,还要啥自行车Python实现经典算法之递推算法stackoverflow 2022 年开发者调查Victoriametrics大胆地将边缘计算带入太空边缘无线和有线服务的融合是电信大趋势天极科技冲刺科创板 拟募资3.83亿元 报告期存货账面价值攀升亚马逊跟卖是什么意思?跟卖有什么好处和风险?A股5大“量子技术”龙头企业,市值低前景好,备受龙头企业青睐雅迪、爱玛高端梦在2022年使用华为mate20 pro是什么体验iPhone 14系列或9月7日发布/一加首款折叠屏手机曝光中南大学:3D打印复合材料薄壁结构多工况载荷下的渐进坍塌行为和机理研究11天9板金智科技:公司虚拟电厂、储能相关业务尚未中标重大项目人形机器人“邓丽君”亮相世界机器人大会 献唱《我只在乎你》分析人工智能机器人的主观意识形态乘联会:上半年新能源微卡、重卡销量大幅上升MYSQL术语介绍:change bufferSpring面试八股文之IoCspring boot 中运用quartz开发定时任务2台S7-1200PLC modbus 通信京东发布最新白皮书:品牌智胜营销方法论赛博昆仑于全球黑帽大会斩获中国安全研究史上最佳成绩浅谈世界"电动"汽车发展历程(一)骁龙8+旗舰怎么选?这三款便宜又好用电梯广告小程序开发,商家推广好帮手DARPA欲借SocialCyber项目摸底开源代码的可信度想要手机用上五年不换,建议一步到位,目前这三款手机可以满足6个压箱底的微信小程序,个个好用不要钱,请大家低调使用iPhone14涨价罗生门iOS15.6RC2正式发布,续航高,发热低,信号强,顶级养老版本Galaxy Z Fold 4/Z Flip 4通过NBTC认证 表明即将发布Counterpoint 公布国内折叠屏手机市场份额:华为一家独大
联系我们

地址:联系地址联系地址联系地址

电话:020-123456789

传真:020-123456789

邮箱:admin@aa.com

0.3447

Copyright © 2024 Powered by 盐城市某某装饰材料业务部   sitemap