【摘要】 本文是使用CSE RestServlet替换Spring MVC DispatcherServlet常见问题汇总。
将Spring Boot的REST应用改造为CSE的REST应用的核心部分就是使用CSE RestServlet替换Spring MVC DispatcherServlet。有很多文章介绍了相关工作量评估、替换原理、改造步骤等。比如:
[改造原理和步骤] 在Spring Boot中使用CSE
[改造工作量评估] 微服务改造设计参考
[改造步骤和实践] 基于Spring Boot 2.0的IoT应用集成和使用CSE实践
本文主要是常见问题汇总。
@RequestMapping(value = {"/v3-ext/agencies", "/v3-huawei/agencies", "/v3.0/OS-AGENCY/agencies"},
method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public Map listAgency(@RequestParam("domain_id") String domainId)
以上接口定义了多个Path。在CSE中,一个接口只能允许一个Path,并且必须存在唯一的operation id。默认情况下operation id就是方法名。
可以将一个接口拆分为多个接口。
@RequestMapping(value = {"/v3-ext/agencies"},
method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public Map listAgency1(@RequestParam("domain_id") String domainId)
@RequestMapping(value = {"/v3.0/OS-AGENCY/agencies"},
method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
public Map listAgency2(@RequestParam("domain_id") String domainId)
@RequestMapping(value = "/v3/groups/{group_id}/users/{user_id}", method = RequestMethod.HEAD, produces = "application/json;charset=UTF-8")
public void isUserOfGroup(@PathVariable("group_id") String groupId,
@PathVariable("user_id") String userId, HttpServletResponse response)
以上接口使用了HttpServletResponse作为接口参数。CSE的通信层与编码层是完全解耦的,业务代码不能直接操作通信层的响应。另外,CSE要求所有接口都需要有明确的定义(即契约,swagger),开发的时候,接口定义即文档。
这种情况需要试业务逻辑进行分析,将操作response的内容抽取为响应值。比如:
response.setStatus(resultCode)
这种代码只是想设置响应的错误码,可以替换为下面的方式:
@RequestMapping(value = "/v3/groups/{group_id}/users/{user_id}", method = RequestMethod.HEAD, produces = "application/json;charset=UTF-8")
@ApiResponses({
@ApiResponse(code = 200, response = String.class, message = ""),@ApiResponse(code = 204, response = String.class, message = "")
})
public Response isUserOfGroup(@PathVariable("group_id") String groupId,
@PathVariable("user_id") String userId) throws BadRequestException {
if(groupService.isUserOfGroup(groupId, userId)) {
return Response.create(javax.ws.rs.core.Response.Status.OK, "");
} else {
return Response.create(javax.ws.rs.core.Response.Status.NO_CONTENT, "");
}
}
@RequestMapping(value = "/v3/regions/{region_id}", method = RequestMethod.GET, produces="application/json;charset=UTF-8")
public Map getRegion(@PathVariable("region_id") String regionId)
其中Region类包含字段locales是Map,没有具体类型。
public class Region {
private String id;
private String description;
private String parent_region_id;
private String type;
private Map locales;
private Links links;
这种情况是具体情况修改为具体类型即可,比如Map
来源:华为云社区 作者:liubao68