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中使用 ...
随机推荐
- SpringBoot原理分析与配置
1.1 起步依赖原理分析 1.1.1 分析spring-boot-starter-parent 按住Ctrl点击pom.xml中的spring-boot-starter-parent,跳转到了spri ...
- vue 源码 学习days8-比较两个对象的方法
// 在面试中可能会遇到, 思想重要 // 比较两个对象是否是相等的 两个对象 // 1. js 中对象是无法使用 == 来比较的, 比是地址 // 2. 我们一般会定义如果对象的各个属性值都相等 那 ...
- 基于GMC/umat的复合材料宏细观渐近损伤分析(一)
近期在开展基于GMC/umat的复合材料宏细观渐近损伤分析,一些技术细节分享如下: 1.理论基础 针对连续纤维增强复合材料,可以通过离散化获得如下的模型: (a)(b)(c) 图1 连续纤维增强复合材 ...
- 菜鸟学习Fabric源码学习 — 背书节点和链码容器交互
Fabric 1.4 源码分析 背书节点和链码容器交互 本文档主要介绍背书节点和链码容器交互流程,在Endorser背书节点章节中,无论是deploy.upgrade或者调用链码,最后都会调用Chai ...
- Spring Boot从零入门2_核心模块详述和开发环境搭建
目录 1 前言 2 名词术语 3 Spring Boot核心模块 3.1 spring-boot(主模块) 3.2 spring-boot-starters(起步依赖) 3.3 spring-boot ...
- Python使用requests爬取一个网页并保存
#导入 requests模块import requests #设置请求头,让网站监测是浏览器 headers = { 'user-agent': 'Mozilla/5.0 (Windows NT 6. ...
- 如何使用F4的IRAM2内存
在使用KEIL做F4的项目的时候发现RAM区有片上IRAM2选项,查了datesheet后发现这块是CCM内存区 CCM内存是在地址0x1000000映射的64KB块,只提供CPU通过数据D总线进行访 ...
- 力扣337——打家劫舍 III
这一篇也是基于"打家劫舍"的扩展,需要针对特殊情况特殊考虑,当然其本质还是动态规划,优化时需要考虑数据结构. 原题 在上次打劫完一条街道之后和一圈房屋后,小偷又发现了一个新的可行窃 ...
- 高通量计算框架HTCondor(四)——案例准备
目录 1. 正文 1.1. 任务划分 1.2. 任务程序 2. 相关 1. 正文 1.1. 任务划分 使用高通量计算第一步就是要针对密集运算任务做任务划分.将一个海量的.耗时的.耗资源的任务划分成合适 ...
- CTF中关于XXE(XML外部实体注入)题目两道
题目:UNCTF-Do you like xml? 链接:http://112.74.37.15:8008/ hint:weak password (弱密码) 1.观察后下载图片拖进WINHEX发现提 ...