常用实用代码

1.swagger配置

@Configuration
@EnableSwagger2
public class SwaggerConfig {
	
	@Value("${swagger.enable}")
	private boolean enableSwagger;
	@Value("${info.version}")
	private String version;
	
    @Bean
    public Docket createRestApi() {
        return new Docket(DocumentationType.SWAGGER_2)
                .apiInfo(apiInfo())
                .enable(enableSwagger)
                .select()
                .apis(RequestHandlerSelectors.basePackage("com.cet.datacenter.controller"))
                .paths(PathSelectors.any())
                .build();
    }

    private ApiInfo apiInfo() {
        return new ApiInfoBuilder()
                .title("定制版服务接口定义说明")
                .description("主要是提供数定制版业务功能。")
                .version(version)
                .build();
    }
}

2.统一异常处理和接口参数返回处理

public class APIException extends RuntimeException{
    private int code;
    private String msg;

    public APIException(int code, String msg) {
        super(msg);
        this.code = code;
        this.msg = msg;
    }

    public APIException() {
        this(BaseRTC.EXCEPTION, "接口异常");
    }
    public APIException(int code) {
        this.code = code;
    }

    public APIException(String msg) {
        this(BaseRTC.EXCEPTION, msg);
    }
}
----------------------------------------------------------------------




-------------------------------------------------------------------------
//统一异常处理
@RestControllerAdvice
@Slf4j
public abstract class BaseController {

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public Result methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        return new Result(BaseRTC.PARAM_ERROR, objectError.getDefaultMessage(),null);
    }

    @ExceptionHandler(APIException.class)
    public Result apiExecptionHandler(APIException e) {
        return new Result(e.getCode(), e.getMsg(), null);
    }

    @ExceptionHandler(Exception.class)
    public Result runExecptionHandler(Exception e) {
        Result result = new Result(BaseRTC.EXCEPTION, e.getMessage(), e.getCause().toString());
        return result;
    }
}


--------------------------------------------------------------------------
//接口返回参数处理
@RestControllerAdvice(basePackages = {"com.cet.datacenter.controller"})
@Slf4j
public class ResponseAdvice implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        // 如果接口返回的类型本身就是Result那就没必要进行额外的操作,返回false
        Type genericParameterType = methodParameter.getGenericParameterType();
        boolean isSuport = genericParameterType.getTypeName().startsWith("com.cet.datacenter.base.Result") || genericParameterType.getTypeName().startsWith("com.cet.datacenter.base.BaseVO");
        return !isSuport;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {

        Type genericParameterType = methodParameter.getGenericParameterType();
        String typeName = genericParameterType.getTypeName();
        // String类型不能直接包装,需特殊处理
        if (typeName.equals(String.class.getTypeName())) {
            ObjectMapper objectMapper = new ObjectMapper();
            try {
                // 转换成规定的类型
                return objectMapper.writeValueAsString(new Result(o));
            } catch (JsonProcessingException e) {
                log.error(e.getMessage(), e);
                throw new APIException("返回String类型错误");
            }
        } else if (typeName.startsWith(List.class.getTypeName())) {
            return new Result<>(o);
        } else if (typeName.startsWith(Map.class.getTypeName())) {
            return new Result<>(o);
        }

        if(o == null){
            return new Result();
        }

        return new Result<>(o);
    }
}

 3.统一接口返回Result

@Data
public class Result<T> {
    private int code;
    private String msg;
    private T data;
    private int total = 0;

    public Result() {
        this.code = BaseRTC.SUCCESS;
        this.msg = "success";
    }

    public Result(T data) {
        this.code = BaseRTC.SUCCESS;
        this.msg = "success";
        this.data = data;
    }

    public Result(T data, int total) {
        this.code = BaseRTC.SUCCESS;
        this.msg = "success";
        this.data = data;
        this.total = total;
    }

    public Result(int code, String msg, T data) {
        this.code = code;
        this.msg = msg;
        this.data = data;
    }

    public Result(int code, String msg, T data, int total) {
        this.code = code;
        this.msg = msg;
        this.data = data;
        this.total = total;
    }

    /**
     * 判断是否请求返回成功
     * @param code 结果code码
     * @return
     */
    public static boolean checkResultSuccessCode(int code) {
        if (code == BaseRTC.SUCCESS) {
            return true;
        }
        return false;
    }

    /**
     * 返回异常结果
     * @param code 结果code码
     * @return
     */
    public static Result error(int code, String msg) {
        return new Result(code,msg,null);
    }

    public static void main(String[] args) {

    }
}

----------------------------------------------------------------------------------
  @ApiOperation(value = "按月查询充放电事件表格数据")
    @PostMapping(value = "/queryBatteryEventTableByMonth")
    public Result<List<Map<String, Object>>> queryBatteryEventTableByMonth(@RequestBody @ApiParam(name = "batteryStatisVo", value = "查询条件", required = true) BatteryStatisVo batteryStatisVo) {
        int index = 0, limit = 100;
        if (batteryStatisVo.getPage() != null) {
            index = batteryStatisVo.getPage().getIndex();
            limit = batteryStatisVo.getPage().getLimit();
        }
        Result<List<Map<String, Object>>> dataMapResult = batteryBusinessService.queryBatteryEventTableByMonth(batteryStatisVo.getYear(), batteryStatisVo.getMonth(), batteryStatisVo.getEventBytes(), index, limit);
        return dataMapResult;
    }

4.多线程应用


 CountDownLatch latch =  new CountDownLatch(graphStyleMap.size());
 graphStyleMap.forEach((statisticsObject,graphStyleType)->{
          executor.execute(()-> {
               try {
                     assembleStatisticsData(conditions,searchBO,countMap,statisticsObject,graphStyleType,eventChatQryBO);
                }finally {
                     latch.countDown();
                }
            });
        });
  latch.await();
  countMap.put("statisticsObjects", statisticsObjects);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值