springboot2.X + websocket (三)

创建相关的util

因笔者仅将一些错误日志保存到本地,所以使用了以下的工具进行保存日志

public class IoUtil {
    /**
     * 创建文件目录
     *
     * @param path
     */
    public static boolean isFileFloderCreated(String path) {
        File file = new File(path);
        File dir = file.getParentFile();
        // 判断文件夹是否存在,如果不存在则创建文件夹
        if (dir != null && !dir.exists()) {
            try {
                dir.mkdirs();
                return true;
            } catch (Exception e) {
                return false;
            }
        } else {
            return true;
        }
    }

    /**
     * 写日志记录
     *
     * @param path
     * @param text
     * @return
     * @throws IOException
     */
    public static boolean isLogSaved(String path, String text) {
        text = LocalDateTime.now().toString()+"\r\n"+text+"\r\n\r\n";

        FileOutputStream fileOutputStream = null;
        BufferedWriter bufferWritter = null;
        OutputStreamWriter outputStreamWriter = null;
        try {
            File file = new File(path);
            isFileFloderCreated(path);
            fileOutputStream = new FileOutputStream(file, true);
            outputStreamWriter = new OutputStreamWriter(fileOutputStream, "UTF-8");
            bufferWritter = new BufferedWriter(outputStreamWriter);
            bufferWritter.write(text);

            fileOutputStream.flush();
            outputStreamWriter.flush();
            bufferWritter.flush();
            bufferWritter.close();
            outputStreamWriter.close();
            fileOutputStream.close();

            return true;
        } catch (Exception ex) {
            return false;
        } finally {
            if (bufferWritter != null) {
                try {
                    bufferWritter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (outputStreamWriter != null) {
                try {
                    outputStreamWriter.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (fileOutputStream != null) {
                try {
                    fileOutputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }

        }
    }
}

 jwtUtil

@Component
@ConfigurationProperties(prefix="token")
public class JwtUtil {
    /**
     * 默认60分钟
     */
    private Integer expirationTime = 60;

    /**
     * 默认60分钟
     */
    private Integer expirationRefreshTime = 60;

    private String signingKey = "wrc123";

    private String issuer = "wrc.com";

    public Integer getExpirationTime() {
        return expirationTime;
    }

    public void setExpirationTime(Integer expirationTime) {
        this.expirationTime = expirationTime;
    }

    public Integer getExpirationRefreshTime() {
        return expirationRefreshTime;
    }

    public void setExpirationRefreshTime(Integer expirationRefreshTime) {
        this.expirationRefreshTime = expirationRefreshTime;
    }

    public String getSigningKey() {
        return signingKey;
    }

    public void setSigningKey(String signingKey) {
        this.signingKey = signingKey;
    }

    public String getIssuer() {
        return issuer;
    }

    public void setIssuer(String issuer) {
        this.issuer = issuer;
    }

    public String createToken(LocalDateTime now ,String detail){
        return createToken(now,detail,expirationTime);
    }

    public String createToken(LocalDateTime now ,String detail,Integer expirationTime){
        if (expirationTime == null) expirationTime = this.expirationTime;

        return createJWT(now,detail,expirationTime);
    }

    public String createRefreshToken(LocalDateTime now ,String detail,Integer expirationRefreshTime){
        if (expirationRefreshTime == null) expirationRefreshTime = this.expirationRefreshTime;
        return createJWT(now,detail,expirationRefreshTime);
    }

    public String createRefreshToken(LocalDateTime now ,String detail){
        return createRefreshToken(now,detail,expirationRefreshTime);
    }

    /**
     * 创建token
     */
    private String createJWT(LocalDateTime now ,String detail,Integer overTime){
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256; //指定签名的时候使用的签名算法,也就是header那部分,jjwt已经将这部分内容封装好了。
        //生成签名的时候使用的秘钥secret
        SecretKey key = generalKey();
        //下面就是在为payload添加各种标准声明和私有声明了
        JwtBuilder builder = Jwts.builder() //这里其实就是new一个JwtBuilder,设置jwt的body
                .setIssuedAt(Date.from(now.atZone(ZoneId.systemDefault()).toInstant())) // Jwt生成时间
                .setSubject(detail) // jwt主体,存放json格式的用户信息
                .signWith(signatureAlgorithm, key)//设置签名使用的签名算法和签名使用的秘钥
                .setExpiration(Date.from(now.plusMinutes(overTime).atZone(ZoneId.systemDefault()).toInstant())) // 过期时间
                .setIssuer(issuer);
        return builder.compact();
    }

    /**
     * 解密jwt
     */
    private Claims parseJWT(String jwt){
        SecretKey key = generalKey();  //签名秘钥,和生成的签名的秘钥一模一样
        Claims claims = Jwts.parser()  //得到DefaultJwtParser
                .setSigningKey(key)         //设置签名的秘钥
                .parseClaimsJws(jwt).getBody();//设置需要解析的jwt
        return claims;
    }

    // 获取用户信息
    public JSONObject getJWTDetail(String jwt){
        try {
            return JSONObject.parseObject(parseJWT(jwt).getSubject());
        }catch (ExpiredJwtException e) {
            return JSONObject.parseObject(e.getClaims().getSubject());
        }
    }

    // 获取过期时间
    public LocalDateTime getJWTExpirationDate(String jwt){
        try {
            return parseJWT(jwt).getExpiration().toInstant().atOffset(ZoneOffset.ofHours(8)).toLocalDateTime();
        }catch (ExpiredJwtException e){
            return e.getClaims().getExpiration().toInstant().atOffset(ZoneOffset.ofHours(8)).toLocalDateTime();
        }
    }

    /**
     * 由字符串生成加密key
     */
    private SecretKey generalKey(){
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] encodedKey = decoder.decode(signingKey);
        return new SecretKeySpec(encodedKey, 0, encodedKey.length, "AES");
    }
}

 IoUtil

public class StringUtil {


    /**
     * 获取字符串
     */
    public static String getString(Object obj){
        return getString(obj,"");
    }
    /**
     * 获取字符串
     *
     *@param obj
     *@param def 默认值
     */
    public static String getString(Object obj,String def){
        if(obj == null){
            return def;
        }else{
            return obj.toString();
        }
    }
    /**
     * 获取字符串长度,空值长度为0
     *
     * @param strValue
     * @return
     */
    final public static int length(String strValue) {
        if (strValue == null) {
            return 0;
        }
        return strValue.length();
    }

    /**
     * 是否为空或长度为0字符串
     *
     * @param strValue
     * @return
     */
    final public static boolean isNullOrEmpty(String strValue) {
        return (length(strValue) == 0);
    }

    /**
     * 是否为空或长度为0字符串
     *
     * @param objValue
     * @return
     */
    final public static boolean isNullOrEmpty(Object objValue) {
        if (objValue == null) return true;
        return (length(objValue.toString()) == 0);
    }

    /**
     * 对比两个字符串,空值最小
     *
     * @param strValue1 String
     * @param strValue2 String
     * @param bIgnoreCase boolean
     * @return int
     */
    final public static int compare(String strValue1, String strValue2, boolean bIgnoreCase) {
        if (strValue1 == null && strValue2 == null) {
            return 0;
        }

        if (strValue1 == null && strValue2 != null) {
            return -1;
        }

        if (strValue1 != null && strValue2 == null) {
            return 1;
        }

        if (bIgnoreCase) {
            return strValue1.compareToIgnoreCase(strValue2);
        } else {
            return strValue1.compareTo(strValue2);
        }
    }

}

 相关的config

@Component
public class SystemConfig {

    private static String logPath;

    @Value("${custom.systemWebsocketLogPath}")
    public void setLogPath(String logPath) {
        SystemConfig.logPath = logPath;
    }

    public static String getLogPath() {
        return logPath;
    }


    private static JwtUtil jwtUtil;

    public static JwtUtil getJwtUtil() {
        return jwtUtil;
    }

    @Resource
    public  void setJwtUtil(JwtUtil jwtUtil) {
        SystemConfig.jwtUtil = jwtUtil;
    }

    private static Long maxTimeOut;


    @Value("${custom.websocketMaxIdleTimeout}")
    public void setMaxTimeOut(Long maxTimeOut) {
        SystemConfig.maxTimeOut = maxTimeOut;
    }

    public static Long getMaxTimeOut() {
        return maxTimeOut;
    }
}

websocket config

@Configuration
public class WebSocketConfig {
    @Bean
    public ServerEndpointExporter serverEndpointExporter(){
        return new ServerEndpointExporter();
    }
}

此时项目结构如下

 springboot2.X + websocket (三)

上一篇:springboot2.X + websocket 总览(一)


下一篇:springboot视图技术-freemarker