lzy 2 tygodni temu
rodzic
commit
41123b2b9d

+ 5 - 0
pom.xml

@@ -35,6 +35,11 @@
             <artifactId>mybatis-spring-boot-starter</artifactId>
             <version>2.3.0</version>
         </dependency>
+        <dependency>
+            <groupId>io.jsonwebtoken</groupId>
+            <artifactId>jjwt</artifactId>
+            <version>0.9.0</version>
+        </dependency>
 
         <dependency>
             <groupId>com.mysql</groupId>

+ 64 - 0
src/main/java/com/zhentao/conment/RRException.java

@@ -0,0 +1,64 @@
+package com.zhentao.conment;
+
+/**
+ * 增强版业务异常类
+ * 包含错误码、错误信息、可选数据载荷
+ */
+public class RRException extends RuntimeException {
+
+
+    private final int code;
+    private final String msg;
+    private transient Object data; // transient避免序列化问题
+
+    // 常用构造方法
+    public RRException(int code, String msg) {
+        super(msg);
+        this.code = code;
+        this.msg = msg;
+    }
+
+    public RRException(int code, String msg, Object data) {
+        super(msg);
+        this.code = code;
+        this.msg = msg;
+        this.data = data;
+    }
+
+    public RRException(int code, String msg, Throwable cause) {
+        super(msg, cause);
+        this.code = code;
+        this.msg = msg;
+    }
+
+    // 快速创建异常的静态工厂方法
+    public static RRException of(int code, String msg) {
+        return new RRException(code, msg);
+    }
+
+    public static RRException of(int code, String msg, Object data) {
+        return new RRException(code, msg, data);
+    }
+
+    // Getter 方法
+    public int getCode() {
+        return code;
+    }
+
+    public String getMsg() {
+        return msg;
+    }
+
+    public Object getData() {
+        return data;
+    }
+
+    @Override
+    public String toString() {
+        return "RRException{" +
+                "code=" + code +
+                ", msg='" + msg + '\'' +
+                ", data=" + data +
+                '}';
+    }
+}

+ 73 - 0
src/main/java/com/zhentao/conment/SnowflakeIdWorker.java

@@ -0,0 +1,73 @@
+package com.zhentao.conment;
+
+import java.util.concurrent.atomic.AtomicLong;
+
+public class SnowflakeIdWorker {
+    // 时间起始标记点,作为基准,一般取系统的最近时间(一旦确定不能变动)
+    private final long twepoch = 1288834974657L;
+    // 机器标识位数
+    private final long workerIdBits = 5L;
+    // 数据标识位数
+    private final long datacenterIdBits = 5L;
+    // 支持的最大机器标识数
+    private final long maxWorkerId = -1L ^ (-1L << workerIdBits);
+    // 支持的最大数据标识数
+    private final long maxDatacenterId = -1L ^ (-1L << datacenterIdBits);
+    // 序列在id中占的位数
+    private final long sequenceBits = 12L;
+    // 机器ID向左移12位
+    private final long workerIdShift = sequenceBits;
+    // 数据标识符向左移17位(12+5)
+    private final long datacenterIdShift = sequenceBits + workerIdBits;
+    // 时间戳向左移22位(5+5+12)
+    private final long timestampLeftShift = sequenceBits + workerIdBits + datacenterIdBits;
+    private final long sequenceMask = -1L ^ (-1L << sequenceBits);
+    private long workerId;
+    private long datacenterId;
+    private long sequence = 0L;
+    private long lastTimestamp = -1L;
+    private final AtomicLong sequenceGenerator = new AtomicLong(0L);
+
+    public SnowflakeIdWorker(long workerId, long datacenterId) {
+        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;
+    }
+
+    public synchronized long nextId() {
+        long timestamp = timeGen();
+        if (timestamp < lastTimestamp) {
+            throw new RuntimeException(String.format("Clock moved backwards. Refusing to generate id for %d milliseconds", lastTimestamp - timestamp));
+        }
+        if (lastTimestamp == timestamp) {
+            sequence = (sequence + 1) & sequenceMask;
+            if (sequence == 0) {
+                timestamp = tilNextMillis(lastTimestamp);
+            }
+        } else {
+            sequence = 0L;
+        }
+        lastTimestamp = timestamp;
+        return ((timestamp - twepoch) << timestampLeftShift) |
+                (datacenterId << datacenterIdShift) |
+                (workerId << workerIdShift) |
+                sequence;
+    }
+
+    protected long tilNextMillis(long lastTimestamp) {
+        long timestamp = timeGen();
+        while (timestamp <= lastTimestamp) {
+            timestamp = timeGen();
+        }
+        return timestamp;
+    }
+
+    protected long timeGen() {
+        return System.currentTimeMillis();
+    }
+}

+ 113 - 0
src/main/java/com/zhentao/conment/TokenUtils.java

@@ -0,0 +1,113 @@
+package com.zhentao.conment;
+
+
+
+import io.jsonwebtoken.Claims;
+import io.jsonwebtoken.JwtBuilder;
+import io.jsonwebtoken.Jwts;
+import io.jsonwebtoken.SignatureAlgorithm;
+
+import javax.crypto.spec.SecretKeySpec;
+import javax.xml.bind.DatatypeConverter;
+import java.security.Key;
+import java.util.Date;
+
+/**
+ * 生成Token工具类
+ */
+public class TokenUtils {
+
+    /**
+     * 签名秘钥
+     */
+    public static final String SECRET = "cjyfutu1688";
+
+    /**
+     * 生成token
+     * @param id 一般传入userName
+     * @return
+     */
+    public static String createJwtToken(String id){
+        String issuer = "www.futureading.com";
+        String subject = "65532781@qq.com";
+        long ttlMillis = System.currentTimeMillis();
+        return createJwtToken(id, issuer, subject, ttlMillis);
+    }
+
+    /**
+     * 生成Token
+     *
+     * @param id
+     *            编号
+     * @param issuer
+     *            该JWT的签发者,是否使用是可选的
+     * @param subject
+     *            该JWT所面向的用户,是否使用是可选的;
+     * @param ttlMillis
+     *            签发时间
+     * @return token String
+     */
+    public static String createJwtToken(String id, String issuer, String subject, long ttlMillis) {
+
+        // 签名算法 ,将对token进行签名
+        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
+
+        // 生成签发时间
+        long nowMillis = System.currentTimeMillis();
+        Date now = new Date(nowMillis);
+
+        // 通过秘钥签名JWT
+        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(SECRET);
+        Key signingKey = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
+
+        // Let's set the JWT Claims
+        JwtBuilder builder = Jwts.builder().setId(id)
+                .setIssuedAt(now)
+                .setSubject(subject)
+                .setIssuer(issuer)
+                .signWith(signatureAlgorithm, signingKey);
+
+        // if it has been specified, let's add the expiration
+        if (ttlMillis >= 0) {
+            long expMillis = nowMillis + ttlMillis;
+            Date exp = new Date(expMillis);
+            builder.setExpiration(exp);
+        }
+
+        // Builds the JWT and serializes it to a compact, URL-safe string
+        return builder.compact();
+
+    }
+
+    // Sample method to validate and read the JWT
+    public static Claims parseJWT(String jwt) {
+        // This line will throw an exception if it is not a signed JWS (as expected)
+        Claims claims = Jwts.parser()
+                .setSigningKey(DatatypeConverter.parseBase64Binary(SECRET))
+                .parseClaimsJws(jwt).getBody();
+        return claims;
+    }
+
+    public static Long getUserId(String token){
+        Claims claims = null;
+        try {
+            claims = TokenUtils.parseJWT(token);
+        } catch (Exception e) {
+            throw new RRException(101, "token错误,请重新登录");
+        }
+
+        if(null==claims) {
+            throw new RRException(101, "token错误,请重新登录");
+        }
+        String id = claims.getId();
+        Long userId=Long.valueOf(id);
+
+        return userId;
+
+
+    }
+
+    public static void main(String[] args) {
+        System.out.println(TokenUtils.createJwtToken("admin"));
+    }
+}

+ 13 - 0
src/main/java/com/zhentao/fale/chang.java

@@ -0,0 +1,13 @@
+package com.zhentao.fale;
+
+public class chang {
+
+    private final Integer uid=1;
+    private final String name="张三";
+
+    private final String username="112";
+    private final String password="112";
+
+
+
+}

+ 9 - 1
src/main/java/com/zhentao/pojo/User.java

@@ -35,6 +35,8 @@ public class User implements Serializable {
      */
     private String sesseionkey;
 
+    private String username;
+    private String password;
     @TableField(exist = false)
     private static final long serialVersionUID = 1L;
 
@@ -53,7 +55,9 @@ public class User implements Serializable {
         return (this.getId() == null ? other.getId() == null : this.getId().equals(other.getId()))
             && (this.getOpenid() == null ? other.getOpenid() == null : this.getOpenid().equals(other.getOpenid()))
             && (this.getUnionid() == null ? other.getUnionid() == null : this.getUnionid().equals(other.getUnionid()))
-            && (this.getSesseionkey() == null ? other.getSesseionkey() == null : this.getSesseionkey().equals(other.getSesseionkey()));
+            && (this.getSesseionkey() == null ? other.getSesseionkey() == null : this.getSesseionkey().equals(other.getSesseionkey()))
+            && (this.getUsername() == null ? other.getUsername() == null : this.getUsername().equals(other.getUsername()))
+            && (this.getPassword() == null ? other.getPassword() == null : this.getPassword().equals(other.getPassword()));
     }
 
     @Override
@@ -64,6 +68,8 @@ public class User implements Serializable {
         result = prime * result + ((getOpenid() == null) ? 0 : getOpenid().hashCode());
         result = prime * result + ((getUnionid() == null) ? 0 : getUnionid().hashCode());
         result = prime * result + ((getSesseionkey() == null) ? 0 : getSesseionkey().hashCode());
+        result = prime * result + ((getUsername() == null) ? 0 : getSesseionkey().hashCode());
+        result = prime * result + ((getPassword() == null) ? 0 : getSesseionkey().hashCode());
         return result;
     }
 
@@ -77,6 +83,8 @@ public class User implements Serializable {
         sb.append(", openid=").append(openid);
         sb.append(", unionid=").append(unionid);
         sb.append(", sesseionkey=").append(sesseionkey);
+        sb.append(", username=").append(username);
+        sb.append(", password=").append(password);
         sb.append(", serialVersionUID=").append(serialVersionUID);
         sb.append("]");
         return sb.toString();