大家好,我是中恆。工作中我們經常使用到自定義的開發工具類,本文就列舉幾個中恆在實際工作中常用的幾個工具類,供弟兄們參考。如果本文對您有幫助,歡迎關注、點贊或分享您在工作中經常使用到的工具類。
日期處理
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 {
/**
* 默認忽略欄位<br>
*/
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<String> ignorePropertyList = new ArrayList<String>();
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<String, Object> bean2Map(Object obj, boolean isAllowNull) {
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();
// 過濾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<String, Object> targetMap, Object obj) {
Map<String, Object> map = new HashMap<String, Object>();
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<String, Object> redisTemplate;
/**
* spring自動調用注入redisTemplate
*/
public RedisUtils(RedisTemplate<String, Object> 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<String, Object> 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<Long>) 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<Long>) connection -> {
RedisSerializer<String> 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<Long>) connection -> {
RedisSerializer<String> 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<Long>) connection -> {
RedisSerializer<String> 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<Long>) connection -> {
RedisSerializer<String> 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<String> willExpire(final String key, final long time) {
final List<String> keysList = new ArrayList<>();
redisTemplate.execute((RedisCallback<List<String>>) connection -> {
Set<String> 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<String> keys(final String keyPatten) {
return redisTemplate.execute((RedisCallback<Set<String>>) connection -> redisTemplate.keys(keyPatten + "*"));
}
/**
* 根據key獲取對象
*
* @param key the key
* @return the byte [ ]
*/
public byte[] get(final byte[] key) {
byte[] result = redisTemplate.execute((RedisCallback<byte[]>) 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<Object>) connection -> {
RedisSerializer<String> serializer = getRedisSerializer();
byte[] keys = serializer.serialize(key);
byte[] values = connection.get(keys);
return OBJECT_SERIALIZER.deserialize(values);
});
log.debug("[redisTemplate redis]取出 緩存 url:{} ", key);
return resultStr;
}
/**
* 根據key獲取對象
* @param keyPatten the key patten
* @return the keys values
*/
public Map<String, Object> getKeysValues(final String keyPatten) {
log.debug("[redisTemplate redis] getValues() patten={} ", keyPatten);
return redisTemplate.execute((RedisCallback<Map<String, Object>>) connection -> {
RedisSerializer<String> serializer = getRedisSerializer();
Map<String, Object> maps = new HashMap<>(16);
Set<String> keys = redisTemplate.keys(keyPatten + "*");
if (CollectionUtils.isNotEmpty(keys)) {
for (String key : keys) {
byte[] bKeys = serializer.serialize(key);
byte[] bValues = connection.get(bKeys);
Object value = OBJECT_SERIALIZER.deserialize(bValues);
maps.put(key, value);
}
}
return maps;
});
}
/**
* Ops for hash hash operations.
*
* @return the hash operations
*/
public HashOperations<String, String, Object> opsForHash() {
return redisTemplate.opsForHash();
}
/**
* 對HashMap操作
*
* @param key the key
* @param hashKey the hash key
* @param hashValue the hash value
*/
public void putHashValue(String key, String hashKey, Object hashValue) {
//log.debug("[redisTemplate redis] putHashValue() key={},hashKey={},hashValue={} ", key, hashKey, hashValue);
opsForHash().put(key, hashKey, hashValue);
}
/**
* 獲取單個field對應的值
*
* @param key the key
* @param hashKey the hash key
* @return the hash values
*/
public Object getHashValues(String key, String hashKey) {
log.debug("[redisTemplate redis] getHashValues() key={},hashKey={}", key, hashKey);
return opsForHash().get(key, hashKey);
}
/**
* 根據key值刪除
*
* @param key the key
* @param hashKeys the hash keys
*/
public void delHashValues(String key, Object... hashKeys) {
log.debug("[redisTemplate redis] delHashValues() key={}", key);
opsForHash().delete(key, hashKeys);
}
/**
* key只匹配map
*
* @param key the key
* @return the hash value
*/
public Map<String, Object> getHashValue(String key) {
log.debug("[redisTemplate redis] getHashValue() key={}", key);
return opsForHash().entries(key);
}
/**
* 批量添加
*
* @param key the key
* @param map the map
*/
public void putHashValues(String key, Map<String, Object> map) {
opsForHash().putAll(key, map);
}
/**
* 集合數量
*
* @return the long
*/
public long dbSize() {
return redisTemplate.execute(RedisServerCommands::dbSize);
}
/**
* 清空redis存儲的數據
*
* @return the string
*/
public String flushDB() {
return redisTemplate.execute((RedisCallback<String>) connection -> {
connection.flushDb();
return "ok";
});
}
/**
* 判斷某個主鍵是否存在
*
* @param key the key
* @return the boolean
*/
public boolean exists(final String key) {
return redisTemplate.execute((RedisCallback<Boolean>) connection -> connection.exists(key.getBytes(DEFAULT_CHARSET)));
}
/**
* 刪除key
*
* @param keys the keys
* @return the long
*/
public long del(final String... keys) {
return redisTemplate.execute((RedisCallback<Long>) connection -> {
long result = 0;
for (String key : keys) {
result = connection.del(key.getBytes(DEFAULT_CHARSET));
}
return result;
});
}
/**
* 獲取 RedisSerializer
*
* @return the redis serializer
*/
protected RedisSerializer<String> getRedisSerializer() {
return redisTemplate.getStringSerializer();
}
/**
* 對某個主鍵對應的值加一,value值必須是全數字的字元串
*
* @param key the key
* @return the long
*/
public long incr(final String key) {
return redisTemplate.execute((RedisCallback<Long>) connection -> {
RedisSerializer<String> redisSerializer = getRedisSerializer();
return connection.incr(redisSerializer.serialize(key));
});
}
/**
* redis List 引擎
*
* @return the list operations
*/
public ListOperations<String, Object> opsForList() {
return redisTemplate.opsForList();
}
/**
* redis List數據結構 : 將一個或多個值 value 插入到列表 key 的表頭
*
* @param key the key
* @param value the value
* @return the long
*/
public Long leftPush(String key, Object value) {
return opsForList().leftPush(key, value);
}
/**
* redis List數據結構 : 移除並返回列表 key 的頭元素
*
* @param key the key
* @return the string
*/
public Object leftPop(String key) {
return opsForList().leftPop(key);
}
/**
* redis List數據結構 :將一個或多個值 value 插入到列表 key 的表尾(最右邊)。
*
* @param key the key
* @param value the value
* @return the long
*/
public Long in(String key, Object value) {
return opsForList().rightPush(key, value);
}
/**
* redis List數據結構 : 移除並返回列表 key 的末尾元素
*
* @param key the key
* @return the string
*/
public Object rightPop(String key) {
return opsForList().rightPop(key);
}
/**
* redis List數據結構 : 返回列表 key 的長度 ; 如果 key 不存在,則 key 被解釋為一個空列表,返回 0 ; 如果 key 不是列表類型,返回一個錯誤。
*
* @param key the key
* @return the long
*/
public Long length(String key) {
return opsForList().size(key);
}
/**
* redis List數據結構 : 根據參數 i 的值,移除列表中與參數 value 相等的元素
*
* @param key the key
* @param i the
* @param value the value
*/
public void remove(String key, long i, Object value) {
opsForList().remove(key, i, value);
}
/**
* redis List數據結構 : 將列表 key 下標為 index 的元素的值設置為 value
*
* @param key the key
* @param index the index
* @param value the value
*/
public void set(String key, long index, Object value) {
opsForList().set(key, index, value);
}
/**
* redis List數據結構 : 返回列表 key 中指定區間內的元素,區間以偏移量 start 和 end 指定。
*
* @param key the key
* @param start the start
* @param end the end
* @return the list
*/
public List<Object> getList(String key, int start, int end) {
return opsForList().range(key, start, end);
}
/**
* redis List數據結構 : 批量存儲
*
* @param key the key
* @param list the list
* @return the long
*/
public Long leftPushAll(String key, List<String> list) {
return opsForList().leftPushAll(key, list);
}
/**
* redis List數據結構 : 將值 value 插入到列表 key 當中,位於值 index 之前或之後,默認之後。
*
* @param key the key
* @param index the index
* @param value the value
*/
public void insert(String key, long index, Object value) {
opsForList().set(key, index, value);
}
}如果您在實際工作中有比較實用的工具類,歡迎分享一下,一起學習提高!
原創文章,作者:投稿專員,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/214525.html
微信掃一掃
支付寶掃一掃