Spring Cloud how so many micro-service interface debugging?

Foreword

Today we talk about the Spring and micro-Cloud service under the topic of service interface debugging and management! We know that in the micro-service architecture, software systems will be split into a number of stand-alone services, interactive communication between these services require, you need to define a wide variety of service interfaces. Specifically, the micro-service model based on Spring Cloud, the individual micro-services will be defined based on Spring MVC Controller of multiple interfaces need to publish the micro-services to the outside.

Depending on the individual micro-service functions defined boundaries, slightly services will provide specific business-related interfaces, such as payment interface, account interface; while slightly services will provide some public service nature of the interface, such as text messaging interfaces, unified authentication interfaces and the like. These services are often micro is again a number of different teams in the development and maintenance, service interface definition of the traditional way often require service providers to provide a good, relatively high readability interface documentation it can be more convenient and docking test, in fact, as time goes on, the iterative updating personnel, in many cases these early interface documentation often because no maintenance and will soon be out of date, even though when, under such a way that the micro-service model will serve as interface documentation too much and let the developers seem crazy!

Is there a way to more easily allows developers to interface the same time, it can automatically generate highly consistent with the service interface documentation to do? The answer is yes, then we talk about it together in the end and what kind of ways to make the interface micro-management services become easier!

Interface management presentation

In fact, the market has a variety of open source projects provide such support! Such as: Swagger, ApiDoc, RAP, DOCLever, CrapApi, these projects provide for Api online document management features, so it is more suitable in Spring Cloud system in which way? Here, we take a contrast of the advantages and disadvantages of these projects.

Swagger

Swagger is a based on YAML, JSON documents online language and code generation tools automatically generated. Its advantages are as follows:

1), it can be directly embedded in the Spring Boot project written comment by the development, which automatically generates the interface documents, to achieve highly consistent code document;
2), can analyze the structure of the interface, and may also be verified by initiation request correctness interface;
3), which provides a variety of programming languages before and after the end of the separation solution that supports a variety of interfaces to export the server or client code language based on defined;
4), it also includes Swagger Editor, which yaml is to use the language of Swagger API editor support interfaces file export yaml and json format;
5), contains Swagger UI, it can be edited Swagger editor interface documentation to show in the form of html;
6), free open source, supports internationalization, eco-rich, community activists;

The disadvantage is that:

1), there is code-invasive;
2), different projects Swagger interface documentation is separate from the need to go to different places;
3), Swagger out of the UI interface documentation to show the lack of classification, experience relatively poor;
4) , different projects do not have permission management interface documentation, lack Mock;

ApiDoc

ApiDoc is a lightweight like Swagger online document generation tool. The disadvantage is also similar to Swagger, interface management, automated testing and other functions are relatively weak, and their communities, ecological aspects are not as good as the internationalization of Swagger.

RAP

RAP is a visual interface management tool that can analyze the structure of the interface dynamically generated simulation data, check the correctness of real interfaces around the interface definition, to enhance the efficiency of collaborative service delivery model through a series of micro-automation tools.

Its advantages are as follows:

1), support for project management, team management, document version management;
2) support the Mock test data;
3), Ali manufacturers produced, get practice in internal Alibaba;
4) to support the interface to retrieve;
5), the interface can be analyzed structure, initiated the request check the correctness of the interface;
6), free and open source

Shortcomings are as follows:

1), documents and interfaces separation, it is prone to inconsistency;
2), each interface requires manual editing;
3), the back-end using nodejs written, inconsistent with the Java-based Spring Cloud technology stack;

DOCLever

DOCLever is a free open source interface management tool, its advantages are as follows:

1), support for project management, team management, documentation tools rich;
2), supports rich Mock test data;
3), the user is also more abundant case: drops, the US group, 58 city, city tourism;
4), support interface to retrieve;
5), can analyze the structure of the interface, interface to initiate a request check the correctness of the parameters is also very rich;
6), support for automated testing of complex scenes, such as access verification code, log in, get a list of orders, and even get a context associated with a specific order details and other operations;

Shortcomings are as follows:

1), documents and interfaces separation, it is prone to inconsistency;
2), each interface requires manual editing;
3), the back end is written using nodejs, Spring Cloud inconsistent with the Java technology stack;

CrapApi

Following advantages:

1), support for project management, team management, document version management;
2) support the Mock test data;
3) to support the interface to retrieve;
4) can be analyzed interface structure, initiate check the correctness of the request interface;
5), support interface monitoring, set the alarm rules, promptly notify the person in charge of the service when the interface is not available;
6), based on the back-end Java development, Java and Spring Cloud technology stack match;
7), free and open source;

Disadvantages:

1), documents and interfaces separation, it is prone to inconsistency;
2), each interface requires manual editing;
3), less use cases, function is not perfect, there may be many pit;

Spring Cloud Integration Swagger

By analysis of these open source projects, in addition to all documentation and code separation Swagger outside the rest of the way to take the project, although this will reduce the intrusion of the code, but can also cause inconsistencies in documentation and code, it's based on Spring Cloud micro services, we select Swagger as micro-services interface management tool.

So Spring Cloud Spring Boot micro services based on the Swagger how to integrate it?

1), introduced in Spring Boot micro Maven relies service project:

 <dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger2</artifactId>
     <version>2.2.2</version>
 </dependency>
 <dependency>
     <groupId>io.springfox</groupId>
     <artifactId>springfox-swagger-ui</artifactId>
     <version>2.2.2</version>
 </dependency>

2) Create Swagger2 configuration class:

@Configuration
@EnableSwagger2
@Profile("!production")
public class SwaggerConfiguration {
    @Bean
    public Docket docket() {
        return new Docket(DocumentationType.SWAGGER_2)
                .groupName("Api")
                .select()
                .apis(withClassAnnotation(RestController.class))
                .build()
                .globalOperationParameters(commonParameters())
                .apiInfo(apiInfo());
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("Api")
                .version("1.0.0-SNAPSHOT")
                .build();
    }

    private List<Parameter> commonParameters() {
        List<Parameter> parameters = Lists.newArrayList();
        parameters.add(new ParameterBuilder()
                .name("war")
                .description("backdoor 在测试环境绕过鉴权")
                .modelRef(new ModelRef("string"))
                .parameterType("query")
                .required(false)
                .defaultValue("war123")
                .build());
        parameters.add(new ParameterBuilder()
                .name("uid")
                .description("backdoor 设定的用户ID")
                .modelRef(new ModelRef("string"))
                .parameterType("query")
                .required(false)
                .defaultValue("1000053")
                .build());
        parameters.add(new ParameterBuilder()
                .name("Authorization")
                .description("生产环境中,需要传递的用户当前 Token")
                .modelRef(new ModelRef("string"))
                .parameterType("header")
                .required(false)
                .defaultValue("Bearer XXXXX")
                .build());
        return parameters;
    }
}

The above configuration class, we can ( "! Production") notes the environment specified by the entry into force of @Profile, as we set here except in a production environment, other environments are effective.

3), add document content

After the above configuration, in fact, can produce content of the document, but this document is a request for itself, the main source describes the naming function, multi-user unfriendly, in order to make the document easier to read and understand, we can Swagger annotations to add some description. These annotations are:

@Api: with class, the role of the class described. br /> @ ApiOperation: annotation to increase the API method explanation.
@ApiImplicitParams: contains a set of parameters used in the described method.
br /> @ ApiImplicitParam: annotation to a method for increasing the parameters described.
@ApiResponses: is used to represent a set of responses.
br /> @ ApiResponse: @ApiResponses used in the general expression for an error response message.
@ApiModel: a description of the Model (generally can not be used when the annotation request @ApiImplicitParam parameters described herein).

Next, we demonstrate the next through a real case of micro-services interface definition:

@Api(value = "运维端系统用户层外部接口", description = "用于组装直接面向运维App端相关服务")
@RestController
@Slf4j
public class OperationUserController {

    @Autowired
    OperationUserService operationUserServiceImpl;

    @ApiOperation(value = "运维端用户注册", httpMethod = "POST")
    @RequestMapping(value = "/userRegister", method = RequestMethod.POST)
    public APIResponse sysUserRegister(@RequestParam(value = "mobileNo") String mobileNo,
            @RequestParam(value = "email") String email,
            @RequestParam(value = "nickName", required = false) String nickName,
            @RequestParam(value = "idName") String idName, @RequestParam(value = "idType") String idType,
            @RequestParam(value = "idNo") String idNo, @RequestParam(value = "gender") String gender,
            @RequestParam(value = "password") String password, @RequestParam(value = "verifyCode") String verifyCode,
            @RequestParam(value = "creator") String creator) {
        UserRegisterReqVo userRegisterReqVo = UserRegisterReqVo.builder().mobileNo(mobileNo).email(email)
                .nickName(nickName).idName(idName).idType(idType).idNo(idNo).gender(gender).passwd(password)
                .passcode(verifyCode).creator(creator).build();
        UserRegisterResVo userRegisterResVo;
        try {
            userRegisterResVo = operationUserServiceImpl.userRegister(userRegisterReqVo);
        } catch (BizException e) {
            log.error(e.toString() + "_" + e.getMessage(), e);
            return APIResponse.error(e.getCode(), e.getMessage());
        } catch (Exception e) {
            log.error(e.toString() + "_" + e.getMessage(), e);
            return APIResponse
                    .error(ApiResultStatus.INTERNAL_SERVER_ERROR.getApiResultStatus(),
                            ApiResultStatus.INTERNAL_SERVER_ERROR.getMessageResourceName());
        }
        return APIResponse
                .success(ApiResultStatus.SUCCESS.getApiResultStatus(), ApiResultStatus.SUCCESS.getMessageResourceName(),
                        userRegisterResVo);
    }
}

In the above we define a micro-service user registration interface, then start micro-services, and then enter the micro-services IP + port + / swagger-ui.html, you can see Swagger-UI, and are as follows:

Spring Cloud how so many micro-service interface debugging?

By Swagger-UI we can verify the way the test interface, but because the interface fields in the UI descriptions and temporary, and is fully consistent with the actual code, so based on these interfaces are defined in docking docking on it!

Guess you like

Origin blog.51cto.com/14570694/2464681