java工具软件(java编程自学教程)
程序员文章站
2023-11-24 09:57:22
大家好,我是中恒。工作中我们经常使用到自定义的开发工具类,本文就列举几个中恒在实际工作中常用的几个工具类,供弟兄们参考。如果本文对您有帮助,欢迎关注、点赞或分享您在工作中经常使用到的工具类。日期处理p...
大家好,我是中恒。工作中我们经常使用到自定义的开发工具类,本文就列举几个中恒在实际工作中常用的几个工具类,供弟兄们参考。如果本文对您有帮助,欢迎关注、点赞或分享您在工作中经常使用到的工具类。
日期处理
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);
}
}
如果您在实际工作中有比较实用的工具类,欢迎分享一下,一起学习提高!
上一篇: Python实现TCP协议下的端口映射功能的脚本程序示例
下一篇: java单链表逆序用法代码示例