本周分享是:https://www.springboottutorial.com/spring-boot-versioning-for-rest-services 对restful接口进行版本化

文中提到了4中版本化的方式,并且进行了优劣分析

1、通过uri进行版本化

  • http://localhost:8080/v1/person
  • http://localhost:8080/v2/person

2、通过url参数进行版本化

  • http://localhost:8080/person/param?version=1
  • http://localhost:8080/person/param?version=2
      @GetMapping(value = "/student/param", params = "version=1")
      public StudentV1 paramV1() {
        return new StudentV1("Bob Charlie");
      }
    
      @GetMapping(value = "/student/param", params = "version=2")
      public StudentV2 paramV2() {
        return new StudentV2(new Name("Bob", "Charlie"));
      }

 

 

3、通过http的header添加版本信息

 

  • http://localhost:8080/person/header
    • headers=[X-API-VERSION=1]
  • http://localhost:8080/person/header
    • headers=[X-API-VERSION=2]
@GetMapping(value = "/student/header", headers = "X-API-VERSION=1")
  public StudentV1 headerV1() {
    return new StudentV1("Bob Charlie");
  }

  @GetMapping(value = "/student/header", headers = "X-API-VERSION=2")
  public StudentV2 headerV2() {
    return new StudentV2(new Name("Bob", "Charlie"));
  }

  4、通过Media type进行版本化

  • http://localhost:8080/person/produces
    • headers[Accept=application/vnd.company.app-v1+json]
  • http://localhost:8080/person/produces

headers[Accept=application/vnd.company.app-v2+json]

 

 @GetMapping(value = "/student/produces", produces = "application/vnd.company.app-v1+json")
  public StudentV1 producesV1() {
    return new StudentV1("Bob Charlie");
  }

  @GetMapping(value = "/student/produces", produces = "application/vnd.company.app-v2+json")
  public StudentV2 producesV2() {
    return new StudentV2(new Name("Bob", "Charlie"));
  }

  文中提到了几种技术选型所需要考虑的一些因素:

1、uri污染,第一种和第二种会对uri进行污染

2、错误使用http头,http头设计的时候不是用于版本化

3、能否简单的在浏览器测试,主要是为了测试啊方便

4、缓存,如果版本化消息放在http头,我们就无法根据url进行缓存,需要考虑header信息

5、api文档化,文档生产的时候,如何标注同一个服务的不同版本