2

介绍

mpaas-springboot-base是得帆公司开发,帮助开发者开发更规范更健壮的spring boot程序

安装

目前没有提交至maven中央仓库,后续会提交到maven仓库.目前只能采用本地安装方式,安装前确认是否本地已安装maven.执行以下命令行,如能正常执行即可.

$ mvn -v
Apache Maven 3.5.0 (ff8f5e7444045639af65f6095c62210b5713f426; 2017-04-04T03:39:06+08:00)
Maven home: /Users/asan/u01/mvn
Java version: 1.8.0_161, vendor: Oracle Corporation
Java home: /Library/Java/JavaVirtualMachines/jdk1.8.0_161.jdk/Contents/Home/jre
Default locale: zh_CN, platform encoding: UTF-8
OS name: "mac os x", version: "10.12.4", arch: "x86_64", family: "mac"
  1. 下载mpaas-springboot-base-v1.0.0.jar包,执行以下命令将jar包安装至本地仓库.
mvn install:install-file -Dfile="/Users/asan/workspace/mpaas/common/out/artifacts/mpaas-springboot-base_v1_0_0/mpaas-springboot-base-v1.0.0.jar" -DgroupId=com.definesys.mpaas -DartifactId=mpaas-springboot-base -Dversion=1.0.0 -Dpackaging=jar
  1. 修改项目pom.xml文件,增加依赖
<dependency>
    <groupId>com.definesys.mpaas</groupId>
    <artifactId>mpaas-springboot-base</artifactId>
    <version>1.0.0</version>
</dependency>

使用

配置启动类

修改启动类xxxApplication.java增加以下注解

@ComponentScan(basePackages = {"com.definesys.mpaas.common","启动类所在的包路径"})

spring boot默认扫描启动类所在的package下的类,要手动增加注解才能让spring boot扫描到mpaas-springboot-base.比如启动类全路径为com.definesys.demo.DemoApplication那么注解应该写成以下格式

@ComponentScan(basePackages = {"com.definesys.mpaas.common","com.definesys.demo"})

至此,你可以使用mpaas-springboot-base所有的功能.

接口返回

所有的controller返回值统一为com.definesys.mpaas.common.http.Response该类定义了一套标准返回格式和相关api

Response字段
    private String code = CODE_OK;  //操作结果编码 ok/error
    private String message;         //记录错误信息或者需要提示给用户的信息
    private Long total;             //记录总数
    private Object data;            //非列表数据
    private List<Object> table;     //列表数据
    private String requestid;       //请求uuid
    
    public static final String CODE_OK = "ok";
    public static final String CODE_ERR = "error";

规定如果是系统错误,如程序异常,空指针等,以http status形式返回500错误.程序应该返回一个code=error的并且http code=500的Response,但如果放在业务代码里处理不仅繁琐也容易忽略掉异常,导致有漏网之鱼.mpaas也提供了更为简便的方案,下面会提到.<br/>
从返回的数据类型来看,抽象出列表非列表两种数据,这边放到两个字段里,列表数据放到table非列表数据防到data

Response-Api:返回成功

1. 只返回code没有数据

Response ok=Response.ok();

输出

{
    "code": "ok",
    "requestid": "0f253675a20147d1b4b106404e4ed21d"
}

ps:每次请求服务器返回Response都会带一个唯一的requestid,该requestid可作为日志追踪业务查询等<br/>
2. 返回非列表数据

//Response ok=new Response()
Response ok=Response.ok();
Map<String,String> data=new HashMap<String,String>();
data.put("user","asan");
data.put("company","definesys");
ok.setData(data);

输出

{
    "code": "ok",
    "data": {
        "company": "definesys",
        "user": "asan"
    },
    "requestid": "2fcae4e453b746e6bfbf95fc76e1618b"
}

如果返回的数据都是key-value形式,也可以写成如下形式

Response ok = Response.ok().set("user", "asan")
                .set("company", "definesys")
                .set("email","jianfenng.zheng@definesys.com");

3. 返回列表数据

List<String>list=new ArrayList<>();
list.add("jianfeng");
list.add("asan");
list.add("Mr.Zheng");
Response ok=Response.ok();
ok.setTable(list);

输出

{
    "code": "ok",
    "total": 3,
    "table": [
        "jianfeng",
        "asan",
        "Mr.Zheng"
    ],
    "requestid": "534435d7812d4810916abd9577b350cf"
}

同样也可以写成如下形式

Response ok = Response.ok().addListItem("jianfeng")
                .addListItem("asan")
                .addListItem("Mr.Zheng");

4. 返回错误

Response ok = Response.error("系统出错");

输出

{
    "code": "error",
    "message": "系统出错",
    "requestid": "a491589ed2b04fe1b1a7e4c73c29178e"
}

异常处理

这里将异常分为两类

  1. 运行时异常:指因为程序bug或者系统问题导致接口调用失败,属于不可预料异常
  2. 业务异常: 指业务数据不符合要求接口本身抛出异常

mpass也分别提供两个类MpaasRuntimeExceptionMpaasBusinessException对应运行时异常业务异常

下面以一个例子说明说明这两个异常使用方法<br/>

测试接口

@RequestMapping(value = "/testException")
    public Response testException(@RequestParam(value = "data") String data) {
        Integer value = null;
        try {
            value = Integer.parseInt(data);
        } catch (Exception ex) {
            throw new MpaasRuntimeException(ex);
        }
        if (value < 10) {
            throw new MpaasBusinessException("数据不合法请输入一个大于10的数字");
        }
        return Response.ok();
    }

RuntimeException(运行时异常)

$ curl http://localhost:8080/testException?data=a -v
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /testException?data=a HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 500   ##返回500
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Mon, 27 Aug 2018 10:58:41 GMT
< Connection: close
<
* Curl_http_done: called premature == 0
* Closing connection 0
{
    "code": "error",
    "message": "系统出错请联系管理员",
    "requestid": "f8beb8c1e817414ba0b2e856f22b0b4d"
}

BusinessException(业务异常)

$ curl http://localhost:8080/testException?data=9 -v
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /testException?data=9 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 200 ##返回200
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Mon, 27 Aug 2018 10:59:57 GMT
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
{
    "code": "error",
    "message": "数据不合法请输入一个大于10的数字",
    "requestid": "0ff8e520aa8548cba06be3d181fc0f7d"
}

ok

curl http://localhost:8080/testException?data=11 -v
*   Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /testException?data=11 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.51.0
> Accept: */*
>
< HTTP/1.1 200
< Content-Type: application/json;charset=UTF-8
< Transfer-Encoding: chunked
< Date: Mon, 27 Aug 2018 11:01:41 GMT
<
* Curl_http_done: called premature == 0
* Connection #0 to host localhost left intact
{
    "code": "ok",
    "requestid": "8e5db7548fc34f5c95420b5ea23e9893"
}

在开发时,希望后台能够返回完整错误栈这样方便后台人员排查问题,可以在application.properties加入以下配置

spring.mpaas.mode=DEV
$curl http://localhost:8080/testException?data=a
{
    "code": "error",
    "message": "com.definesys.mpaas.common.exception.MpaasRuntimeException: java.lang.NumberFormatException: For input string: \"a\"\ncom.smec.remes.auto.controller.FastRepairController.testException(FastRepairController.java:50)\n
    ....
}

如果是运行时错误系统默认返回的错误信息为系统出错请联系管理员如果想更改该信息,可以在application.properties加入以下配置

spring.mpaas.mode=PROD
spring.mpaas.errormsg=提示信息的unnicode编码

如果是中文需要转成unicode编码,可以在http://tool.chinaz.com/tools/unicode.aspx这里进行转码.如想更改为系统出错请稍后再试转码之后配置

spring.mpaas.mode=PROD
spring.mpaas.errormsg=\u7cfb\u7edf\u51fa\u9519\u8bf7\u7a0d\u540e\u518d\u8bd5
$curl http://localhost:8080/testException?data=a
{
    "code": "error",
    "message": "系统出错请联系管理员",
    "requestid": "27c5ead8fa4a49e1b5cd44cc55ce130e"
}

DQuery
300 声望93 粉丝

幸福是奋斗出来的