大家好,我是中恒。工作中我们经常使用到自定义的开发工具类,本文就列举几个中恒在实际工作中常用的几个工具类,供弟兄们参考。如果本文对您有帮助,欢迎关注、点赞或分享您在工作中经常使用到的工具类。
日期处理
public class DateUtils {
// 日志
private static final Logger logger = Logger.getLogger(DateUtils.class);
/**
* 时间格式(yyyy-MM-dd)
*/
public final static String DATE_PATTERN = "yyyy-MM-dd";
/**
* 无分隔符日期格式 "yyyyMMddHHmmssSSS"
*/
public static String DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS_SSS = "yyyyMMddHHmmssSSS";
/**
* 时间格式(yyyy-MM-dd HH:mm:ss)
*/
public final static String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
private static String[] parsePatterns = {"yyyy-MM-dd", "yyyy-MM-dd HH:mm:ss", "yyyy-MM-dd HH:mm", "yyyy-MM", "yyyy/MM/dd", "yyyy/MM/dd HH:mm:ss", "yyyy/MM/dd HH:mm", "yyyy" +
"/MM", "yyyy.MM.dd", "yyyy.MM.dd HH:mm:ss", "yyyy.MM.dd HH:mm", "yyyy.MM"};
// 日期转换格式数组
public static String[][] regularExp = new String[][]{
// 默认格式
{"\d{4}-((([0][1,3-9]|[1][0-2]|[1-9])-([0-2]\d|[3][0,1]|[1-9]))|((02|2)-(([1-9])|[0-2]\d)))\s+([0,1]\d|[2][0-3]|\d):([0-5]\d|\d):([0-5]\d|\d)",
DATE_TIME_PATTERN},
// 仅日期格式 年月日
{"\d{4}-((([0][1,3-9]|[1][0-2]|[1-9])-([0-2]\d|[3][0,1]|[1-9]))|((02|2)-(([1-9])|[0-2]\d)))", DATE_PATTERN},
// 带毫秒格式
{"\d{4}((([0][1,3-9]|[1][0-2]|[1-9])([0-2]\d|[3][0,1]|[1-9]))|((02|2)(([1-9])|[0-2]\d)))([0,1]\d|[2][0-3])([0-5]\d|\d)([0-5]\d|\d)\d{1,3}",
DATE_TIME_PATTERN_YYYY_MM_DD_HH_MM_SS_SSS}};
public static String format(Date date) {
return format(date, DATE_PATTERN);
}
public static String format(Date date, String pattern) {
if (date != null) {
SimpleDateFormat df = new SimpleDateFormat(pattern);
return df.format(date);
}
return null;
}
public static String timeToStr(Long time, String pattern) {
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
if (time.toString().length() < 13) {
time = time * 1000L;
}
Date date = new Date(time);
String value = dateFormat.format(date);
return value;
}
public static long strToTime(String timeStr) {
Date time = strToDate(timeStr);
return time.getTime() / 1000;
}
/**
* 转换为时间类型格式
* @param strDate 日期
* @return
*/
public static Date strToDate(String strDate) {
try {
String strType = getDateFormat(strDate);
SimpleDateFormat sf = new SimpleDateFormat(strType);
return new Date((sf.parse(strDate).getTime()));
} catch (Exception e) {
return null;
}
}
/**
* 根据传入的日期格式字符串,获取日期的格式
* @return 秒
*/
public static String getDateFormat(String date_str) {
String style = null;
if (StringUtils.isEmpty(date_str)) {
return null;
}
boolean b = false;
for (int i = 0; i < regularExp.length; i++) {
b = date_str.matches(regularExp[i][0]);
if (b) {
style = regularExp[i][1];
}
}
if (StringUtils.isEmpty(style)) {
logger.info("date_str:" + date_str);
logger.info("日期格式获取出错,未识别的日期格式");
}
return style;
}
/**
* 将字符串类型的转换成Date类型
* @param dateStr 字符串类型的日期 yyyy-MM-dd
* @return Date类型的日期
* @throws ParseException
*/
public static Date convertStringToDate(String dateStr) {
// 返回的日期
Date resultDate = null;
try {
// 日期格式转换
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
resultDate = sdf.parse(dateStr);
} catch (ParseException e) {
e.printStackTrace();
}
return resultDate;
}
/**
* 日期型字符串转化为日期 格式
*/
public static Date parseDate(Object str) {
if (str == null) {
return null;
}
try {
return org.apache.commons.lang3.time.DateUtils.parseDate(str.toString(), parsePatterns);
} catch (ParseException e) {
return null;
}
}
}
Base64加密和解密
public class Base64Utils {
/**
* 加密
* @param str
* @return
*/
public static String encode(String str) {
Base64.Encoder encoder = Base64.getEncoder();
byte[] b = str.getBytes(StandardCharsets.UTF_8);
return encoder.encodeToString(b);
}
/**
* 解密
* @param s
* @return
*/
public static String decode(String s) {
Base64.Decoder decoder = Base64.getDecoder();
return new String(decoder.decode(s), StandardCharsets.UTF_8);
}
}
Bean工具类
public class BeanUtils extends org.springframework.beans.BeanUtils {
/**
* 默认忽略字段
*/
private static String[] IGNORE_PROPERTIES = {"createUser", "createTime"};
/**
* 重写copyProperties,NULL值,可以拷贝
* @param source 拷贝元实体
* @param target 拷贝目标实体
* @throws BeansException 抛出异常
*/
public static void copyProperties(Object source, Object target, String[] ignoreList) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
List ignorePropertyList = new ArrayList();
ignorePropertyList.addAll(Arrays.asList(IGNORE_PROPERTIES));
// 传入的忽略数组非空扩展忽略数组
if (ignoreList != null && ignoreList.length != 0) {
ignorePropertyList.addAll(Arrays.asList(ignoreList));
}
Class> actualEditable = target.getClass();
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
for (PropertyDescriptor targetPd : targetPds) {
if (targetPd.getWriteMethod() != null) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null && sourcePd.getReadMethod() != null && !ignorePropertyList.contains(targetPd.getName())) {
try {
Method readMethod = sourcePd.getReadMethod();
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
// 这里判断value是否为空,过滤Integer类型字段 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等
// if (value != null &&
// !"java.lang.Integer".equals(readMethod.getReturnType().getName())) {
// if (value != null && !"".equals(value)) {
Method writeMethod = targetPd.getWriteMethod();
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
// }
} catch (Throwable ex) {
throw new FatalBeanException("Could not copy properties "" + targetPd.getName() + "" from source to target", ex);
}
}
}
}
}
/**
* 重写copyProperties,忽略NULL值
* @param source
* @param target
* @throws BeansException
*/
public static void copyProperties(Object source, Object target) throws BeansException {
Assert.notNull(source, "Source must not be null");
Assert.notNull(target, "Target must not be null");
Class> actualEditable = target.getClass();
PropertyDescriptor[] targetPds = getPropertyDescriptors(actualEditable);
for (PropertyDescriptor targetPd : targetPds) {
if (targetPd.getWriteMethod() != null) {
PropertyDescriptor sourcePd = getPropertyDescriptor(source.getClass(), targetPd.getName());
if (sourcePd != null && sourcePd.getReadMethod() != null) {
try {
Method readMethod = sourcePd.getReadMethod();
if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
readMethod.setAccessible(true);
}
Object value = readMethod.invoke(source);
// 这里判断value是否为空,过滤Integer类型字段 当然这里也能进行一些特殊要求的处理 例如绑定时格式转换等等
// if (value != null && !"java.lang.Integer".equals(readMethod.getReturnType().getName())) {
if (value != null && !"".equals(value)) {
Method writeMethod = targetPd.getWriteMethod();
if (!Modifier.isPublic(writeMethod.getDeclaringClass().getModifiers())) {
writeMethod.setAccessible(true);
}
writeMethod.invoke(target, value);
}
} catch (Throwable ex) {
throw new FatalBeanException("Could not copy properties "" + targetPd.getName() + "" from source to target", ex);
}
}
}
}
}
/**
* bean 转为map
* @param obj bean对象
* @param isAllowNull 空字段是否转换 false 不转换
* @return map值
*/
public static Map bean2Map(Object obj, boolean isAllowNull) {
if (obj == null) {
return null;
}
Map map = new HashMap();
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
// 过滤class属性
if (!key.equals("class")) {
// 得到property对应的getter方法
Method getter = property.getReadMethod();
Object value = getter.invoke(obj);
if (isAllowNull || value != null && !value.toString().isEmpty()) {
map.put(key, value);
}
}
}
} catch (Exception e) {
System.out.println("transBean2Map Error " + e);
}
return map;
}
/**
* map转bean
* @param targetMap 被转化的map
* @param obj 对象
*/
public static void map2Bean(Map targetMap, Object obj) {
Map map = new HashMap();
for (String key : targetMap.keySet()) {
Object value = targetMap.get(key);
map.put(StringUtils.lineToHump(key), value);
}
try {
BeanInfo beanInfo = Introspector.getBeanInfo(obj.getClass());
PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();
for (PropertyDescriptor property : propertyDescriptors) {
String key = property.getName();
if (map.containsKey(key)) {
try {
Object value = map.get(key);
// 得到property对应的setter方法
Method setter = property.getWriteMethod();
setter.invoke(obj, value);
} catch (Exception e) {
throw new RuntimeException("实体转换错误:" + key);
}
}
}
} catch (Exception e) {
e.getStackTrace();
throw new RuntimeException("数据转换异常!");
}
}
}
cookie处理工具类
public class CookieUtils {
/**
* 得到Cookie的值, 不编码
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName) {
return getCookieValue(request, cookieName, false);
}
/**
* 得到Cookie的值,
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, boolean isDecoder) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
if (isDecoder) {
retValue = URLDecoder.decode(cookieList[i].getValue(), "UTF-8");
} else {
retValue = cookieList[i].getValue();
}
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}
/**
* 得到Cookie的值,
* @param request
* @param cookieName
* @return
*/
public static String getCookieValue(HttpServletRequest request, String cookieName, String encodeString) {
Cookie[] cookieList = request.getCookies();
if (cookieList == null || cookieName == null) {
return null;
}
String retValue = null;
try {
for (int i = 0; i < cookieList.length; i++) {
if (cookieList[i].getName().equals(cookieName)) {
retValue = URLDecoder.decode(cookieList[i].getValue(), encodeString);
break;
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return retValue;
}
/**
* 设置Cookie的值 不设置生效时间默认浏览器关闭即失效,也不编码
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue) {
setCookie(request, response, cookieName, cookieValue, -1);
}
/**
* 设置Cookie的值 在指定时间内生效,但不编码
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage) {
setCookie(request, response, cookieName, cookieValue, cookieMaxage, false);
}
/**
* 设置Cookie的值 不设置生效时间,但编码
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, boolean isEncode) {
setCookie(request, response, cookieName, cookieValue, -1, isEncode);
}
/**
* 设置Cookie的值 在指定时间内生效, 编码参数
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, isEncode);
}
/**
* 设置Cookie的值 在指定时间内生效, 编码参数(指定编码)
*/
public static void setCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
doSetCookie(request, response, cookieName, cookieValue, cookieMaxage, encodeString);
}
/**
* 删除Cookie带cookie域名
*/
public static void deleteCookie(HttpServletRequest request, HttpServletResponse response, String cookieName) {
doSetCookie(request, response, cookieName, "", -1, false);
}
/**
* 设置Cookie的值,并使其在指定时间内生效
* @param cookieMaxage cookie生效的最大秒数
*/
public static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, boolean isEncode) {
try {
if (cookieValue == null) {
cookieValue = "";
} else if (isEncode) {
cookieValue = URLEncoder.encode(cookieValue, "utf-8");
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0) {
cookie.setMaxAge(cookieMaxage);
}
String domainName = getDomainName(request);
cookie.setDomain(domainName);
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 设置Cookie的值,并使其在指定时间内生效
* @param cookieMaxage cookie生效的最大秒数
*/
public static final void doSetCookie(HttpServletRequest request, HttpServletResponse response, String cookieName, String cookieValue, int cookieMaxage, String encodeString) {
try {
if (cookieValue == null) {
cookieValue = "";
} else {
cookieValue = URLEncoder.encode(cookieValue, encodeString);
}
Cookie cookie = new Cookie(cookieName, cookieValue);
if (cookieMaxage > 0) {
cookie.setMaxAge(cookieMaxage);
}
if (null != request) {// 设置域名的cookie
String domainName = getDomainName(request);
cookie.setDomain(domainName);
}
cookie.setPath("/");
response.addCookie(cookie);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 得到cookie的域名
*/
private static final String getDomainName(HttpServletRequest request) {
String domainName = null;
String serverName = request.getRequestURL().toString();
if (serverName == null || serverName.equals("")) {
domainName = "";
} else {
serverName = serverName.toLowerCase();
serverName = serverName.substring(7);
final int end = serverName.indexOf("/");
serverName = serverName.substring(0, end);
final String[] domains = serverName.split("\.");
int len = domains.length;
if (len > 3) {
// www.xxx.com.cn
domainName = "." + domains[len - 3] + "." + domains[len - 2] + "." + domains[len - 1];
} else if (len <= 3 && len > 1) {
// xxx.com or xxx.cn
domainName = "." + domains[len - 2] + "." + domains[len - 1];
} else {
domainName = serverName;
}
}
if (domainName != null && domainName.indexOf(":") > 0) {
String[] ary = domainName.split("\:");
domainName = ary[0];
}
return domainName;
}
}
ID 生成工具类
public class IdUtils {
/**
* 主要功能:生成流水号 yyyyMMddHHmmssSSS + 3位随机数
* 注意事项:无
* @return 流水号
*/
public static String createIdByDate() {
// 精确到毫秒
SimpleDateFormat fmt = new SimpleDateFormat("(yyyyMMddHHmmssSSS)");
String suffix = fmt.format(new Date());
suffix = suffix + "-" + Math.round((Math.random() * 100000));
return suffix;
}
/**
* 主要功能:生成uuid
* 注意事项:无
* @return uuid 32 位
*/
public static String createIdbyUUID() {
return UUID.randomUUID().toString().replaceAll("-", "");
}
/**
* 获取随机UUID
* @return 随机UUID
*/
public static String randomUUID() {
return UUID.randomUUID().toString();
}
/**
* 简化的UUID,去掉了横线
* @return 简化的UUID,去掉了横线
*/
public static String simpleUUID() {
return UUID.randomUUID().toString(true);
}
/**
* 获取随机UUID,使用性能更好的ThreadLocalRandom生成UUID
* @return 随机UUID
*/
public static String fastUUID() {
return UUID.fastUUID().toString();
}
/**
* 简化的UUID,去掉了横线,使用性能更好的ThreadLocalRandom生成UUID
* @return 简化的UUID,去掉了横线
*/
public static String fastSimpleUUID() {
return UUID.fastUUID().toString(true);
}
}
Redis工具类
@Component
public class RedisUtils {
private Logger log = LoggerFactory.getLogger(this.getClass());
/**
* 默认编码
*/
private static final Charset DEFAULT_CHARSET = StandardCharsets.UTF_8;
/**
* key序列化
*/
private static final StringRedisSerializer STRING_SERIALIZER = new StringRedisSerializer();
/**
* value 序列化
*/
private static final JdkSerializationRedisSerializer OBJECT_SERIALIZER = new JdkSerializationRedisSerializer();
/**
* Spring Redis Template
*/
private RedisTemplate redisTemplate;
/**
* spring自动调用注入redisTemplate
*/
public RedisUtils(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
//设置序列化器
this.redisTemplate.setKeySerializer(STRING_SERIALIZER);
this.redisTemplate.setValueSerializer(OBJECT_SERIALIZER);
this.redisTemplate.setHashKeySerializer(STRING_SERIALIZER);
this.redisTemplate.setHashValueSerializer(OBJECT_SERIALIZER);
}
/**
* 获取链接工厂
*/
public RedisConnectionFactory getConnectionFactory() {
return this.redisTemplate.getConnectionFactory();
}
/**
* 获取 RedisTemplate对象
*/
public RedisTemplate getRedisTemplate() {
return redisTemplate;
}
/**
* 清空DB
* @param node redis 节点
*/
public void flushDB(RedisClusterNode node) {
this.redisTemplate.opsForCluster().flushDb(node);
}
/**
* 添加到带有 过期时间的 缓存
* @param key redis主键
* @param value 值
* @param time 过期时间(单位秒)
*/
public void setExpire(final byte[] key, final byte[] value, final long time) {
redisTemplate.execute((RedisCallback) connection -> {
connection.setEx(key, time, value);
log.debug("[redisTemplate redis]放入 缓存 url:{} ========缓存时间为{}秒", key, time);
return 1L;
});
}
/**
* 添加到带有 过期时间的 缓存
* @param key redis主键
* @param value 值
* @param time 过期时间(单位秒)
*/
public void setExpire(final String key, final Object value, final long time) {
redisTemplate.execute((RedisCallback) connection -> {
RedisSerializer serializer = getRedisSerializer();
byte[] keys = serializer.serialize(key);
byte[] values = OBJECT_SERIALIZER.serialize(value);
connection.setEx(keys, time, values);
return 1L;
});
}
/**
* 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销
* @param keys redis主键数组
* @param values 值数组
* @param time 过期时间(单位秒)
*/
public void setExpire(final String[] keys, final Object[] values, final long time) {
redisTemplate.execute((RedisCallback) connection -> {
RedisSerializer serializer = getRedisSerializer();
for (int i = 0; i < keys.length; i++) {
byte[] bKeys = serializer.serialize(keys[i]);
byte[] bValues = OBJECT_SERIALIZER.serialize(values[i]);
connection.setEx(bKeys, time, bValues);
}
return 1L;
});
}
/**
* 一次性添加数组到 过期时间的 缓存,不用多次连接,节省开销
* @param keys the keys
* @param values the values
*/
public void set(final String[] keys, final Object[] values) {
redisTemplate.execute((RedisCallback) connection -> {
RedisSerializer serializer = getRedisSerializer();
for (int i = 0; i < keys.length; i++) {
byte[] bKeys = serializer.serialize(keys[i]);
byte[] bValues = OBJECT_SERIALIZER.serialize(values[i]);
connection.set(bKeys, bValues);
}
return 1L;
});
}
/**
* 添加到缓存
*
* @param key the key
* @param value the value
*/
public void set(final String key, final Object value) {
redisTemplate.execute((RedisCallback) connection -> {
RedisSerializer serializer = getRedisSerializer();
byte[] keys = serializer.serialize(key);
byte[] values = OBJECT_SERIALIZER.serialize(value);
connection.set(keys, values);
log.debug("[redisTemplate redis]放入 缓存 url:{}", key);
return 1L;
});
}
/**
* 查询在这个时间段内即将过期的key
* @param key the key
* @param time the time
* @return the list
*/
public List willExpire(final String key, final long time) {
final List keysList = new ArrayList<>();
redisTemplate.execute((RedisCallback>) connection -> {
Set keys = redisTemplate.keys(key + "*");
for (String key1 : keys) {
Long ttl = connection.ttl(key1.getBytes(DEFAULT_CHARSET));
if (0 <= ttl && ttl <= 2 * time) {
keysList.add(key1);
}
}
return keysList;
});
return keysList;
}
/**
* 查询在以keyPatten的所有 key
*
* @param keyPatten the key patten
* @return the set
*/
public Set keys(final String keyPatten) {
return redisTemplate.execute((RedisCallback>) connection -> redisTemplate.keys(keyPatten + "*"));
}
/**
* 根据key获取对象
*
* @param key the key
* @return the byte [ ]
*/
public byte[] get(final byte[] key) {
byte[] result = redisTemplate.execute((RedisCallback) connection -> connection.get(key));
log.debug("[redisTemplate redis]取出 缓存 url:{} ", key);
return result;
}
/**
* 根据key获取对象
*
* @param key the key
* @return the string
*/
public Object get(final String key) {
Object resultStr = redisTemplate.execute((RedisCallback
如果您在实际工作中有比较实用的工具类,欢迎分享一下,一起学习提高!