书接上文,上一篇文章大概写了一下使用SpringCloud框架的GateWay进行转发WebSocket的demo,其中也说了会有一个common的子项目,用于抽离各种工具类,今天就将相关类列一下,供大家参考。
pom
<?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <parent> <groupId>XX.XX</groupId> <artifactId>platform</artifactId> <version>0.0.1-SNAPSHOT</version> </parent> <groupId>XX.XX.platform</groupId> <artifactId>common</artifactId> <version>0.0.1-SNAPSHOT</version> <name>common</name> <description>工具类</description> <packaging>jar</packaging> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> </properties> <dependencies> <!-- spring2.X集成redis所需common-pool2,使用jedis必须依赖它--> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-pool2</artifactId> <version>2.5.0</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.58</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.6.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.6.4</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.6.4</version> </dependency> <!--redis--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> <!--mongodb--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-mongodb</artifactId> </dependency> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> </dependency> <!--在pom.xml中添加依赖--> <dependency> <groupId>org.apache.rocketmq</groupId> <artifactId>rocketmq-spring-boot-starter</artifactId> <version>2.0.4</version> </dependency> </dependencies> </project>
UUIDUtil--用于生成唯一id,单点处理还可以,分布式可能会有问题,各位也可以拼接业务号/交易号来降低重复生成的风险。如果还是不能满足要求的话,可以看看美团点评分布式ID生成系统-leaf框架。
import java.util.Random; import java.util.UUID;public class UUIDUtil { private static final String STR = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; private static final String NUM = "0123456789"; /** * 随机生成UUID * @return */ public static synchronized String getUUID() { UUID uuid = UUID.randomUUID(); String str = uuid.toString(); String uuidStr = str.replace("-", ""); return uuidStr; } /** * 生成指定长度的随机数,含英文 * * @param length * 长度 * @return */ public static String generateRandow(int length) { StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { char ch = STR.charAt(new Random().nextInt(STR.length())); sb.append(ch); } return sb.toString(); } /** * 生成指定长度的随机数,全数字 * * @param length * 长度 * @return */ public static String generateRandowNum(int length) { StringBuilder sb = new StringBuilder(length); for (int i = 0; i < length; i++) { char ch = NUM.charAt(new Random().nextInt(NUM.length())); sb.append(ch); } return sb.toString(); } }
StringUtil--用于操作字符串的工具类,目前项目用到的不多,主要是翻译表情,大家有需要可以在网上查查类似的工具,会比我这个功能丰富的多。
import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.util.regex.Matcher; public class StringUtil { public static byte[] stringToBytes(String str) { try { // 使用指定的字符集将此字符串编码为byte序列并存到一个byte数组中 return str.getBytes("utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public static String bytesToString(byte[] bs) { try { // 通过指定的字符集解码指定的byte数组并构造一个新的字符串 return new String(bs, "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public static String changeCharacters(String content) { // gbEncoding(content); if (content != null && content.contains("\\u")) { content = decodeUnicode(content); if (content.contains("[[") && content.contains("]]")) { try { content = emojiRecovery2(new String(content)); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } } else { content = content; } } else { content = content; } return content; } public static String decodeUnicode(final String dataStr) { int start = 0; int end = 0; final StringBuffer buffer = new StringBuffer(); while (start > -1) { end = dataStr.indexOf("\\u", start + 2); String charStr = ""; if (end == -1) { charStr = dataStr.substring(start + 2, dataStr.length()); } else { charStr = dataStr.substring(start + 2, end); } char letter = (char) Integer.parseInt(charStr, 16); buffer.append(new Character(letter).toString()); start = end; } return buffer.toString(); } /** * @Description 还原utf8数据库中保存的含转换后emoji表情的字符串 * @param str * 转换后的字符串 * @return 转换前的字符串 * @throws UnsupportedEncodingException * exception */ public static String emojiRecovery2(String str) throws UnsupportedEncodingException { String patternString = "\\[\\[(.*?)\\]\\]"; java.util.regex.Pattern pattern = java.util.regex.Pattern.compile(patternString); Matcher matcher = pattern.matcher(str); StringBuffer sb = new StringBuffer(); while (matcher.find()) { try { matcher.appendReplacement(sb, URLDecoder.decode(matcher.group(1), "UTF-8")); } catch (UnsupportedEncodingException e) { throw e; } } matcher.appendTail(sb); return sb.toString(); } }
JsonUtil--json的工具类,对于我当前的项目是够用了,大家有更多的需求的话,可以百度哦。
import com.google.gson.*; import java.beans.BeanInfo; import java.beans.Introspector; import java.beans.PropertyDescriptor; import java.lang.reflect.Method; import java.util.*; public class JsonUtil { /** * 将Map转成json * @param map * @return */ public static String mapToJson(Map<String, Object> map){ Gson gson = new Gson(); return gson.toJson(map, Map.class); } /** * 依据json字符串返回Map对象 * @param json * @return */ public static Map<String,Object> toMap(String json){ Gson gson = new Gson(); return JsonUtil.toMap(JsonUtil.parseJson(json)); } /** * 获取JsonObject * @param json * @return */ public static JsonObject parseJson(String json){ JsonParser parser = new JsonParser(); JsonObject jsonObj = parser.parse(json).getAsJsonObject(); return jsonObj; } /** * 将JSONObjec对象转换成Map-List集合 * @param json * @return */ public static Map<String, Object> toMap(JsonObject json){ Map<String, Object> map = new HashMap<String, Object>(); Set<Map.Entry<String, JsonElement>> entrySet = json.entrySet(); for (Iterator<Map.Entry<String, JsonElement>> iter = entrySet.iterator(); iter.hasNext(); ){ Map.Entry<String, JsonElement> entry = iter.next(); String key = entry.getKey(); Object value = entry.getValue(); if(value instanceof JsonArray) map.put((String) key, toList((JsonArray) value)); else if(value instanceof JsonObject) map.put((String) key, toMap((JsonObject) value)); else map.put((String) key, value); } return map; } /** * 将JSONArray对象转换成List集合 * @param json * @return */ public static List<Object> toList(JsonArray json){ List<Object> list = new ArrayList<Object>(); for (int i=0; i<json.size(); i++){ Object value = json.get(i); if(value instanceof JsonArray){ list.add(toList((JsonArray) value)); } else if(value instanceof JsonObject){ list.add(toMap((JsonObject) value)); } else{ list.add(value); } } return list; } public static Map<String, String> parseObjectToJson(Object obj) { return getCamelMap(transBean2Map(obj)); } public static Map<String, Object> transBean2Map(Object obj) { if (obj == null) { return null; } Map<String, Object> map = new HashMap<String, Object>(); try { BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass()); PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors(); for (PropertyDescriptor property : propertyDescriptors) { String key = property.getName(); if (!key.equals("class")) { Method getter = property.getReadMethod(); Object value = getter.invoke(obj); map.put(key, value); } } } catch (Exception e) { e.printStackTrace(); } return map; } public static Map<String, String> getCamelMap(Map<String, Object> paramMap){ Map<String, String> resMap = new HashMap<String, String>(); if(null == paramMap){ return null; } Set<String> keySet = paramMap.keySet(); Iterator<String> it = keySet.iterator(); String sKey = null; Object oVal = null; while(it.hasNext()){ sKey = it.next(); oVal = paramMap.get(sKey); resMap.put(sKey, oVal.toString()); } return resMap; } }
FileUtil--文件的操作工具类
import java.io.*; import java.net.*; public class FileUtil { /** * 读取文件内容 * * @param is * @return */ public static String readFile(InputStream is) { BufferedReader br = null; StringBuffer sb = new StringBuffer(); try { br = new BufferedReader(new InputStreamReader(is, "UTF-8")); String readLine = null; while ((readLine = br.readLine()) != null) { sb.append(readLine); } } catch (Exception e) { e.printStackTrace(); } finally { try { br.close(); is.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString(); } /** * 判断指定的文件是否存在。 * * @param fileName * @return */ public static boolean isFileExist(String fileName) { return new File(fileName).isFile(); } /** * 创建指定的目录。 如果指定的目录的父目录不存在则创建其目录书上所有需要的父目录。 * 注意:可能会在返回false的时候创建部分父目录。 * * @param file * @return */ public static boolean makeDirectory(File file) { File parent = file.getParentFile(); if (parent != null) { return parent.mkdirs(); } return false; } /** * 返回文件的URL地址。 * * @param file * @return * @throws MalformedURLException */ public static URL getURL(File file) throws MalformedURLException { String fileURL = "file:/" + file.getAbsolutePath(); URL url = new URL(fileURL); return url; } /** * 从文件路径得到文件名。 * * @param filePath * @return */ public static String getFileName(String filePath) { File file = new File(filePath); return file.getName(); } /** * 从文件名得到文件绝对路径。 * * @param fileName * @return */ public static String getFilePath(String fileName) { File file = new File(fileName); return file.getAbsolutePath(); } /** * 将DOS/Windows格式的路径转换为UNIX/Linux格式的路径。 * * @param filePath * @return */ public static String toUNIXpath(String filePath) { return filePath.replace("", "/"); } /** * 从文件名得到UNIX风格的文件绝对路径。 * * @param fileName * @return */ public static String getUNIXfilePath(String fileName) { File file = new File(fileName); return toUNIXpath(file.getAbsolutePath()); } public static long getFileSize(String fileName) { File file = new File(fileName); return file.length(); } /** * 得到文件后缀名 * * @param fileName * @return */ public static String getFileExt(String fileName) { int point = fileName.lastIndexOf('.'); int length = fileName.length(); if (point == -1 || point == length - 1) { return ""; } else { return fileName.substring(point + 1, length).toLowerCase(); } } /** * 得到文件的名字部分。 实际上就是路径中的最后一个路径分隔符后的部分。 * * @param fileName * @return */ public static String getNamePart(String fileName) { int point = getPathLastIndex(fileName); int length = fileName.length(); if (point == -1) { return fileName; } else if (point == length - 1) { int secondPoint = getPathLastIndex(fileName, point - 1); if (secondPoint == -1) { if (length == 1) { return fileName; } else { return fileName.substring(0, point); } } else { return fileName.substring(secondPoint + 1, point); } } else { return fileName.substring(point + 1); } } /** * 得到文件名中的父路径部分。 对两种路径分隔符都有效。 不存在时返回""。 * 如果文件名是以路径分隔符结尾的则不考虑该分隔符,例如"/path/"返回""。 * * @param fileName * @return */ public static String getPathPart(String fileName) { int point = getPathLastIndex(fileName); int length = fileName.length(); if (point == -1) { return ""; } else if (point == length - 1) { int secondPoint = getPathLastIndex(fileName, point - 1); if (secondPoint == -1) { return ""; } else { return fileName.substring(0, secondPoint); } } else { return fileName.substring(0, point); } } /** * 得到路径分隔符在文件路径中最后出现的位置。 对于DOS或者UNIX风格的分隔符都可以。 * * @param fileName * @return */ public static int getPathLastIndex(String fileName) { int point = fileName.lastIndexOf("/"); if (point == -1) { point = fileName.lastIndexOf(""); } return point; } /** * 得到路径分隔符在文件路径中指定位置前最后出现的位置。 对于DOS或者UNIX风格的分隔符都可以。 * * @param fileName * @param fromIndex * @return */ public static int getPathLastIndex(String fileName, int fromIndex) { int point = fileName.lastIndexOf("/", fromIndex); if (point == -1) { point = fileName.lastIndexOf("", fromIndex); } return point; } /** * 得到路径分隔符在文件路径中首次出现的位置。 对于DOS或者UNIX风格的分隔符都可以。 * * @param fileName * @return */ public static int getPathIndex(String fileName) { int point = fileName.indexOf("/"); if (point == -1) { point = fileName.indexOf(""); } return point; } /** * 得到路径分隔符在文件路径中指定位置后首次出现的位置。 对于DOS或者UNIX风格的分隔符都可以。 * * @param fileName * @param fromIndex * @return */ public static int getPathIndex(String fileName, int fromIndex) { int point = fileName.indexOf("/", fromIndex); if (point == -1) { point = fileName.indexOf("", fromIndex); } return point; } /** * 将文件名中的类型部分去掉。 * * @param filename * @return */ public static String removeFileExt(String filename) { int index = filename.lastIndexOf("."); if (index != -1) { return filename.substring(0, index); } else { return filename; } } /** * 得到相对路径。 文件名不是目录名的子节点时返回文件名。 * * @param pathName * @param fileName * @return */ public static String getSubpath(String pathName, String fileName) { int index = fileName.indexOf(pathName); if (index != -1) { return fileName.substring(index + pathName.length() + 1); } else { return fileName; } } /** * 删除一个文件。 * * @param filename * @throws IOException */ public static void deleteFile(String filename) { try { File file = new File(filename); if (file.isDirectory()) { throw new IOException("IOException -> BadInputException: not a file."); } if (!file.exists()) { throw new IOException("IOException -> BadInputException: file is not exist."); } if (!file.delete()) { throw new IOException("Cannot delete file. filename = " + filename); } } catch (IOException e) { //e.printStackTrace(); } } /** * 删除文件夹及其下面的子文件夹 * * @param dir * @throws IOException */ public static void deleteDir(File dir) throws IOException { if (dir.isFile()) throw new IOException("IOException -> BadInputException: not a directory."); File[] files = dir.listFiles(); if (files != null) { for (int i = 0; i < files.length; i++) { File file = files[i]; if (file.isFile()) { file.delete(); } else { deleteDir(file); } } } dir.delete(); } /** * 复制文件 * * @param src * @param dst * @throws Exception */ public static void copy(File src, File dst) throws Exception { int BUFFER_SIZE = 4096; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); out = new BufferedOutputStream(new FileOutputStream(dst), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (Exception e) { throw e; } finally { if (null != in) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } in = null; } if (null != out) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } out = null; } } } /** * @复制文件,支持把源文件内容追加到目标文件末尾 * @param src * @param dst * @param append * @throws Exception */ public static void copy(File src, File dst, boolean append) throws Exception { int BUFFER_SIZE = 4096; InputStream in = null; OutputStream out = null; try { in = new BufferedInputStream(new FileInputStream(src), BUFFER_SIZE); out = new BufferedOutputStream(new FileOutputStream(dst, append), BUFFER_SIZE); byte[] buffer = new byte[BUFFER_SIZE]; int len = 0; while ((len = in.read(buffer)) > 0) { out.write(buffer, 0, len); } } catch (Exception e) { throw e; } finally { if (null != in) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } in = null; } if (null != out) { try { out.close(); } catch (IOException e) { e.printStackTrace(); } out = null; } } } /** * 说明:根据指定URL将文件下载到指定目标位置 * * @param urlPath * 下载路径 * @param downloadDir * 文件存放目录 * @return 返回下载文件 */ @SuppressWarnings("finally") public static File downloadFile(String urlPath, String downloadDir) throws IOException { File file = null; OutputStream out = null; BufferedInputStream bin = null; try { // 统一资源 URL url = new URL(urlPath); // 连接类的父类,抽象类 URLConnection urlConnection = url.openConnection(); // http的连接类 HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection; //设置超时 httpURLConnection.setConnectTimeout(1000*5); //设置请求方式,默认是GET httpURLConnection.setRequestMethod("POST"); // 设置字符编码 httpURLConnection.setRequestProperty("Charset", "UTF-8"); // 打开到此 URL引用的资源的通信链接(如果尚未建立这样的连接)。 httpURLConnection.connect(); // 文件大小 int fileLength = httpURLConnection.getContentLength(); if(fileLength/(1024*1024)>100) { return null; } // 建立链接从请求中获取数据 bin = new BufferedInputStream(httpURLConnection.getInputStream()); // 指定文件名称(有需求可以自定义) String fileFullName = getFileName(httpURLConnection,urlPath); // 指定存放位置(有需求可以自定义) String path = downloadDir + File.separatorChar + fileFullName; file = new File(path); // 校验文件夹目录是否存在,不存在就创建一个目录 if (!file.getParentFile().exists()) { file.getParentFile().mkdirs(); } out = new FileOutputStream(file); int size = 0; int len = 0; byte[] buf = new byte[2048]; while ((size = bin.read(buf)) != -1) { len += size; out.write(buf, 0, size); } // 关闭资源 bin.close(); out.close(); System.out.println("文件下载成功!"); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("文件下载失败!"); } finally { bin.close(); out.close(); return file; } } /** * description: 获取文件名 * @param http * @param urlPath * @throws UnsupportedEncodingException * @return String * @version v1.0 * @author w * @date 2019年9月3日 下午8:25:55 */ private static String getFileName(HttpURLConnection http , String urlPath) throws UnsupportedEncodingException { String headerField = http.getHeaderField("Content-Disposition"); String fileName = null ; if(null != headerField) { String decode = URLDecoder.decode(headerField, "UTF-8"); fileName = decode.split(";")[1].split("=")[1].replaceAll("\"", ""); System.out.println("文件名是: "+ fileName); } if(null == fileName) { // 尝试从url中获取文件名 String[] arr = urlPath.split("/"); fileName = arr[arr.length - 1]; System.out.println("url中获取文件名:"+ fileName); } return fileName; } public static byte[] fileToByte(File file) throws IOException{ byte[] bytes = null; FileInputStream fis = null; try{ fis = new FileInputStream(file); bytes = new byte[(int) file.length()]; fis.read(bytes); }catch(IOException e){ e.printStackTrace(); throw e; }finally{ fis.close(); } return bytes; } public static byte[] fileToByte(String filepath){ File file = new File(filepath); byte[] bytes = null; FileInputStream fis = null; try{ fis = new FileInputStream(file); bytes = new byte[(int) file.length()]; fis.read(bytes); }catch(Exception e){ e.printStackTrace(); }finally{ try { fis.close(); }catch (Exception e) { e.printStackTrace(); } } return bytes; } public static void bytesToFile(byte[] bFile, String fileDest) { FileOutputStream fileOuputStream = null; try { fileOuputStream = new FileOutputStream(fileDest); fileOuputStream.write(bFile); } catch (IOException e) { e.printStackTrace(); } finally { if (fileOuputStream != null) { try { fileOuputStream.close(); } catch (IOException e) { e.printStackTrace(); } } } } }
DateUtil--日期工具类,主要是获取日期对应的字符串。。
import java.util.Calendar; import java.util.GregorianCalendar; public class DateUtil { /** * 得到当前系统日期 author: YT * @return 当前日期的格式字符串,日期格式为"yyyy-MM-dd" */ public static String getCurrentDate() { GregorianCalendar tGCalendar = new GregorianCalendar(); int sYears = tGCalendar.get(Calendar.YEAR); int sMonths = tGCalendar.get(Calendar.MONTH) + 1; int sDays = tGCalendar.get(Calendar.DAY_OF_MONTH); StringBuffer tStringBuffer = new StringBuffer(10); tStringBuffer.append(sYears); tStringBuffer.append('-'); if(sMonths < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sMonths); tStringBuffer.append('-'); if(sDays < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sDays); return tStringBuffer.toString(); } /** * 得到当前系统时间 author: YT * @return 当前时间的格式字符串,时间格式为"HH:mm:ss" */ public static String getCurrentTime() { GregorianCalendar tGCalendar = new GregorianCalendar(); int sHOUR = tGCalendar.get(Calendar.HOUR_OF_DAY); int sMINUTE = tGCalendar.get(Calendar.MINUTE); int sSECOND = tGCalendar.get(Calendar.SECOND); StringBuffer tStringBuffer = new StringBuffer(8); if(sHOUR < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sHOUR); tStringBuffer.append(':'); if(sMINUTE < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sMINUTE); tStringBuffer.append(':'); if(sSECOND < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sSECOND); return tStringBuffer.toString(); } public static String getCurrentDateTime() { GregorianCalendar tGCalendar = new GregorianCalendar(); int sYears = tGCalendar.get(Calendar.YEAR); int sMonths = tGCalendar.get(Calendar.MONTH) + 1; int sDays = tGCalendar.get(Calendar.DAY_OF_MONTH); int sHOUR = tGCalendar.get(Calendar.HOUR_OF_DAY); int sMINUTE = tGCalendar.get(Calendar.MINUTE); int sSECOND = tGCalendar.get(Calendar.SECOND); StringBuffer tStringBuffer = new StringBuffer(10); tStringBuffer.append(sYears); tStringBuffer.append('-'); if(sMonths < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sMonths); tStringBuffer.append('-'); if(sDays < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sDays).append(" "); if(sHOUR < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sHOUR); tStringBuffer.append(':'); if(sMINUTE < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sMINUTE); tStringBuffer.append(':'); if(sSECOND < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sSECOND); return tStringBuffer.toString(); } public static String getCurrentDateTimeTrim() { GregorianCalendar tGCalendar = new GregorianCalendar(); int sYears = tGCalendar.get(Calendar.YEAR); int sMonths = tGCalendar.get(Calendar.MONTH) + 1; int sDays = tGCalendar.get(Calendar.DAY_OF_MONTH); int sHOUR = tGCalendar.get(Calendar.HOUR_OF_DAY); int sMINUTE = tGCalendar.get(Calendar.MINUTE); int sSECOND = tGCalendar.get(Calendar.SECOND); StringBuffer tStringBuffer = new StringBuffer(10); tStringBuffer.append(sYears); // tStringBuffer.append('-'); if(sMonths < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sMonths); // tStringBuffer.append('-'); if(sDays < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sDays);//.append(" "); if(sHOUR < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sHOUR); // tStringBuffer.append(':'); if(sMINUTE < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sMINUTE); // tStringBuffer.append(':'); if(sSECOND < 10) { tStringBuffer.append('0'); } tStringBuffer.append(sSECOND); return tStringBuffer.toString(); } }
BaseCode--基本常量的定义
public class BaseCode { //成功 public final static String SUCCESSCODE = "200"; //失败 public final static String FAILCODE = "400"; //需要登录 public final static String LOGINERROR = "501"; //操作成功提示 public final static String SUCCESSMSG = "操作成功"; //操作失败提示 public final static String FAILSSMSG = "操作失败"; //天 public final static long DAY = 60 * 60 * 24; //时 public final static long HOUR = 60 * 60; //分 public final static long MIN = 60; //token信息 public final static String TOKEN = "TOKEN"; //验证码 public final static String YZM="YZM"; //未删除 public final static short NOTDELETE = 0; //删除了 public final static short DELETE = 1; //报工录入 public final static String INPUT = "I"; //报工上报 public final static String REPORT = "R"; //单点登录 public final static String SINGLELOGIN = "singlelogin"; //消费者 public final static String CONSUMER = "consumer"; //websocket的session public final static String SESSION = "session"; //用户id public final static String USERID = "userid"; //聊天类型的mq public final static String IMCHAT = "bhimchat"; }
Result--通用结果类
import java.util.ArrayList; /** * @version v1.0 * <p>返回结果类</p> */ public class Result { /** * 返回值 */ private String returnCode = BaseCode.SUCCESSCODE; /** * 提示信息 */ private String returnMsg = BaseCode.FAILSSMSG; /** * 返回数据 */ private Object returnData = new Object(); public static Result createok() { return new Result(); } public static Result createok(Object result) { return new Result(result); } public static Result createFail(String msg) { return new Result(BaseCode.FAILCODE,msg); } public static Result createTokenFail(String msg) { return new Result(BaseCode.LOGINERROR,msg); } /** * 构造方法 */ public Result(Object returnData) { this.returnCode = BaseCode.SUCCESSCODE; this.returnMsg = BaseCode.SUCCESSMSG; this.returnData = returnData; } /** * 构造方法 */ public Result(String resultCode,String resultMsg) { this.returnCode = resultCode; this.returnMsg = resultMsg; this.returnData = null; } public Result(String returnCode, String returnMsg, Object returnData) { this.returnCode = returnCode; this.returnMsg = returnMsg; this.returnData = returnData; if(!returnCode.equals(BaseCode.SUCCESSCODE)) { this.returnMsg = (String) returnData; this.returnData = new ArrayList<>(); } } public Result() { super(); } public String getReturnCode() { return returnCode; } public void setReturnCode(String returnCode) { this.returnCode = returnCode; } public String getReturnMsg() { return returnMsg; } public void setReturnMsg(String returnMsg) { this.returnMsg = returnMsg; } public Object getReturnData() { return returnData; } public void setReturnData(Object returnData) { this.returnData = returnData; } }
MongoBean--mongodb的bean对象
import lombok.Data; import org.springframework.data.annotation.Id; @Data public class MongoBean { @Id private String mid;//主键 private String busType;//业务类型 private String busNo;//业务号 private Integer order;//顺序 private String objectType;//对象类型 private byte[] object;//对象内容,需要按照对象类型进行转换 可参考FileUtil和StringUtil }
MongodbUtils--mongodb的工具类
import java.util.List; import javax.annotation.PostConstruct; import com.mongodb.BasicDBObject; import com.mongodb.DBObject; import org.bson.types.ObjectId; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.domain.Sort; import org.springframework.data.domain.Sort.Direction; import org.springframework.data.mongodb.core.MongoTemplate; import org.springframework.data.mongodb.core.query.Criteria; import org.springframework.data.mongodb.core.query.Query; import org.springframework.data.mongodb.core.query.Update; import org.springframework.stereotype.Component; @Component public class MongodbUtils { public static MongodbUtils mongodbUtils; @PostConstruct public void init() { mongodbUtils = this; mongodbUtils.mongoTemplate = this.mongoTemplate; } @Autowired private MongoTemplate mongoTemplate; /** * 保存数据对象,集合为数据对象中@Document 注解所配置的collection * * @param obj * 数据对象 */ public static void save(Object obj) { mongodbUtils.mongoTemplate.save(obj); } /** * 指定集合保存数据对象 * * @param obj * 数据对象 * @param collectionName * 集合名 */ public static void save(Object obj, String collectionName) { mongodbUtils.mongoTemplate.save(obj, collectionName); } /** * 根据数据对象中的id删除数据,集合为数据对象中@Document 注解所配置的collection * * @param obj * 数据对象 */ public static void remove(Object obj) { mongodbUtils.mongoTemplate.remove(obj); } /** * 指定集合 根据数据对象中的id删除数据 * * @param obj * 数据对象 * @param collectionName * 集合名 */ public static void remove(Object obj, String collectionName) { mongodbUtils.mongoTemplate.remove(obj, collectionName); } /** * 根据key,value到指定集合删除数据 * * @param key * 键 * @param value * 值 * @param collectionName * 集合名 */ public static void removeById(String key, Object value, String collectionName) { Criteria criteria = Criteria.where(key).is(value); criteria.and(key).is(value); Query query = Query.query(criteria); mongodbUtils.mongoTemplate.remove(query, collectionName); } /** * 指定集合 修改数据,且仅修改找到的第一条数据 * * @param accordingKey * 修改条件 key * @param accordingValue * 修改条件 value * @param updateKeys * 修改内容 key数组 * @param updateValues * 修改内容 value数组 * @param collectionName * 集合名 */ public static void updateFirst(String accordingKey, Object accordingValue, String[] updateKeys, Object[] updateValues, String collectionName) { Criteria criteria = Criteria.where(accordingKey).is(accordingValue); Query query = Query.query(criteria); Update update = new Update(); for (int i = 0; i < updateKeys.length; i++) { update.set(updateKeys[i], updateValues[i]); } mongodbUtils.mongoTemplate.updateFirst(query, update, collectionName); } /** * 指定集合 修改数据,且修改所找到的所有数据 * * @param accordingKey * 修改条件 key * @param accordingValue * 修改条件 value * @param updateKeys * 修改内容 key数组 * @param updateValues * 修改内容 value数组 * @param collectionName * 集合名 */ public static void updateMulti(String accordingKey, Object accordingValue, String[] updateKeys, Object[] updateValues, String collectionName) { Criteria criteria = Criteria.where(accordingKey).is(accordingValue); Query query = Query.query(criteria); Update update = new Update(); for (int i = 0; i < updateKeys.length; i++) { update.set(updateKeys[i], updateValues[i]); } mongodbUtils.mongoTemplate.updateMulti(query, update, collectionName); } /** * 根据条件查询出所有结果集 集合为数据对象中@Document 注解所配置的collection * * @param obj * 数据对象 * @param findKeys * 查询条件 key * @param findValues * 查询条件 value * @return */ public static List<? extends Object> find(Object obj, String[] findKeys, Object[] findValues) { Criteria criteria = null; for (int i = 0; i < findKeys.length; i++) { if (i == 0) { criteria = Criteria.where(findKeys[i]).is(findValues[i]); } else { criteria.and(findKeys[i]).is(findValues[i]); } } Query query = Query.query(criteria); List<? extends Object> resultList = mongodbUtils.mongoTemplate.find(query, obj.getClass()); return resultList; } /** * 指定集合 根据条件查询出所有结果集 * * @param obj * 数据对象 * @param findKeys * 查询条件 key * @param findValues * 查询条件 value * @param collectionName * 集合名 * @return */ public static List<? extends Object> find(Object obj, String[] findKeys, Object[] findValues, String collectionName) { Criteria criteria = null; for (int i = 0; i < findKeys.length; i++) { if (i == 0) { criteria = Criteria.where(findKeys[i]).is(findValues[i]); } else { criteria.and(findKeys[i]).is(findValues[i]); } } Query query = Query.query(criteria); List<? extends Object> resultList = mongodbUtils.mongoTemplate.find(query, obj.getClass(), collectionName); return resultList; } /** * 指定集合 根据条件查询出所有结果集 并排倒序 * * @param obj * 数据对象 * @param findKeys * 查询条件 key * @param findValues * 查询条件 value * @param collectionName * 集合名 * @param sort * 排序字段 * @return */ public static List<? extends Object> find(Object obj, String[] findKeys, Object[] findValues, String collectionName ,String sort) { Criteria criteria = null; for (int i = 0; i < findKeys.length; i++) { if (i == 0) { criteria = Criteria.where(findKeys[i]).is(findValues[i]); } else { criteria.and(findKeys[i]).is(findValues[i]); } } Query query = Query.query(criteria); query.with(new Sort(Direction.DESC, sort)); List<? extends Object> resultList = mongodbUtils.mongoTemplate.find(query, obj.getClass(), collectionName); return resultList; } /** * 根据条件查询出符合的第一条数据 集合为数据对象中 @Document 注解所配置的collection * * @param obj * 数据对象 * @param findKeys * 查询条件 key * @param findValues * 查询条件 value * @return */ public static Object findOne(Object obj, String[] findKeys, Object[] findValues) { Criteria criteria = null; for (int i = 0; i < findKeys.length; i++) { if (i == 0) { criteria = Criteria.where(findKeys[i]).is(findValues[i]); } else { criteria.and(findKeys[i]).is(findValues[i]); } } Query query = Query.query(criteria); Object resultObj = mongodbUtils.mongoTemplate.findOne(query, obj.getClass()); return resultObj; } /** * 指定集合 根据条件查询出符合的第一条数据 * * @param obj * 数据对象 * @param findKeys * 查询条件 key * @param findValues * 查询条件 value * @param collectionName * 集合名 * @return */ public static Object findOne(Object obj, String[] findKeys, Object[] findValues, String collectionName) { Criteria criteria = null; for (int i = 0; i < findKeys.length; i++) { if (i == 0) { criteria = Criteria.where(findKeys[i]).is(findValues[i]); } else { criteria.and(findKeys[i]).is(findValues[i]); } } Query query = Query.query(criteria); Object resultObj = mongodbUtils.mongoTemplate.findOne(query, obj.getClass(), collectionName); return resultObj; } /** * 查询出所有结果集 集合为数据对象中 @Document 注解所配置的collection * * @param obj * 数据对象 * @return */ public static List<? extends Object> findAll(Object obj) { List<? extends Object> resultList = mongodbUtils.mongoTemplate.findAll(obj.getClass()); return resultList; } /** * 指定集合 查询出所有结果集 * * @param obj * 数据对象 * @param collectionName * 集合名 * @return */ public static List<? extends Object> findAll(Object obj, String collectionName) { List<? extends Object> resultList = mongodbUtils.mongoTemplate.findAll(obj.getClass(), collectionName); return resultList; } public static MongoBean findDocumentById(String id) { Query query = new Query(); query.addCriteria(Criteria.where("_id").is(id)); // query.put("_id", new ObjectId(id)); MongoBean dbObj = (MongoBean) mongodbUtils.mongoTemplate.findOne(query,MongoBean.class); return dbObj; } }
RedisConfig--redis配置类
import com.fasterxml.jackson.annotation.JsonAutoDetect; import com.fasterxml.jackson.annotation.PropertyAccessor; import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.redis.connection.RedisConnectionFactory; import org.springframework.data.redis.core.*; import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer; import org.springframework.data.redis.serializer.JdkSerializationRedisSerializer; import org.springframework.data.redis.serializer.StringRedisSerializer; /** * RedisConfig * * @description redis配置 */ @Configuration @AutoConfigureAfter(RedisAutoConfiguration.class) public class RedisConfig { @Autowired private RedisConnectionFactory redisConnectionFactory; @Bean public RedisTemplate<String, Object> redisTemplate() { RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); // 设置redis主键的序列化形式 redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(new JdkSerializationRedisSerializer()); redisTemplate.setValueSerializer(new JdkSerializationRedisSerializer()); Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<Object>(Object.class); ObjectMapper om = new ObjectMapper(); om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL); jackson2JsonRedisSerializer.setObjectMapper(om); redisTemplate.setValueSerializer(jackson2JsonRedisSerializer); redisTemplate.setConnectionFactory(redisConnectionFactory); return redisTemplate; } @Bean public HashOperations<String, String, Object> hashOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForHash(); } @Bean public ValueOperations<String, String> valueOperations(RedisTemplate<String, String> redisTemplate) { return redisTemplate.opsForValue(); } @Bean public ListOperations<String, Object> listOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForList(); } @Bean public SetOperations<String, Object> setOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForSet(); } @Bean public ZSetOperations<String, Object> zSetOperations(RedisTemplate<String, Object> redisTemplate) { return redisTemplate.opsForZSet(); } }
RedisService--redis操作方法的接口类
import java.util.List; import java.util.Set; public interface RedisService { /** * 写入缓存 * @param key * @param value * @return */ public boolean set(final String key, Object value) ; /** * 写入缓存设置时效时间 * @param key * @param value * @return */ public boolean set(final String key, Object value, Long expireTime) ; /** * 批量删除对应的value * @param keys */ public void remove(final String... keys) ; /** * 批量删除key * @param pattern */ public void removePattern(final String pattern) ; /** * 删除对应的value * @param key */ public void remove(final String key) ; /** * 判断缓存中是否有对应的value * @param key * @return */ public boolean exists(final String key) ; /** * 读取缓存 * @param key * @return */ public Object get(final String key) ; /** * 哈希 添加 * @param key * @param hashKey * @param value */ public void hmSet(String key, Object hashKey, Object value) ; /** * 哈希获取数据 * @param key * @param hashKey * @return */ public Object hmGet(String key, Object hashKey) ; /** * 列表添加 * @param k * @param v */ public void lPush(String k, Object v) ; /** * 列表获取 * @param k * @param l * @param l1 * @return */ public List<Object> lRange(String k, long l, long l1) ; /** * 集合添加 * @param key * @param value */ public void add(String key, Object value) ; /** * 集合获取 * @param key * @return */ public Set<Object> setMembers(String key) ; /** * 有序集合添加 * @param key * @param value * @param scoure */ public void zAdd(String key, Object value, double scoure) ; /** * 有序集合获取 * @param key * @param scoure * @param scoure1 * @return */ public Set<Object> rangeByScore(String key, double scoure, double scoure1) ; }
RedisServiceImpl--redis操作实现类
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.*; import org.springframework.stereotype.Service; import java.io.Serializable; import java.util.List; import java.util.Set; import java.util.concurrent.TimeUnit; @Service public class RedisServiceImpl implements RedisService{ @Autowired private RedisTemplate redisTemplate; @Override public boolean set(final String key, Object value) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } @Override public boolean set(final String key, Object value, Long expireTime) { boolean result = false; try { ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); operations.set(key, value); redisTemplate.expire(key, expireTime, TimeUnit.SECONDS); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } @Override public void remove(final String... keys) { for (String key : keys) { remove(key); } } @Override public void removePattern(final String pattern) { Set<Serializable> keys = redisTemplate.keys(pattern); if (keys.size() > 0) redisTemplate.delete(keys); } @Override public void remove(final String key) { if (exists(key)) { redisTemplate.delete(key); } } @Override public boolean exists(final String key) { return redisTemplate.hasKey(key); } @Override public Object get(final String key) { Object result = null; ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue(); result = operations.get(key); return result; } @Override public void hmSet(String key, Object hashKey, Object value) { HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); hash.put(key, hashKey, value); } @Override public Object hmGet(String key, Object hashKey) { HashOperations<String, Object, Object> hash = redisTemplate.opsForHash(); return hash.get(key, hashKey); } @Override public void lPush(String k, Object v) { ListOperations<String, Object> list = redisTemplate.opsForList(); list.rightPush(k, v); } @Override public List<Object> lRange(String k, long l, long l1) { ListOperations<String, Object> list = redisTemplate.opsForList(); return list.range(k, l, l1); } @Override public void add(String key, Object value) { SetOperations<String, Object> set = redisTemplate.opsForSet(); set.add(key, value); } @Override public Set<Object> setMembers(String key) { SetOperations<String, Object> set = redisTemplate.opsForSet(); return set.members(key); } @Override public void zAdd(String key, Object value, double scoure) { ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); zset.add(key, value, scoure); } @Override public Set<Object> rangeByScore(String key, double scoure, double scoure1) { ZSetOperations<String, Object> zset = redisTemplate.opsForZSet(); return zset.rangeByScore(key, scoure, scoure1); } }
IMChatMessage--聊天信息
import lombok.Data; @Data public class IMChatMessage { private Object from; private String data; private String type; private Object groupInfo; private String gmtCreat; public Object getFrom() { return from; } public void setFrom(Object from) { this.from = from; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String getType() { return type; } public void setType(String type) { this.type = type; } public Object getGroupInfo() { return groupInfo; } public void setGroupInfo(Object groupInfo) { this.groupInfo = groupInfo; } public String getGmtCreat() { return gmtCreat; } public void setGmtCreat(String gmtCreat) { this.gmtCreat = gmtCreat; } }
IMChatRequest--请求发送聊天信息
import lombok.Data; @Data public class IMChatRequest { private String token; private String type; private String data; private String[] touserid; private String[] togroupid; private Object from; public String getToken() { return token; } public void setToken(String token) { this.token = token; } public String getType() { return type; } public void setType(String type) { this.type = type; } public String getData() { return data; } public void setData(String data) { this.data = data; } public String[] getTouserid() { return touserid; } public void setTouserid(String[] touserid) { this.touserid = touserid; } public String[] getTogroupid() { return togroupid; } public void setTogroupid(String[] togroupid) { this.togroupid = togroupid; } public Object getFrom() { return from; } public void setFrom(Object from) { this.from = from; } }
IMChatResponse--响应反馈消息
import com.bohailife.platform.common.base.BaseCode; import lombok.Data; @Data public class IMChatResponse { /** * 返回值 */ private String returnCode = BaseCode.SUCCESSCODE; /** * 提示信息 */ private String returnMsg = "操作成功"; /** * 返回数据 */ private Object returnData = new Object(); /** * 构造方法 */ public IMChatResponse(Object returnData) { this.returnCode = BaseCode.SUCCESSCODE; this.returnMsg = "操作成功"; this.returnData = returnData; } public IMChatResponse(String returnCode, String returnMsg, Object returnData) { this.returnCode = returnCode; this.returnMsg = returnMsg; this.returnData = returnData; if(!returnCode.equals(BaseCode.SUCCESSCODE)) { this.returnData = new MsgVo((String) returnData); } } public IMChatResponse() { super(); } }
MsgVo
public class MsgVo { private String msg = ""; public MsgVo(String msg) { this.msg = msg; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } @Override public String toString() { return "MsgVo{" + "msg='" + msg + '\'' + '}'; } }
Consumer--mq的消费类
import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.client.consumer.DefaultMQPushConsumer; import org.apache.rocketmq.client.consumer.listener.ConsumeConcurrentlyStatus; import org.apache.rocketmq.client.consumer.listener.MessageListenerConcurrently; import org.apache.rocketmq.common.consumer.ConsumeFromWhere; import org.apache.rocketmq.common.message.Message; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.CommandLineRunner; import org.springframework.stereotype.Component; /** * @Description:消费者 */ @Component @Slf4j public class Consumer implements CommandLineRunner { /** * 消费者 */ @Value("${apache.rocketmq.consumer.pushConsumer}") private String pushConsumer; /** * NameServer 地址 */ @Value("${apache.rocketmq.namesrvAddr}") private String namesrvAddr; /** * 初始化RocketMq的监听信息,渠道信息 */ public void messageListener(){ DefaultMQPushConsumer consumer=new DefaultMQPushConsumer("222"); consumer.setNamesrvAddr(namesrvAddr); try { // 订阅PushTopic下Tag为push的消息,都订阅消息 consumer.subscribe("PushTopic", "push"); // 程序第一次启动从消息队列头获取数据 consumer.setConsumeFromWhere(ConsumeFromWhere.CONSUME_FROM_FIRST_OFFSET); //可以修改每次消费消息的数量,默认设置是每次消费一条 consumer.setConsumeMessageBatchMaxSize(1); //在此监听中消费信息,并返回消费的状态信息 consumer.registerMessageListener((MessageListenerConcurrently) (msgs, context) -> { // 会把不同的消息分别放置到不同的队列中 for(Message msg:msgs){ log.info("接收到了消息:"+new String(msg.getBody())); } return ConsumeConcurrentlyStatus.CONSUME_SUCCESS; }); consumer.start(); } catch (Exception e) { e.printStackTrace(); } } @Override public void run(String... args) { this.messageListener(); } }
Producer--mq的生产类
import lombok.extern.slf4j.Slf4j; import org.apache.rocketmq.client.producer.DefaultMQProducer; import org.apache.rocketmq.client.producer.SendResult; import org.apache.rocketmq.common.message.Message; import org.apache.rocketmq.remoting.common.RemotingHelper; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Component; import javax.annotation.PostConstruct; /** * @Description:生产者 */ @Component @Slf4j public class Producer { /** * 生产者的组名 */ @Value("${apache.rocketmq.producer.producerGroup}") private String producerGroup; private DefaultMQProducer producer; /** * NameServer 地址 */ @Value("${apache.rocketmq.namesrvAddr}") private String namesrvAddr; @PostConstruct public void defaultMQProducer() { //生产者的组名 producer= new DefaultMQProducer(producerGroup); //指定NameServer地址,多个地址以 ; 隔开 producer.setNamesrvAddr(namesrvAddr); producer.setVipChannelEnabled(false); try { producer.start(); log.info("-------->:producer启动了"); } catch (Exception e) { e.printStackTrace(); } } public String sendMsg(String topic,String tags,String body){ log.info("start trans message"); SendResult result; try { Message message = new Message(topic, tags, body.getBytes(RemotingHelper.DEFAULT_CHARSET)); result = producer.send(message, (list, message1, o) -> { Integer id = (Integer) o; int index = id % list.size(); return list.get(index); },0); log.info("发送响应:MsgId:" + result.getMsgId() + ",发送状态:" + result.getSendStatus()); } catch (Exception e) { e.printStackTrace(); return "Error"; } return "{\"MsgId\":\""+result.getMsgId()+"\"}"; } }
以上就是全部common项目的代码啦,关于聊天部分的实体类,刚捋了一下,有点乱,大家按照实际情况调整吧,一定要和前端约定好发送和接受的接口字段就好啦。