欢迎来到 丹东市某某商贸培训中心
全国咨询热线:020-123456789
联系我们

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

电话:020-123456789

传真:020-123456789

邮箱:admin@aa.com

新闻中心
最佳实践之接口规范性检查插件
  来源:丹东市某某商贸培训中心  更新时间:2024-05-05 11:09:31

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

前言

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

一、范性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.

四、运行效果

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

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

友情链接lol我的英雄联盟三周年活动 lol我的影响力活动网址求生之路2怎么联机-两种有效联机方法win11英雄联盟进不去怎么回事 win11系统lol进不去游戏如何修复dnf解密暗号魔兽世界plus输出法师P1毕业天赋符文配装推荐王者荣耀:暃从出场到全民厌恶不到短短两天,这英雄究竟多恶心魔兽世界黑爪龙虾怎么获得正在阅读:摩尔庄园密码箱密码是多少 密码箱密码破解教程【详解】摩尔庄园密码箱密码是多少 密码箱密码破解教程【详解】浓缩铀多少钱一克怎么玩好《王者荣耀》里的鬼谷子?自带gm权限的手游app推荐2岁10个月第1周的孩子梦幻西游:每次重置星盘都是华丽大爆 天罡星高兽决和五宝拿不停召唤刀爷为你而战!暗黑3死灵法师复活技能测试仙剑奇侠传1修改器 v1.0dnf读取文件失败怎么回事、DNF读取文件失败,如何解决?DNF: 旭旭宝宝准备玩奶妈! 看到这三个宝珠, 玩家: 一万智力奶妈?暗黑破坏神3单机版 绿色中文破解版斯通纳德传送门的简单介绍全民斗战神四大职业技能对比分析 最是最强DNF:增幅改版后耳环白11好还是红10好?dnf解密暗号梦幻西游:每次重置星盘都是华丽大爆 天罡星高兽决和五宝拿不停原神荒海五个机关解密攻略地下城扩大账号金库需要的材料,地下城与勇士金库广东梅州抢车杀人犯被执行死刑PassFab Android Unlock破解版(安卓手机屏幕解锁软件)1.80星王合击拳头宣布5月28日举办“特殊”的《英雄联盟》季中赛稳定200坐骑!魔兽世界玩家分享坐骑收集指南斯坦索姆刷马路线与地图(斯坦索姆刷马路线与地图不符)沙滩上的圆滚滚——扣扣奇沙滩圆石归纳整合 | 高考常考的风沙问题浅谈法系影魔的玩法:“你无处可藏。”CF手游白骨之秘觉醒宝箱抽奖技巧梦幻西游年底最强捡漏王,5.5W的号仓库塞满8级宝石还有15个神兜兜无尽之剑3藏宝图地点及获取攻略dnf净化之石怎么获得-净化之石获得途径及用途DNF宠物淘气虎怎么获得 DNF宠物淘气虎获取方法攻略dnf怎么分解时装(dnf无法分解的时装怎么办)小狗的日记
联系我们

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

电话:020-123456789

传真:020-123456789

邮箱:admin@aa.com

0.1745

Copyright © 2024 Powered by 丹东市某某商贸培训中心   sitemap