ID 的生成, 返回 JSON 等工具類

1. 簡介

做 Spring Cloud + Vue 前後端分離技術中, 後端需要返回 JSON 數據, 這是需要工具類, 拋出異常也需要工具類, ID 的生成也需要工具類.

2. ID 的生成

這裏用 雪花算法

2.1 工具類

package com.springCloud.common.util;

import lombok.Data;

/**
 * Snowflake algorithm, an open-source distributed ID generation algorithm of Twitter.
 */

@Data
public class IdWorker {

    /* Because the first bit in binary is negative if it is 1, but the IDS we generate are all positive, so the first bit is 0. */

    // 機器ID  2進制5位  32位減掉1位 31個
    private long workerId;
    // 機房ID 2進制5位  32位減掉1位 31個
    private long dataCenterId;
    // 代表一毫秒內生成的多個id的最新序號  12位 4096 -1 = 4095 個
    private long sequence;
    // 設置一個時間初始值    2^41 - 1   差不多可以用69年
    private long timeInit = 1585644268888L;
    // 5位的機器id
    private long workerIdBits = 5L;
    // 5位的機房id
    private long dataCenterIdBits = 5L;
    // 每毫秒內產生的id數 2 的 12次方
    private long sequenceBits = 12L;
    // 這個是二進制運算,就是5 bit最多隻能有31個數字,也就是說機器id最多隻能是32以內
    private long maxWorkerId = ~(-1L << workerIdBits);
    // 這個是一個意思,就是5 bit最多隻能有31個數字,機房id最多隻能是32以內
    private long maxDataCenterId = ~(-1L << dataCenterIdBits);

    private long workerIdShift = sequenceBits;
    private long dataCenterIdShift = sequenceBits + workerIdBits;
    private long timestampLeftShift = sequenceBits + workerIdBits + dataCenterIdBits;
    private long sequenceMask = ~(-1L << sequenceBits);
    // 記錄產生時間毫秒數,判斷是否是同1毫秒
    private long lastTimestamp = -1L;

    public IdWorker(long workerId, long dataCenterId, long sequence) {
        // 檢查機房id和機器id是否超過31 不能小於0
        if (workerId > maxWorkerId || workerId < 0) {
            throw new IllegalArgumentException(
                    String.format("worker Id can't be greater than %d or less than 0", maxWorkerId));
        }

        if (dataCenterId > maxDataCenterId || dataCenterId < 0) {
            throw new IllegalArgumentException(
                    String.format("dataCenter Id can't be greater than %d or less than 0", maxDataCenterId));
        }
        this.workerId = workerId;
        this.dataCenterId = dataCenterId;
        this.sequence = sequence;
    }

    // 這個是核心方法,通過調用 nextId() 方法,讓當前這臺機器上的 snowflake 算法程序生成一個全局唯一的id
    public synchronized long nextId() {
        // 這兒就是獲取當前時間戳,單位是毫秒
        long timestamp = timeGen();
        if (timestamp < lastTimestamp) {
            System.err.printf(
                    "clock is moving backwards. Rejecting requests until %d.", lastTimestamp);
            throw new RuntimeException(
                    String.format("Clock moved backwards. Refusing to generate id for %d milliseconds",
                            lastTimestamp - timestamp));
        }

        // 下面是說假設在同一個毫秒內,又發送了一個請求生成一個id
        // 這個時候就得把 sequence 序號給遞增1,最多就是 4096
        if (lastTimestamp == timestamp) {
            // 這個意思是說一個毫秒內最多隻能有4096個數字,無論你傳遞多少進來,
            //這個位運算保證始終就是在4096這個範圍內,避免你自己傳遞個sequence超過了4096這個範圍
            sequence = (sequence + 1) & sequenceMask;
            //當某一毫秒的時間,產生的id數 超過4095,系統會進入等待,直到下一毫秒,系統繼續產生ID
            if (sequence == 0) {
                timestamp = tilNextMillis(lastTimestamp);
            }
        } else {
            sequence = 0;
        }
        // 這兒記錄一下最近一次生成id的時間戳,單位是毫秒
        lastTimestamp = timestamp;
        // 這兒就是最核心的二進制位運算操作,生成一個64bit的id
        // 先將當前時間戳左移,放到41 bit那兒;將機房id左移放到5 bit那兒;將機器id左移放到5 bit那兒;將序號放最後12 bit
        // 最後拼接起來成一個64 bit的二進制數字,轉換成10進制就是個long型
        return ((timestamp - timeInit) << timestampLeftShift) |
                (dataCenterId << dataCenterIdShift) |
                (workerId << workerIdShift) | sequence;
    }

    /**
     * 當某一毫秒的時間,產生的id數 超過4095,系統會進入等待,直到下一毫秒,系統繼續產生ID
     *
     * @param lastTimestamp lastTimestamp
     * @return long
     */
    private long tilNextMillis(long lastTimestamp) {
        long timestamp = timeGen();
        while (timestamp <= lastTimestamp) {
            timestamp = timeGen();
        }
        return timestamp;
    }

    //獲取當前時間戳
    private long timeGen() {
        return System.currentTimeMillis();
    }

    /**
     * main 測試類
     *
     * @param args args
     */
    public static void main(String[] args) {
        System.out.println(1 & 4596);
        System.out.println(2 & 4596);
        System.out.println(6 & 4596);
        System.out.println(6 & 4596);
        System.out.println(6 & 4596);
        System.out.println(6 & 4596);
//		IdWorker worker = new IdWorker(1,1,1);
//		for (int i = 0; i < 22; i++) {
//			System.out.println(worker.nextId());
//		}
    }
}


2.2 使用

package com.springCloud.user.config.idWoker;

import com.springCloud.common.util.IdWorker;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class UserIdWorker {

    @Bean
    public IdWorker idWorker() {
        return new IdWorker(1, 1, 1);
    }


}


	......
    // 創建 IdWorker 對象 idWorker.
    private IdWorker idWorker;
	......

    /**
     * 必須有構造函數
     */
    public UserServiceImpl() {
    }

    /**
     * 獲取容器對象
     *
     * @param userDao  識別 userDao 容器對象
     * @param idWorker 識別 idWorker 容器對象
     */
    @Autowired
    private UserServiceImpl(......
							IdWorker idWorker
							......) {
		......
        this.idWorker = idWorker;
		......
    }
	......
        // 隨機生成 id 號 (雪花算法)
        String id = String.valueOf(idWorker.nextId());
	......

3. 返回類

返回的工具類

package com.springCloud.common.entity;

import lombok.*;

import java.io.Serializable;

@AllArgsConstructor
@NoArgsConstructor
@ToString
@Data
public class Result implements Serializable {

    private Integer code;
    private boolean flag;
    private String message;
    private Object data;

    public Result(Integer code, boolean flag, String message) {
        this.code = code;
        this.flag = flag;
        this.message = message;
    }

}

分頁的工具類

package com.springCloud.common.entity;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.Serializable;
import java.util.List;

/**
 * 換回分頁數據的信息:
 * PageResult<T> 返回類型
 * total: 數據的總數.
 * pageSize: 分頁的頁數.
 * data: 當前分頁的數據.
 * @param <T>
 */

@AllArgsConstructor
@NoArgsConstructor
@Data
public class PageResult<T> implements Serializable {

    private long total;
    private Integer pageSize;
    private List<T> data;

}

自定義狀態碼

package com.springCloud.common.entity;

import java.io.Serializable;

public class StatusCode implements Serializable {
    public static final int OK = 20000; //成功
    public static final int ERROR = 20001; //失敗
    public static final int LOGIN_ERROR = 20002; //用戶名或密碼錯誤
    public static final int ACCESS_ERROR = 20003; //權限不足
    public static final int REMOTE_ERROR = 20004; //遠程調用失敗
    public static final int REP_ERROR = 20005; //重複操作

}

使用

return new Result(StatusCode.OK, true, "查詢成功", userService.findById(id));

4. 異常

package com.springCloud.user.config.error;

import com.springCloud.common.entity.Result;
import com.springCloud.common.entity.StatusCode;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * 定製 springCloud_user 的錯誤頁面
 */

@RestControllerAdvice
public class UserExceptionHandler {

    /**
     * 定義攔截錯誤頁面的信息
     * @param e 錯誤信息對象
     * @return Result
     */
    @ExceptionHandler(value = Exception.class)
    public Result exceptionHandler(Exception e) {
        return new Result(StatusCode.ERROR, false, e.getMessage());
    }

}

捕獲 404 異常需要加上下面的配置

spring:
  mvc:
    throw-exception-if-no-handler-found: true
  resources:
    add-mappings: false

5. 得到 Spring 容器中的 Bean

5.1 工具類

package com.springCloud.common.util;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.lang.Nullable;

/**
 * 獲取 Spring 中 bean
 */
public class SpringUtil implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(@Nullable ApplicationContext applicationContext) throws BeansException {
        if (SpringUtil.applicationContext == null) {
            SpringUtil.applicationContext = applicationContext;
        }
        System.out.println("========ApplicationContext 配置成功,在普通類可以通過調用 SpringUtil.getAppContext() 獲取 applicationContext 對象, applicationContext=" + SpringUtil.applicationContext + "========");
    }

    // 獲取 applicationContext
    private static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    // 通過 name 獲取 Bean.
    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    // 通過 class 獲取 Bean.
    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    // 通過 name, 以及 Class 返回指定的 Bean
    public static <T> T getBean(String name, Class<T> clazz) {
        return getApplicationContext().getBean(name, clazz);
    }

}

5.2 使用

使用過程和 ID 的生成 的一樣, 需要將該類加入 Bean.

6. JSON 與 POJO 類對象之間的轉化

package com.springCloud.common.util;

import java.util.List;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * 自定義響應結構, 轉換類
 */
public class JsonUtils {

    // 定義 jackson 對象
    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     * 將對象轉換成json字符串。
     * <p>Title: pojoToJson</p>
     * <p>Description: </p>
     *
     * @param data data
     * @return String
     */
    public static String objectToJson(Object data) {
        try {
            return MAPPER.writeValueAsString(data);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * @param jsonData json數據
     * @param beanType 對象中的 object 類型
     * @param <T>      T
     * @return <T>
     */
    public static <T> T jsonToPojo(String jsonData, Class<T> beanType) {
        try {
            return MAPPER.readValue(jsonData, beanType);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 將 json 數據轉換成 pojo 對象 list
     * <p>Title: jsonToList</p>
     * <p>Description: </p>
     *
     * @param jsonData json數據
     * @param beanType 對象中的 object 類型
     * @return <T>List<T>
     */
    public static <T> List<T> jsonToList(String jsonData, Class<T> beanType) {
        JavaType javaType = MAPPER.getTypeFactory().constructParametricType(List.class, beanType);
        try {
            return MAPPER.readValue(jsonData, javaType);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return null;
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章