关于java:lombok依赖和热部署SpringBoot-工程的健康监控实现工程中的异常处理方式工程中的响应标准设计及实现

3次阅读

共计 5090 个字符,预计需要花费 13 分钟才能阅读完成。

lombok

增加 lombok 依赖。

<dependency>
   <groupId>org.projectlombok</groupId>
   <artifactId>lombok</artifactId>
   <scope>annotationProcessor</scope>
</dependency>

lombok 作用:注解减少 getset 办法等等
很不便,不必本人导 getsettostring 办法
如:

@Data 
@NoArgsConstructor 
@AllArgsConstructor 
public class Goods {
    private Long id;
    private String name;
    private String remark;
    private Date createdTime;
}

热部署

在须要热部署的我的项目或 module 中增加如下依赖:

<dependency>
   <groupId>org.springframework.boot</groupId>
   <artifactId>spring-boot-devtools</artifactId>
   <scope>runtime</scope>
</dependency>

热部署占内存多,改一次重启一次

SpringBoot 工程的衰弱监控

Spring Boot 中 actuator 模块提供了健康检查,审计、指标收集,HTTP 跟踪等性能,能够帮忙咱们更好的治理和跟踪 springboot 我的项目。

在须要应用衰弱监控的我的项目或 module 中,增加如下依赖:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

启动我的项目, 在浏览器中输出如下地址:(SpringBoot 默认关上的监控选项无限)

http://localhost/actuator

还能够在 actuator 列出的选中中进行点击, 例如拜访 health

http://localhost/actuator/health

如果心愿查看更多 actuator 选项,能够在 spring boot 中配置文件

application.properties 中增加如下语句:

management.endpoints.web.exposure.include=*

而后, 重启服务器, 基于拜访 http://localhost/actuator 地址)

SpringBoot 工程中的异样解决形式

咱们在解决异样的过程中通常要遵循肯定的设计规范,例如:

  • 捕捉异样时与抛出的异样必须齐全匹配,或者捕捉异样是抛出异样的父类类型。
  • 防止间接抛出 RuntimeException, 更不容许抛出 Exception 或者 Throwable, 应应用有业务含意的自定义异样(例如 ServiceException)。
  • 捕捉异样后必须进行解决(例如记录日志)。如果不想解决它,须要将异样抛给它的调用者。
  • 最外层的逻辑必须解决异样,将其转化成用户能够了解的内容。
  • 避免出现反复的代码(Don’t Repeat Yourself), 即 DAY 准则。

创立我的项目或 module,并增加 web 依赖,代码如下:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>

批改我的项目拜访端口为 80,例如

server.port=80

定义 Controller 类,代码如下:

package com.cy.pj.arithmetic.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class ArithmeticController {@RequestMapping("doCompute/{n1}/{n2}")
  @ResponseBody
  public String doCompute(@PathVariable  Integer n1, 
  @PathVariable Integer n2){
          Integer result=n1/n2;
          return "Result is"+result;
  }
}

启动我的项目进行拜访测试

在浏览器地址栏输出 http://localhost/doCompute/10/2,检测输入后果。

Result is 5

默认异样解决

在浏览器地址栏输出 http://localhost/doCompute/10/0,检测输入后果。

对于这样的默认异样解决(spring boot 提供),用户体验不太敌对,为了出现更加敌对的异样信息,咱们通常要对异样进行自定义解决。

本人 try 异样解决

在管制层办法中,咱们能够进行 try catch 解决,例如:

 @RequestMapping("doCompute/{n1}/{n2}")
  @ResponseBody
  public String doCompute(@PathVariable  Integer n1, 
  @PathVariable Integer n2){
          try{
          Integer result=n1/n2;
          return "Result is"+result;
          }catch(ArithmeticException e){return "exception is"+e.getMessage();
          }
  } 

一个 Controller 类中通常会有多个办法,这样多个办法中都写 try 语句进行异样解决会带来大量反复代码的编写,不易保护。

Controller 外部定义异样解决办法

在 Controller 类中增加异样解决办法,代码如下:

@ExceptionHandler(ArithmeticException.class)
@ResponseBody
public String doHandleArithmeticException(ArithmeticException e){e.printStackTrace();
    return "计算过程中呈现了异样,异样信息为"+e.getMessage();}

@ExceptionHandler 注解形容的办法为异样解决办法(注解中的异样类型为可解决的异样类型),如果 Controller 类中的逻辑办法中出现异常后没有解决异样,则会查找 Controller 类中有没有定义异样解决办法,如果定义了,且能够解决抛出的异样类型,则由异样解决办法解决异样。

管制层中的全局异样解决类及办法定义

当我的项目由多个管制层类中有多个共性异样的解决办法定义时,咱们能够将这些办法提取到公共的父类对象中,然而这种形式是一种强耦合的实现,不利于代码的保护。咱们还能够借助 spring 框架中 web 模块定义的全局异样解决标准进行实现,例如定义全局异样解决类, 代码如下:

package com.cy.pj.common.web;

@RestControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(ArithmeticException.class)
    public String doHandleArithmeticException(ArithmeticException e){e.printStackTrace();
        return  "计算过程中呈现了异样,异样信息为"+e.getMessage();}
} 

其中,@RestControllerAdvice 注解形容的类为全局异样解决类,当管制层办法中的异样没有本人捕捉, 也没有定义其外部的异样解决办法,底层默认会查找全局异样解决类,调用对应的异样解决办法进行异样解决。

工程中的响应规范设计及实现

响应规范设计

/**
 * 基于此对象封装服务端响应到客户端的数据
 */
public class ResponseResult {/** 响应状态码(有的人用 code)*/
    private Integer state=1;// 1 示意 ok,0 示意 error,.....
    /** 状态码对应的信息 */
    private String message="ok";
    /** 正确的响应数据 */
    private Object data;

    public ResponseResult(){}

    public ResponseResult(String message){//new ResponseResult("delete ok"),
        this.message=message;
    }
    public ResponseResult(Object data){//new ResponseResult(list);
        this.data=data;
    }
    public ResponseResult(Throwable e){//new ResponseResult(e);
        this.state=0;
        this.message=e.getMessage();}

    public Integer getState() {return state;}

    public void setState(Integer state) {this.state = state;}

    public String getMessage() {return message;}

    public void setMessage(String message) {this.message = message;}

    public Object getData() {return data;}

    public void setData(Object data) {this.data = data;}
}

响应数据的封装

import com.cy.pj.common.pojo.ResponseResult;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ArithmeticController {@RequestMapping("/doCompute/{n1}/{n2}")
      public ResponseResult doCompute(@PathVariable  Integer n1, @PathVariable Integer n2){
          Integer result=n1/n2;
          ResponseResult r=new ResponseResult("计算结果:"+result);
          r.setData(result);
          return r;
      }
}

在全局异样解决对象中进行异样响应数据的封装,例如:

import com.cy.pj.common.pojo.ResponseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@RestControllerAdvice
public class GlobalExceptionHandler {private static final Logger log= LoggerFactory.getLogger(GlobalExceptionHandler.class);//2
      @ExceptionHandler(ArithmeticException.class)
      public ResponseResult doHandleArithmeticException(ArithmeticException e){e.printStackTrace();
          log.info("exception {}",e.getMessage());
          return new ResponseResult(e);// 封装异样后果
      }
}

完结

正文完
 0