java工具类方法
1.生成16位数字(当时日期时间加随机两位数)
public static String getNo16() {
String getNo = getNo();
return getNo.substring(0, getNo.length() - 4);
}
//生成年月日时分秒+随机6位数
public static String getNo() {
Calendar c = Calendar.getInstance();
String year = String.valueOf(c.get(Calendar.YEAR));
String month = String.valueOf(c.get(Calendar.MONTH) + 1);
String day = String.valueOf(c.get(Calendar.DAY_OF_MONTH));
String hours = String.valueOf(c.get(Calendar.HOUR_OF_DAY));
String m = String.valueOf(c.get(Calendar.MINUTE));
String s = String.valueOf(c.get(Calendar.SECOND));
if (month.length() == 1) {
month = "0" + month;
} if (day.length() == 1) {
day = "0" + day;
}
if (hours.length() == 1) {
hours = "0" + hours;
}
if (m.length() == 1) {
m = "0" + m;
}
if (s.length() == 1) {
s = "0" + s;
}
return year + month + day + hours + m + s + getN(6);
}
//获取4-8位随机数
public static int getN(int num) {
Random random = new Random();
int number = 0;
switch (num) {
case 4:
number = random.nextInt(8999) + 1000;
break;
case 5:
number = random.nextInt(89999) + 10000;
break;
case 6:
number = random.nextInt(899999) + 100000;
break;
case 7:
number = random.nextInt(8999999) + 1000000;
break;
case 8:
number = random.nextInt(8999999) + 10000000;
break;
default:
number = random.nextInt(8999999) + 1000000;// 默认7位
break;
}
return number;
}
2.判断非空
public static boolean isEmpty(Object str) {
return str == null || "".equals(str) || String.valueOf(str).length() == 0
|| String.valueOf(str).matches("\\s*");
} public static boolean isNotEmpty(Object str){
return !isEmpty(str);
}
Java工具类:
时间:
package com.yingjun.ssm.util; import java.text.SimpleDateFormat;
import java.util.Date; /**
* TimeUtils
*
*/
public class TimeUtils {
private final static long minute = 60 * 1000;// 1分钟
private final static long hour = 60 * minute;// 1小时
private final static long day = 24 * hour;// 1天
private final static long month = 31 * day;// 月
private final static long year = 12 * month;// 年 public static final SimpleDateFormat DATE_FORMAT_DATE_D = new SimpleDateFormat("yyyy-MM-dd");
public static final SimpleDateFormat DATE_FORMAT_DATE_M = new SimpleDateFormat("yyyy-MM-dd HH:mm");
public static final SimpleDateFormat DATE_FORMAT_DATE_S = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); private TimeUtils() {
throw new AssertionError();
} /**
* long time to string
*
* @param timeInMillis
* @param dateFormat
* @return
*/
public static String getTime(long timeInMillis, SimpleDateFormat dateFormat) {
return dateFormat.format(new Date(timeInMillis));
} /**
* long time to string, format is {@link #DEFAULT_DATE_FORMAT}
*
* @param timeInMillis
* @return
*/
public static String getTime(long timeInMillis) {
return getTime(timeInMillis, DATE_FORMAT_DATE_S);
} /**
* get current time in milliseconds
*
* @return
*/
public static long getCurrentTimeInLong() {
return System.currentTimeMillis();
} /**
* get current time in milliseconds, format is {@link #DEFAULT_DATE_FORMAT}
*
* @return
*/
public static String getCurrentTimeInString() {
return getTime(getCurrentTimeInLong());
} /**
* get current time in milliseconds
*
* @return
*/
public static String getCurrentTimeInString(SimpleDateFormat dateFormat) {
return getTime(getCurrentTimeInLong(), dateFormat);
} public static String getTimeFormatText(Date date) {
if (date == null) {
return null;
}
long diff = new Date().getTime() - date.getTime();
long r = 0;
if (diff > year) {
r = (diff / year);
return r + "年前";
}
if (diff > month) {
r = (diff / month);
return r + "个月前";
}
if (diff > day) {
r = (diff / day);
return r + "天前";
}
if (diff > hour) {
r = (diff / hour);
return r + "小时前";
}
if (diff > minute) {
r = (diff / minute);
return r + "分钟前";
}
return "刚刚";
}
}
请求的返回类型封装JSON结果:
package com.yingjun.ssm.dto; import com.fasterxml.jackson.annotation.JsonInclude; import java.io.Serializable; /**
*
* @author yingjun
*
* ajax 请求的返回类型封装JSON结果
*/
@JsonInclude(JsonInclude.Include.NON_NULL)
public class BaseResult<T> implements Serializable { private static final long serialVersionUID = -4185151304730685014L; private boolean success; private T data; private String error; public BaseResult(boolean success, String error) {
this.success = success;
this.error = error;
} public BaseResult(boolean success, T data) {
this.success = success;
this.data = data;
} public boolean isSuccess() {
return success;
} public void setSuccess(boolean success) {
this.success = success;
} public T getData() {
return data;
} public void setData(T data) {
this.data = data;
} public String getError() {
return error;
} public void setError(String error) {
this.error = error;
} @Override
public String toString() {
return "BaseResult [success=" + success + ", data=" + data + ", error=" + error + "]";
} }
对未处理的错误信息做一个统一处理:
package com.yingjun.ssm.exception; import com.alibaba.fastjson.JSON;
import com.yingjun.ssm.dto.BaseResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter; /**
* 错误信息统一处理
* 对未处理的错误信息做一个统一处理
* @author yingjun
*
*/
@Component
public class GlobalExceptionResolver implements HandlerExceptionResolver { private final Logger LOG = LoggerFactory.getLogger(this.getClass()); @ResponseBody
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) {
LOG.error("访问" + request.getRequestURI() + " 发生错误, 错误信息:" + ex.getMessage());
//这里有2种选择
//跳转到定制化的错误页面
/*ModelAndView error = new ModelAndView("error");
error.addObject("exMsg", ex.getMessage());
error.addObject("exType", ex.getClass().getSimpleName().replace("\"", "'"));*/
//返回json格式的错误信息
try {
PrintWriter writer = response.getWriter();
BaseResult<String> result=new BaseResult(false, ex.getMessage());
writer.write(JSON.toJSONString(result));
writer.flush();
} catch (Exception e) {
LOG.error("Exception:",e);
}
return null;
} }
spring配置文件需加上如下:
<!--全局异常捕捉 -->
<bean class="com.yingjun.ssm.exception.GlobalExceptionResolver" />
序列化工具类:
package com.yingjun.ssm.util; import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.List; import com.dyuproject.protostuff.LinkedBuffer;
import com.dyuproject.protostuff.ProtostuffIOUtil;
import com.dyuproject.protostuff.Schema;
import com.dyuproject.protostuff.runtime.RuntimeSchema; /**
* 序列话工具
*/
public class ProtoStuffSerializerUtil { /**
* 序列化对象
* @param obj
* @return
*/
public static <T> byte[] serialize(T obj) {
if (obj == null) {
throw new RuntimeException("序列化对象(" + obj + ")!");
}
@SuppressWarnings("unchecked")
Schema<T> schema = (Schema<T>) RuntimeSchema.getSchema(obj.getClass());
LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
byte[] protostuff = null;
try {
protostuff = ProtostuffIOUtil.toByteArray(obj, schema, buffer);
} catch (Exception e) {
throw new RuntimeException("序列化(" + obj.getClass() + ")对象(" + obj + ")发生异常!", e);
} finally {
buffer.clear();
}
return protostuff;
} /**
* 反序列化对象
* @param paramArrayOfByte
* @param targetClass
* @return
*/
public static <T> T deserialize(byte[] paramArrayOfByte, Class<T> targetClass) {
if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
}
T instance = null;
try {
instance = targetClass.newInstance();
} catch (InstantiationException | IllegalAccessException e) {
throw new RuntimeException("反序列化过程中依据类型创建对象失败!", e);
}
Schema<T> schema = RuntimeSchema.getSchema(targetClass);
ProtostuffIOUtil.mergeFrom(paramArrayOfByte, instance, schema);
return instance;
} /**
* 序列化列表
* @param objList
* @return
*/
public static <T> byte[] serializeList(List<T> objList) {
if (objList == null || objList.isEmpty()) {
throw new RuntimeException("序列化对象列表(" + objList + ")参数异常!");
}
@SuppressWarnings("unchecked")
Schema<T> schema = (Schema<T>) RuntimeSchema.getSchema(objList.get(0).getClass());
LinkedBuffer buffer = LinkedBuffer.allocate(1024 * 1024);
byte[] protostuff = null;
ByteArrayOutputStream bos = null;
try {
bos = new ByteArrayOutputStream();
ProtostuffIOUtil.writeListTo(bos, objList, schema, buffer);
protostuff = bos.toByteArray();
} catch (Exception e) {
throw new RuntimeException("序列化对象列表(" + objList + ")发生异常!", e);
} finally {
buffer.clear();
try {
if (bos != null) {
bos.close();
}
} catch (IOException e) {
e.printStackTrace();
}
} return protostuff;
} /**
* 反序列化列表
* @param paramArrayOfByte
* @param targetClass
* @return
*/
public static <T> List<T> deserializeList(byte[] paramArrayOfByte, Class<T> targetClass) {
if (paramArrayOfByte == null || paramArrayOfByte.length == 0) {
throw new RuntimeException("反序列化对象发生异常,byte序列为空!");
} Schema<T> schema = RuntimeSchema.getSchema(targetClass);
List<T> result = null;
try {
result = ProtostuffIOUtil.parseListFrom(new ByteArrayInputStream(paramArrayOfByte), schema);
} catch (IOException e) {
throw new RuntimeException("反序列化对象列表发生异常!", e);
}
return result;
} }
redis缓存:
package com.yingjun.ssm.cache; import com.yingjun.ssm.util.ProtoStuffSerializerUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component; import java.util.List;
import java.util.Set; /**
* redis缓存
*
* @author yingjun
*
*/
@Component
public class RedisCache { public final static String CAHCENAME="cache";//缓存名
public final static int CAHCETIME=60;//默认缓存时间 @Autowired
private RedisTemplate<String, String> redisTemplate; public <T> boolean putCache(String key, T obj) {
final byte[] bkey = key.getBytes();
final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
return connection.setNX(bkey, bvalue);
}
});
return result;
} public <T> void putCacheWithExpireTime(String key, T obj, final long expireTime) {
final byte[] bkey = key.getBytes();
final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
connection.setEx(bkey, expireTime, bvalue);
return true;
}
});
} public <T> boolean putListCache(String key, List<T> objList) {
final byte[] bkey = key.getBytes();
final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList);
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
return connection.setNX(bkey, bvalue);
}
});
return result;
} public <T> boolean putListCacheWithExpireTime(String key, List<T> objList, final long expireTime) {
final byte[] bkey = key.getBytes();
final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList);
boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
@Override
public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
connection.setEx(bkey, expireTime, bvalue);
return true;
}
});
return result;
} public <T> T getCache(final String key, Class<T> targetClass) {
byte[] result = redisTemplate.execute(new RedisCallback<byte[]>() {
@Override
public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
return connection.get(key.getBytes());
}
});
if (result == null) {
return null;
}
return ProtoStuffSerializerUtil.deserialize(result, targetClass);
} public <T> List<T> getListCache(final String key, Class<T> targetClass) {
byte[] result = redisTemplate.execute(new RedisCallback<byte[]>() {
@Override
public byte[] doInRedis(RedisConnection connection) throws DataAccessException {
return connection.get(key.getBytes());
}
});
if (result == null) {
return null;
}
return ProtoStuffSerializerUtil.deserializeList(result, targetClass);
} /**
* 精确删除key
*
* @param key
*/
public void deleteCache(String key) {
redisTemplate.delete(key);
} /**
* 模糊删除key
*
* @param pattern
*/
public void deleteCacheWithPattern(String pattern) {
Set<String> keys = redisTemplate.keys(pattern);
redisTemplate.delete(keys);
} /**
* 清空所有缓存
*/
public void clearCache() {
deleteCacheWithPattern(RedisCache.CAHCENAME+"|*");
}
}
redis缓存,采用Jedis Cluster
package com.yingjun.ssm.cache; import com.yingjun.ssm.util.ProtoStuffSerializerUtil;
import org.springframework.stereotype.Component;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPool; import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set; /**
* redis缓存
*
* 采用Jedis Cluster
*
* @author yingjun
*
*/
@Component
public class RedisClusterCache { public final static String CAHCENAME="cache";//缓存名
public final static int CAHCETIME=60;//默认缓存时间 //@Autowired
private JedisCluster jedisCluster; public <T> void putCache(String key, T obj) {
final byte[] bkey = key.getBytes();
final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
jedisCluster.set(bkey,bvalue);
} public <T> void putCacheWithExpireTime(String key, T obj, int expireTime) {
final byte[] bkey = key.getBytes();
final byte[] bvalue = ProtoStuffSerializerUtil.serialize(obj);
jedisCluster.setex(bkey, expireTime, bvalue);
} public <T> void putListCache(String key, List<T> objList) {
final byte[] bkey = key.getBytes();
final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList);
jedisCluster.set(bkey,bvalue);
} public <T> void putListCacheWithExpireTime(String key, List<T> objList, int expireTime) {
final byte[] bkey = key.getBytes();
final byte[] bvalue = ProtoStuffSerializerUtil.serializeList(objList);
jedisCluster.setex(bkey, expireTime, bvalue);
} public <T> T getCache(final String key, Class<T> targetClass) {
byte[] result =jedisCluster.get(key.getBytes());
if (result == null) {
return null;
}
return ProtoStuffSerializerUtil.deserialize(result, targetClass);
} public <T> List<T> getListCache(String key, Class<T> targetClass) {
byte[] result =jedisCluster.get(key.getBytes());
if (result == null) {
return null;
}
return ProtoStuffSerializerUtil.deserializeList(result, targetClass);
} /**
* 精确删除key
*
* @param key
*/
public void deleteCache(String key) {
jedisCluster.del(key);
} /**
* 模糊删除key
*
* @param pattern
*/
public void deleteCacheWithPattern(String pattern) {
Set<String> keys =this.keys(pattern);
for(String key:keys){
jedisCluster.del(key);
}
} /**
* 清空所有缓存
*/
public void clearCache() {
deleteCacheWithPattern(RedisClusterCache.CAHCENAME+"|*");
} /**
* 由于JedisCluster没有提供对keys命令的封装,只能自己实现
* @param pattern
* @return
*/
public Set<String> keys(String pattern){
Set<String> keys = new HashSet<>();
Map<String, JedisPool> clusterNodes = jedisCluster.getClusterNodes();
for(String k : clusterNodes.keySet()){
JedisPool jp = clusterNodes.get(k);
Jedis connection = jp.getResource();
try {
keys.addAll(connection.keys(pattern));
} catch(Exception e){
e.printStackTrace();
} finally{
//用完一定要close这个链接!!!
connection.close();
}
}
return keys;
}
}
JedisCluster 集群高可用配置需加:
<bean id="jedisCluster" class="redis.clients.jedis.JedisCluster">
<constructor-arg index="0">
<set>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg index="0" value="${redis.ip1}" />
<constructor-arg index="1" value="${redis.port1}" type="int" />
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg index="0" value="${redis.ip2}" />
<constructor-arg index="1" value="${redis.port2}" type="int" />
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg index="0" value="${redis.ip3}" />
<constructor-arg index="1" value="${redis.port3}" type="int" />
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg index="0" value="${redis.ip4}" />
<constructor-arg index="1" value="${redis.port4}" type="int" />
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg index="0" value="${redis.ip5}" />
<constructor-arg index="1" value="${redis.port5}" type="int" />
</bean>
<bean class="redis.clients.jedis.HostAndPort">
<constructor-arg index="0" value="${redis.ip6}" />
<constructor-arg index="1" value="${redis.port6}" type="int" />
</bean>
</set>
</constructor-arg>
<constructor-arg index="1" value="2000" type="int"></constructor-arg>
<constructor-arg index="2" value="100" type="int"></constructor-arg>
<constructor-arg index="3" ref="jedisPoolConfig"></constructor-arg>
</bean>
获取指定字数的字符:
private String getNumber(int size) {
String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
String number = "";
Random r = new Random();
for (int i = 0; i < size; i++) {
number += str.charAt(r.nextInt(str.length()));
}
return number;
}
java工具类方法的更多相关文章
- Java 调用http接口(基于OkHttp的Http工具类方法示例)
目录 Java 调用http接口(基于OkHttp的Http工具类方法示例) OkHttp3 MAVEN依赖 Http get操作示例 Http Post操作示例 Http 超时控制 工具类示例 Ja ...
- Java工具类之——BigDecimal运算封装(包含金额的计算方式)
日常对于金额计算,应该都是用的BigDecimal, 可是苦于没有好的工具类方法,现在贡献一个我正在用的对于数字计算的工具类,项目中就是用的这个,简单粗暴好用,话不多说,代码奉上(该工具类需要引入g ...
- 排名前 16 的 Java 工具类
在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...
- 排名前16的Java工具类
原文:https://www.jianshu.com/p/9e937d178203 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法 ...
- 创建Jmeter中使用的jar包中的工具类方法
1. 在IDEA中新建一个maven工程. 2. 编写工具类方法,如加密算法.此处以加法为例. package DemoTest; public class DemoClass{ public int ...
- jxl java工具类,导出excel,导入数据库
1: 引入jxl jar 我使用的为maven管理, <!--Excel工具--> <dependency> <groupId>net.sourceforge.je ...
- 干货:排名前16的Java工具类
在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...
- 常用高效 Java 工具类总结
一.前言 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码 ...
- 16 个超级实用的 Java 工具类
阅读本文大概需要 4 分钟. 出处:alterem juejin.im/post/5d4a25b351882505c105cc6e 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用 ...
随机推荐
- BuilderPattern(建造者模式)-----Java/.Net
建造者模式(Builder Pattern)使用多个简单的对象一步一步构建成一个复杂的对象.这种类型的设计模式属于创建型模式,它提供了一种创建对象的最佳方式
- Atlas 读写分离
1.前置条件 需要配置好mysql 主从 主库:192.168.28.137:16205 从库:192.168.28.135:16205 Atlas:192.168.28.139 2.Atlas 部署 ...
- mysql-5.7.9-winx64遇坑记
昨天在mysql5.0上导入sql文件时,一直卡在一个地方报错,也没仔细分析,认为应该是mysql版本太低不支持这个语法而已.遂决心下载一个最新版本的mysql,却浑然不知前面无数的坑已经埋伏好了在等 ...
- Dockerfile文件记录(用于后端项目部署)
Dockerfile文件记录(用于后端项目部署) 本教程依据个人理解并经过实际验证为正确,特此记录下来,权当笔记. 注:基于linux操作系统(敏感信息都进行了处理) 此文结合另一篇博客共同构成后端服 ...
- Don’t Repeat Yourself,Repeat Yourself
Don't Repeat Yourself,Repeat Yourself Don't repeat yourself (DRY, or sometimes do not repeat yoursel ...
- JetBrains Pycharm破解,含破解文件和安装包2019.2版
此教程支持最新的2019.3版本的Pycharm,并兼容之前的版本. 一.准备工作: 1.下载Pycharm 有条件的可以自行去官网下载,这里我提供了我下载的版本,已上传到百度网盘,链接在下方. 2. ...
- ArcGIS Enterprise 10.6 (Windows)安装及部署图解
目录 前言 1 本地环境配置 1.1 机器名修改 1.2 安装和配置IIS 2 ArcGIS for Server 2.1 安装 ArcGIS for Server 2.2 配置 ArcGIS for ...
- ATOM插件及快捷键
xml-formatter :https://atom.io/packages/xml-formatter xml格式化工具 SHIFT-CTRL-X:快速格式化 SHIFT-CTRL-M:移除换行符 ...
- win + ubuntu 双系统 grub引导项修复
ubuntu liveCD模式,找到ubuntu的系统盘位置,挂载到系统上面,然后使用grub进行修复 ubuntu liveCD模式下是用boot-repair软件进行修复 grub急救模式 1. ...
- Thinkpad S440 I/O接口配置
HDMI 视频接口 SS USB3.0接口 电源接口 音频接口 网络接口 没有com口可以用USB口,然后安装一个USB转com口的驱动.