ApiVesrsionCondition.java 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package com.yihu.jw.version;
  2. import org.springframework.web.servlet.mvc.condition.RequestCondition;
  3. import javax.servlet.http.HttpServletRequest;
  4. import java.util.regex.Matcher;
  5. import java.util.regex.Pattern;
  6. /**
  7. * 版本控制的规则类
  8. * Created by chenweida on 2017/6/15.
  9. */
  10. public class ApiVesrsionCondition implements RequestCondition<ApiVesrsionCondition> {
  11. // 路径中版本的前缀, 这里用 /v[1-9]/的形式
  12. private final static Pattern VERSION_PREFIX_PATTERN = Pattern.compile("v(\\d+)/");
  13. private int apiVersion;
  14. public ApiVesrsionCondition(int apiVersion){
  15. this.apiVersion = apiVersion;
  16. }
  17. public ApiVesrsionCondition combine(ApiVesrsionCondition other) {
  18. // 采用最后定义优先原则,则方法上的定义覆盖类上面的定义
  19. return new ApiVesrsionCondition(other.getApiVersion());
  20. }
  21. public ApiVesrsionCondition getMatchingCondition(HttpServletRequest request) {
  22. String path=request.getRequestURI();
  23. Matcher m = VERSION_PREFIX_PATTERN.matcher(path);
  24. if(m.find()){
  25. Integer version = Integer.valueOf(m.group(1));
  26. if(version >= this.apiVersion) // 如果请求的版本号大于配置版本号, 则满足
  27. return this;
  28. }
  29. return null;
  30. }
  31. public int compareTo(ApiVesrsionCondition other, HttpServletRequest request) {
  32. // 优先匹配最新的版本号
  33. return other.getApiVersion() - this.apiVersion;
  34. }
  35. public int getApiVersion() {
  36. return apiVersion;
  37. }
  38. }