前言
为什么接口会出现多个版本?
一般来说,restful api 接口是提供给其它模块,系统或是其他公司使用,不能随意频繁的变更。然而,需求和业务不断变化,接口和参数也会发生相应的变化。如果直接对原来的接口进行修改,势必会影响线其他系统的正常运行。这就必须对 api 接口进行有效的版本控制。
接口多版本的方式
相同url,用不同的版本参数区分
- api.test.com/user?version=v1
- api.test.com/user?version=v2
- version=v1 表示 v1版本的接口, 保持原有接口不动
- version=v2 表示 v2版本的接口,更新新的接口
区分不同的接口域名
不同的版本有不同的子域名, 路由到不同的实例:
- v1.api.test.com/user
- v2.api.test.com/user
- v1版本的接口, 保持原有接口不动, 路由到instance1
- v2版本的接口,更新新的接口, 路由到instance2
网关路由不同子目录到不同的实例
- api.test.com/v1/user
- api.test.com/v2/user
- v1版本的接口, 保持原有接口不动, 路由到instance1
- v2版本的接口,更新新的接口, 路由到instance2
同一实例,用注解隔离不同版本控制
- api.test.com/v1/user
- api.test.com/v2/user
- v1版本的接口, 保持原有接口不动,匹配@apiversion(“1”)的handlermapping
- v2版本的接口,更新新的接口,匹配@apiversion(“2”)的handlermapping
下面咱们主要展示第四种单一实例中如何优雅的控制接口的版本。
实现案例
这个例子基于 springboot 封装了 @apiversion 注解方式控制接口版本。
自定义 @apiversion 注解
package com.test.springboot.api.version.config.version;
import org.springframework.web.bind.annotation.mapping;
import java.lang.annotation.*;
@target({elementtype.method, elementtype.type})
@retention(retentionpolicy.runtime)
@documented
@mapping
public @interface apiversion {
string value();
}定义版本匹配 requestcondition
版本匹配支持三层版本
- v1.1.1 (大版本.小版本.补丁版本)
- v1.1 (等同于v1.1.0)
- v1 (等同于v1.0.0)
package com.test.springboot.api.version.config.version;
import lombok.getter;
import lombok.extern.slf4j.slf4j;
import org.springframework.web.servlet.mvc.condition.requestcondition;
import javax.servlet.http.httpservletrequest;
import java.util.arrays;
import java.util.collections;
import java.util.list;
import java.util.regex.matcher;
import java.util.regex.pattern;
@slf4j
public class apiversioncondition implements requestcondition<apiversioncondition> {
/**
* support v1.1.1, v1.1, v1; three levels .
*/
private static final pattern version_prefix_pattern_1 = pattern.compile("/v\\d\\.\\d\\.\\d/");
private static final pattern version_prefix_pattern_2 = pattern.compile("/v\\d\\.\\d/");
private static final pattern version_prefix_pattern_3 = pattern.compile("/v\\d/");
private static final list<pattern> version_list = collections.unmodifiablelist(
arrays.aslist(version_prefix_pattern_1, version_prefix_pattern_2, version_prefix_pattern_3)
);
@getter
private final string apiversion;
public apiversioncondition(string apiversion) {
this.apiversion = apiversion;
}
/**
* method priority is higher then class.
*
* @param other other
* @return apiversioncondition
*/
@override
public apiversioncondition combine(apiversioncondition other) {
return new apiversioncondition(other.apiversion);
}
@override
public apiversioncondition getmatchingcondition(httpservletrequest request) {
for (int vindex = 0; vindex < version_list.size(); vindex++) {
matcher m = version_list.get(vindex).matcher(request.getrequesturi());
if (m.find()) {
string version = m.group(0).replace("/v", "").replace("/", "");
if (vindex == 1) {
version = version + ".0";
} else if (vindex == 2) {
version = version + ".0.0";
}
if (compareversion(version, this.apiversion) >= 0) {
log.info("version={}, apiversion={}", version, this.apiversion);
return this;
}
}
}
return null;
}
@override
public int compareto(apiversioncondition other, httpservletrequest request) {
return compareversion(other.getapiversion(), this.apiversion);
}
private int compareversion(string version1, string version2) {
if (version1 == null || version2 == null) {
throw new runtimeexception("compareversion error:illegal params.");
}
string[] versionarray1 = version1.split("\\.");
string[] versionarray2 = version2.split("\\.");
int idx = 0;
int minlength = math.min(versionarray1.length, versionarray2.length);
int diff = 0;
while (idx < minlength
&& (diff = versionarray1[idx].length() - versionarray2[idx].length()) == 0
&& (diff = versionarray1[idx].compareto(versionarray2[idx])) == 0) {
++idx;
}
diff = (diff != 0) ? diff : versionarray1.length - versionarray2.length;
return diff;
}
}定义 handlermapping
package com.test.springboot.api.version.config.version;
import org.springframework.core.annotation.annotationutils;
import org.springframework.lang.nonnull;
import org.springframework.web.servlet.mvc.condition.requestcondition;
import org.springframework.web.servlet.mvc.method.annotation.requestmappinghandlermapping;
import java.lang.reflect.method;
public class apiversionrequestmappinghandlermapping extends requestmappinghandlermapping {
/**
* add @apiversion to controller class.
*
* @param handlertype handlertype
* @return requestcondition
*/
@override
protected requestcondition<?> getcustomtypecondition(@nonnull class<?> handlertype) {
apiversion apiversion = annotationutils.findannotation(handlertype, apiversion.class);
return null == apiversion ? super.getcustomtypecondition(handlertype) : new apiversioncondition(apiversion.value());
}
/**
* add @apiversion to controller method.
*
* @param method method
* @return requestcondition
*/
@override
protected requestcondition<?> getcustommethodcondition(@nonnull method method) {
apiversion apiversion = annotationutils.findannotation(method, apiversion.class);
return null == apiversion ? super.getcustommethodcondition(method) : new apiversioncondition(apiversion.value());
}
}配置注册handlermapping
package com.test.springboot.api.version.config.version;
import org.springframework.context.annotation.configuration;
import org.springframework.web.servlet.config.annotation.webmvcconfigurationsupport;
import org.springframework.web.servlet.mvc.method.annotation.requestmappinghandlermapping;
@configuration
public class customwebmvcconfiguration extends webmvcconfigurationsupport {
@override
public requestmappinghandlermapping createrequestmappinghandlermapping() {
return new apiversionrequestmappinghandlermapping();
}
}
或者实现 webmvcregistrations 接口
@configuration
@requiredargsconstructor
public class webconfig implements webmvcconfigurer, webmvcregistrations {
//...
@override
@nonnull
public requestmappinghandlermapping getrequestmappinghandlermapping() {
return new apiversionrequestmappinghandlermapping();
}
}
测试运行
controller
package com.test.springboot.api.version.controller;
import org.springframework.web.bind.annotation.requestmapping;
import org.springframework.web.bind.annotation.restcontroller;
import tech.pdai.springboot.api.version.config.version.apiversion;
import tech.pdai.springboot.api.version.entity.user;
/**
* @author farerboy
*/
@restcontroller
@requestmapping("api/{v}/user")
public class usercontroller {
@requestmapping("get")
public user getuser() {
return user.builder().age(18).name("pdai, default").build();
}
@apiversion("1.0.0")
@requestmapping("get")
public user getuserv1() {
return user.builder().age(18).name("pdai, v1.0.0").build();
}
@apiversion("1.1.0")
@requestmapping("get")
public user getuserv11() {
return user.builder().age(19).name("pdai, v1.1.0").build();
}
@apiversion("1.1.2")
@requestmapping("get")
public user getuserv112() {
return user.builder().age(19).name("pdai2, v1.1.2").build();
}
}
输出
http://localhost:8080/api/v1/user/get
// {"name":"farerboy, v1.0.0","age":18}http://localhost:8080/api/v1.1/user/get
// {"name":"farerboy, v1.1.0","age":19}http://localhost:8080/api/v1.1.1/user/get
// {"name":"farerboy, v1.1.0","age":19} 匹配比1.1.1小的中最大的一个版本号http://localhost:8080/api/v1.1.2/user/get
// {"name":"farerboy, v1.1.2","age":19}http://localhost:8080/api/v1.2/user/get
// {"name":"farerboy, v1.1.2","age":19} 匹配最大的版本号,v1.1.2
这样,如果我们向另外一个模块提供v1版本的接口,新的需求中只变动了一个接口方法,这时候我们只需要增加一个接口添加版本号v1.1即可用v1.1版本访问所有接口。
此外,这种方式可能会导致v3版本接口没有发布,但是是可以通过v3访问接口的;这种情况下可以添加一些限制版本的逻辑,比如最大版本,版本集合等。
到此这篇关于springboot 如何实现多版本接口的方法步骤的文章就介绍到这了,更多相关springboot 多版本接口内容请搜索代码网以前的文章或继续浏览下面的相关文章希望大家以后多多支持代码网!
发表评论