搭建一個Java專案可直接拿去使用的通用工具類

自律即自由-發表於2024-03-09

1、通用列舉類

import lombok.Getter;

/**
 * @Description 狀態碼定義約束,共6位數,前三位代表服務,後3位代表介面
 * 比如 商品服務210,購物車是220、使用者服務230,403代表許可權
 **/
public enum BizCodeEnum {


    /**
     * 短鏈分組
     */
    GROUP_REPEAT(23001, "分組名重複"),
    GROUP_OPER_FAIL(23503, "分組名操作失敗"),
    GROUP_NOT_EXIST(23404, "分組不存在"),


    /**
     * 驗證碼
     */
    CODE_TO_ERROR(240001, "接收號碼不合規"),
    CODE_LIMITED(240002, "驗證碼傳送過快"),
    CODE_ERROR(240003, "驗證碼錯誤"),
    CODE_CAPTCHA_ERROR(240101, "圖形驗證碼錯誤"),


    /**
     * 賬號
     */
    ACCOUNT_REPEAT(250001, "賬號已經存在"),
    ACCOUNT_UNREGISTER(250002, "賬號不存在"),
    ACCOUNT_PWD_ERROR(250003, "賬號或者密碼錯誤"),
    ACCOUNT_UNLOGIN(250004, "賬號未登入"),


    /**
     * 短鏈
     */
    SHORT_LINK_NOT_EXIST(260404, "短鏈不存在"),


    /**
     * 訂單
     */
    ORDER_CONFIRM_PRICE_FAIL(280002, "建立訂單-驗價失敗"),
    ORDER_CONFIRM_REPEAT(280008, "訂單惡意-重複提交"),
    ORDER_CONFIRM_TOKEN_EQUAL_FAIL(280009, "訂單令牌缺少"),
    ORDER_CONFIRM_NOT_EXIST(280010, "訂單不存在"),

    /**
     * 支付
     */
    PAY_ORDER_FAIL(300001, "建立支付訂單失敗"),
    PAY_ORDER_CALLBACK_SIGN_FAIL(300002, "支付訂單回撥驗證籤失敗"),
    PAY_ORDER_CALLBACK_NOT_SUCCESS(300003, "支付寶回撥更新訂單失敗"),
    PAY_ORDER_NOT_EXIST(300005, "訂單不存在"),
    PAY_ORDER_STATE_ERROR(300006, "訂單狀態不正常"),
    PAY_ORDER_PAY_TIMEOUT(300007, "訂單支付超時"),


    /**
     * 流控操作
     */
    CONTROL_FLOW(500101, "限流控制"),
    CONTROL_DEGRADE(500201, "降級控制"),
    CONTROL_AUTH(500301, "認證控制"),


    /**
     * 流量包操作
     */
    TRAFFIC_FREE_NOT_EXIST(600101, "免費流量包不存在,聯絡客服"),

    TRAFFIC_REDUCE_FAIL(600102, "流量不足,扣減失敗"),

    TRAFFIC_EXCEPTION(600103, "流量包資料異常,使用者無流量包"),


    /**
     * 通用操作碼
     */

    OPS_REPEAT(110001, "重複操作"),
    OPS_NETWORK_ADDRESS_ERROR(110002, "網路地址錯誤"),


    /**
     * 檔案相關
     */
    FILE_UPLOAD_USER_IMG_FAIL(700101, "使用者頭像檔案上傳失敗");

    @Getter
    private String message;

    @Getter
    private int code;

    private BizCodeEnum(int code, String message) {
        this.code = code;
        this.message = message;
    }
}


全域性異常類

import lombok.Data;
import net.xdclass.enums.BizCodeEnum;

@Data
public class BizException extends RuntimeException {

    private int code;

    private String msg;

    public BizException(Integer code, String message) {
        super(message);
        this.code = code;
        this.msg = message;
    }

    public BizException(BizCodeEnum bizCodeEnum) {
        super(bizCodeEnum.getMessage());
        this.code = bizCodeEnum.getCode();
        this.msg = bizCodeEnum.getMessage();
    }
}

自定義異常處理器

import lombok.extern.slf4j.Slf4j;
import net.xdclass.utils.JsonData;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * 自定義異常處理器
 */
@ControllerAdvice
@Slf4j
public class CustomExceptionHandler {

    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public JsonData handler(Exception e) {
        if (e instanceof BizException) {
            BizException bizException = (BizException) e;
            log.error("[業務異常]{}",e);
            return JsonData.buildCodeAndMsg(bizException.getCode(),bizException.getMsg());
        }else {
            log.error("[系統異常]{}",e);
            return JsonData.buildError("系統異常");
        }
    }
}

2、通用工具類

import lombok.extern.slf4j.Slf4j;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.util.*;


@Slf4j
public class CommonUtil {
    /**
     * 獲取ip
     *
     * @param request
     * @return
     */
    public static String getIpAddr(HttpServletRequest request) {
        String ipAddress = null;
        try {
            ipAddress = request.getHeader("x-forwarded-for");
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getHeader("WL-Proxy-Client-IP");
            }
            if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
                ipAddress = request.getRemoteAddr();
                if (ipAddress.equals("127.0.0.1")) {
                    // 根據網路卡取本機配置的IP
                    InetAddress inet = null;
                    try {
                        inet = InetAddress.getLocalHost();
                    } catch (UnknownHostException e) {
                        e.printStackTrace();
                    }
                    ipAddress = inet.getHostAddress();
                }
            }
            // 對於透過多個代理的情況,第一個IP為客戶端真實IP,多個IP按照','分割
            if (ipAddress != null && ipAddress.length() > 15) {
                // "***.***.***.***".length()
                // = 15
                if (ipAddress.indexOf(",") > 0) {
                    ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
                }
            }
        } catch (Exception e) {
            ipAddress = "";
        }
        return ipAddress;
    }


    /**
     * 獲取全部請求頭
     *
     * @param request
     * @return
     */
    public static Map<String, String> getAllRequestHeader(HttpServletRequest request) {
        Enumeration<String> headerNames = request.getHeaderNames();
        Map<String, String> map = new HashMap<>();
        while (headerNames.hasMoreElements()) {
            String key = (String) headerNames.nextElement();
            //根據名稱獲取請求頭的值
            String value = request.getHeader(key);
            map.put(key, value);
        }

        return map;
    }


    /**
     * MD5加密
     *
     * @param data
     * @return
     */
    public static String MD5(String data) {
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            byte[] array = md.digest(data.getBytes("UTF-8"));
            StringBuilder sb = new StringBuilder();
            for (byte item : array) {
                sb.append(Integer.toHexString((item & 0xFF) | 0x100).substring(1, 3));
            }

            return sb.toString().toUpperCase();
        } catch (Exception exception) {
        }
        return null;

    }


    /**
     * 獲取驗證碼隨機數
     *
     * @param length
     * @return
     */
    public static String getRandomCode(int length) {

        String sources = "0123456789";
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int j = 0; j < length; j++) {
            sb.append(sources.charAt(random.nextInt(9)));
        }
        return sb.toString();
    }


    /**
     * 獲取當前時間戳
     *
     * @return
     */
    public static long getCurrentTimestamp() {
        return System.currentTimeMillis();
    }


    /**
     * 生成uuid
     *
     * @return
     */
    public static String generateUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").substring(0, 32);
    }

    /**
     * 獲取隨機長度的串
     *
     * @param length
     * @return
     */
    private static final String ALL_CHAR_NUM = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";

    public static String getStringNumRandom(int length) {
        //生成隨機數字和字母,
        Random random = new Random();
        StringBuilder saltString = new StringBuilder(length);
        for (int i = 1; i <= length; ++i) {
            saltString.append(ALL_CHAR_NUM.charAt(random.nextInt(ALL_CHAR_NUM.length())));
        }
        return saltString.toString();
    }


    /**
     * 響應json資料給前端
     *
     * @param response
     * @param obj
     */
    public static void sendJsonMessage(HttpServletResponse response, Object obj) {

        response.setContentType("application/json; charset=utf-8");

        try (PrintWriter writer = response.getWriter()) {
            writer.print(JsonUtil.obj2Json(obj));
            response.flushBuffer();

        } catch (IOException e) {
            log.warn("響應json資料給前端異常:{}", e);
        }


    }

}

3、Json格式轉換

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import lombok.extern.slf4j.Slf4j;

import java.text.SimpleDateFormat;
import java.util.List;


@Slf4j
public class JsonUtil {


    private static final ObjectMapper mapper = new ObjectMapper();

    static {

        //設定可用單引號
        mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);

        //序列化的時候序列物件的所有屬性
        mapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);

        //反序列化的時候如果多了其他屬性,不丟擲異常
        mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        //如果是空物件的時候,不拋異常
        mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);

        //取消時間的轉化格式,預設是時間戳,可以取消,同時需要設定要表現的時間格式
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        mapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
    }



    /**
     * 物件轉為Json字串
     * @param data
     * @return
     */
    public static String obj2Json(Object obj) {
        String jsonStr = null;
        try {
            jsonStr = mapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            //e.printStackTrace();
            log.error("json格式化異常:{}",e);
        }
        return jsonStr;
    }
    /**
     * json字串轉為物件
     * @param str
     * @param valueType
     * @return
     */
    public static <T> T json2Obj(String jsonStr, Class<T> beanType) {
        T obj = null;
        try {
            obj = mapper.readValue(jsonStr, beanType);
        } catch (Exception e){
            //e.printStackTrace();
            log.error("json格式化異常:{}",e);
        }
        return obj;
    }


    /**
     * json資料轉換成pojo物件list
     * @param jsonData
     * @param beanType
     * @return
     */
    public static <T> List<T> json2List(String jsonData, Class<T> beanType) {
        JavaType javaType = mapper.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            List<T> list = mapper.readValue(jsonData, javaType);
            return list;
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("json格式化異常:{}",e);
        }
        return null;
    }

    /**
     * 物件轉為byte陣列
     * @param data
     * @return
     */
    public static byte[] obj2Bytes(Object obj) {
        byte[] byteArr = null;
        try {
            byteArr = mapper.writeValueAsBytes(obj);
        } catch (JsonProcessingException e) {
            //e.printStackTrace();
            log.error("json格式化異常:{}",e);
        }
        return byteArr;
    }



    /**
     * byte陣列轉為物件
     * @param byteArr
     * @param valueType
     * @return
     */
    public static <T> T bytes2Obj(byte[] byteArr, Class<T> beanType) {
        T obj = null;
        try {
            obj = mapper.readValue(byteArr, beanType);
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("json格式化異常:{}",e);
        }
        return obj;
    }
}

4、時間工具類

package net.xdclass.utils;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.Date;


public class TimeUtil {

    /**
     * 預設日期格式
     */
    private static final String DEFAULT_PATTERN = "yyyy-MM-dd HH:mm:ss";

    /**
     * 預設日期格式
     */
    private static final DateTimeFormatter DEFAULT_DATE_TIME_FORMATTER  = DateTimeFormatter.ofPattern(DEFAULT_PATTERN);

    private static final ZoneId DEFAULT_ZONE_ID = ZoneId.systemDefault();


    /**
     * LocalDateTime 轉 字串,指定日期格式
     * @param time
     * @param pattern
     * @return
     */
    public static String format(LocalDateTime localDateTime, String pattern){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        String timeStr = formatter.format(localDateTime.atZone(DEFAULT_ZONE_ID));
        return timeStr;
    }


    /**
     * Date 轉 字串, 指定日期格式
     * @param time
     * @param pattern
     * @return
     */
    public static String format(Date time, String pattern){
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern(pattern);
        String timeStr = formatter.format(time.toInstant().atZone(DEFAULT_ZONE_ID));
        return timeStr;
    }

    /**
     *  Date 轉 字串,預設日期格式
     * @param time
     * @return
     */
    public static String format(Date time){

        String timeStr = DEFAULT_DATE_TIME_FORMATTER.format(time.toInstant().atZone(DEFAULT_ZONE_ID));
        return timeStr;
    }

    /**
     * timestamp 轉 字串,預設日期格式
     *
     * @param time
     * @return
     */
    public static String format(long timestamp) {
        String timeStr = DEFAULT_DATE_TIME_FORMATTER.format(new Date(timestamp).toInstant().atZone(DEFAULT_ZONE_ID));
        return timeStr;
    }


    /**
     * 字串 轉 Date
     *
     * @param time
     * @return
     */
    public static Date strToDate(String time) {
        LocalDateTime localDateTime = LocalDateTime.parse(time, DEFAULT_DATE_TIME_FORMATTER);
        return Date.from(localDateTime.atZone(DEFAULT_ZONE_ID).toInstant());

    }


    /**
     * 獲取當天剩餘的秒數,用於流量包過期配置
     * @param currentDate
     * @return
     */
    public static Integer getRemainSecondsOneDay(Date currentDate) {
        LocalDateTime midnight = LocalDateTime.ofInstant(currentDate.toInstant(),
                        ZoneId.systemDefault()).plusDays(1).withHour(0).withMinute(0)
                .withSecond(0).withNano(0);

        LocalDateTime currentDateTime = LocalDateTime.ofInstant(currentDate.toInstant(),
                ZoneId.systemDefault());
        long seconds = ChronoUnit.SECONDS.between(currentDateTime, midnight);
        return (int) seconds;
    }
}

相關文章