雪花算法,返回 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;
}
}