Utils 公共方法
EmailUtils
@Slf4j
public class EmailUtils {
public static String getContent(String code) {
Resource resource = new ClassPathResource("template/mailtemplate.ftl");
InputStream inputStream = null;
BufferedReader fileReader = null;
StringBuilder buffer = new StringBuilder();
String line = "";
try {
inputStream = resource.getStream();
fileReader = new BufferedReader(new InputStreamReader(inputStream));
while ((line = fileReader.readLine()) != null) {
buffer.append(line);
}
} catch (Exception e) {
log.info("发送邮件读取模板失败:", e);
} finally {
if (fileReader != null) {
try {
fileReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (inputStream != null) {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return MessageFormat.format(buffer.toString(), code);
}
}
IpUtils
public class IpUtils {
public static final String REGX_0_255 = "(25[0-5]|2[0-4]\\d|1\\d{2}|[1-9]\\d|\\d)";
public static final String REGX_IP = "((" + REGX_0_255 + "\\.){3}" + REGX_0_255 + ")";
public static final String REGX_IP_WILDCARD = "(((\\*\\.){3}\\*)|(" + REGX_0_255 + "(\\.\\*){3})|(" + REGX_0_255 + "\\." + REGX_0_255 + ")(\\.\\*){2}" + "|((" + REGX_0_255 + "\\.){3}\\*))";
public static final String REGX_IP_SEG = "(" + REGX_IP + "\\-" + REGX_IP + ")";
public static String getIpAddr()
{
return getIpAddr(ServletUtils.getRequest());
}
public static String getIpAddr(HttpServletRequest request)
{
if (request == null)
{
return "unknown";
}
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("X-Forwarded-For");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getHeader("X-Real-IP");
}
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
{
ip = request.getRemoteAddr();
}
return "0:0:0:0:0:0:0:1".equals(ip) ? "127.0.0.1" : getMultistageReverseProxyIp(ip);
}
public static boolean internalIp(String ip)
{
byte[] addr = textToNumericFormatV4(ip);
return internalIp(addr) || "127.0.0.1".equals(ip);
}
private static boolean internalIp(byte[] addr)
{
if (addr == null || addr.length < 2)
{
return true;
}
final byte b0 = addr[0];
final byte b1 = addr[1];
final byte SECTION_1 = 0x0A;
final byte SECTION_2 = (byte) 0xAC;
final byte SECTION_3 = (byte) 0x10;
final byte SECTION_4 = (byte) 0x1F;
final byte SECTION_5 = (byte) 0xC0;
final byte SECTION_6 = (byte) 0xA8;
switch (b0)
{
case SECTION_1:
return true;
case SECTION_2:
if (b1 >= SECTION_3 && b1 <= SECTION_4)
{
return true;
}
case SECTION_5:
switch (b1)
{
case SECTION_6:
return true;
}
default:
return false;
}
}
public static byte[] textToNumericFormatV4(String text)
{
if (text.length() == 0)
{
return null;
}
byte[] bytes = new byte[4];
String[] elements = text.split("\\.", -1);
try
{
long l;
int i;
switch (elements.length)
{
case 1:
l = Long.parseLong(elements[0]);
if ((l < 0L) || (l > 4294967295L))
{
return null;
}
bytes[0] = (byte) (int) (l >> 24 & 0xFF);
bytes[1] = (byte) (int) ((l & 0xFFFFFF) >> 16 & 0xFF);
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 2:
l = Integer.parseInt(elements[0]);
if ((l < 0L) || (l > 255L))
{
return null;
}
bytes[0] = (byte) (int) (l & 0xFF);
l = Integer.parseInt(elements[1]);
if ((l < 0L) || (l > 16777215L))
{
return null;
}
bytes[1] = (byte) (int) (l >> 16 & 0xFF);
bytes[2] = (byte) (int) ((l & 0xFFFF) >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 3:
for (i = 0; i < 2; ++i)
{
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L))
{
return null;
}
bytes[i] = (byte) (int) (l & 0xFF);
}
l = Integer.parseInt(elements[2]);
if ((l < 0L) || (l > 65535L))
{
return null;
}
bytes[2] = (byte) (int) (l >> 8 & 0xFF);
bytes[3] = (byte) (int) (l & 0xFF);
break;
case 4:
for (i = 0; i < 4; ++i)
{
l = Integer.parseInt(elements[i]);
if ((l < 0L) || (l > 255L))
{
return null;
}
bytes[i] = (byte) (int) (l & 0xFF);
}
break;
default:
return null;
}
}
catch (NumberFormatException e)
{
return null;
}
return bytes;
}
public static String getHostIp()
{
try
{
return InetAddress.getLocalHost().getHostAddress();
}
catch (UnknownHostException e)
{
}
return "127.0.0.1";
}
public static String getHostName()
{
try
{
return InetAddress.getLocalHost().getHostName();
}
catch (UnknownHostException e)
{
}
return "未知";
}
public static String getMultistageReverseProxyIp(String ip)
{
if (ip != null && ip.indexOf(",") > 0)
{
final String[] ips = ip.trim().split(",");
for (String subIp : ips)
{
if (false == isUnknown(subIp))
{
ip = subIp;
break;
}
}
}
return StringUtils.substring(ip, 0, 255);
}
public static boolean isUnknown(String checkString)
{
return StringUtils.isBlank(checkString) || "unknown".equalsIgnoreCase(checkString);
}
public static boolean isIP(String ip)
{
return StringUtils.isNotBlank(ip) && ip.matches(REGX_IP);
}
public static boolean isIpWildCard(String ip)
{
return StringUtils.isNotBlank(ip) && ip.matches(REGX_IP_WILDCARD);
}
public static boolean ipIsInWildCardNoCheck(String ipWildCard, String ip)
{
String[] s1 = ipWildCard.split("\\.");
String[] s2 = ip.split("\\.");
boolean isMatchedSeg = true;
for (int i = 0; i < s1.length && !s1[i].equals("*"); i++)
{
if (!s1[i].equals(s2[i]))
{
isMatchedSeg = false;
break;
}
}
return isMatchedSeg;
}
public static boolean isIPSegment(String ipSeg)
{
return StringUtils.isNotBlank(ipSeg) && ipSeg.matches(REGX_IP_SEG);
}
public static boolean ipIsInNetNoCheck(String iparea, String ip)
{
int idx = iparea.indexOf('-');
String[] sips = iparea.substring(0, idx).split("\\.");
String[] sipe = iparea.substring(idx + 1).split("\\.");
String[] sipt = ip.split("\\.");
long ips = 0L, ipe = 0L, ipt = 0L;
for (int i = 0; i < 4; ++i)
{
ips = ips << 8 | Integer.parseInt(sips[i]);
ipe = ipe << 8 | Integer.parseInt(sipe[i]);
ipt = ipt << 8 | Integer.parseInt(sipt[i]);
}
if (ips > ipe)
{
long t = ips;
ips = ipe;
ipe = t;
}
return ips <= ipt && ipt <= ipe;
}
public static boolean isMatchedIp(String filter, String ip)
{
if (StringUtils.isEmpty(filter) || StringUtils.isEmpty(ip))
{
return false;
}
String[] ips = filter.split(";");
for (String iStr : ips)
{
if (isIP(iStr) && iStr.equals(ip))
{
return true;
}
else if (isIpWildCard(iStr) && ipIsInWildCardNoCheck(iStr, ip))
{
return true;
}
else if (isIPSegment(iStr) && ipIsInNetNoCheck(iStr, ip))
{
return true;
}
}
return false;
}
}
JwtUtils
public class JwtUtils {
public static String secret = TokenConstants.SECRET;
public static String createToken(Map<String, Object> claims)
{
return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
}
public static Claims parseToken(String token)
{
return Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
}
public static String getUserKey(String token)
{
Claims claims = parseToken(token);
return getValue(claims, SecurityConstants.USER_KEY);
}
public static String getUserKey(Claims claims)
{
return getValue(claims, SecurityConstants.USER_KEY);
}
public static String getUserId(String token)
{
Claims claims = parseToken(token);
return getValue(claims, SecurityConstants.USER_ID);
}
public static String getUserId(Claims claims)
{
return getValue(claims, SecurityConstants.USER_ID);
}
public static String getUserName(String token)
{
Claims claims = parseToken(token);
return getValue(claims, SecurityConstants.USER_PHONE);
}
public static String getUserName(Claims claims)
{
return getValue(claims, SecurityConstants.USER_PHONE);
}
public static String getValue(Claims claims, String key)
{
return Convert.toStr(claims.get(key), "");
}
}
SecurityUtils
public class SecurityUtils {
public static String getToken() throws IllegalStateException
{
return getToken(Objects.requireNonNull(ServletUtils.getRequest()));
}
public static String getToken(HttpServletRequest request) throws IllegalStateException{
String header = request.getHeader(TokenConstants.AUTHENTICATION);
if (StringUtils.isBlank(header)) {
header = request.getParameter(TokenConstants.AUTHENTICATION);
}
if (StringUtils.isBlank(header)) {
Cookie[] cookies = request.getCookies();
if (ObjectUtils.isEmpty(cookies)) {
throw new IllegalStateException("Request Token Is Empty");
}
for (Cookie cookie : cookies) {
if (Objects.equals(cookie.getName(), TokenConstants.AUTHENTICATION)) {
header = cookie.getValue();
}
}
}
if (StringUtils.isBlank(header)) {
throw new IllegalStateException("Request Token Is Empty");
}
if (!header.startsWith(TokenConstants.PREFIX)) {
throw new IllegalStateException("Request Token Is Empty");
}
return JwtUtils.getUserKey(header.substring(TokenConstants.PREFIX.length()));
}
public static String encryptPassword(String password)
{
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.encode(password);
}
public static boolean matchesPassword(String rawPassword, String encodedPassword)
{
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
return passwordEncoder.matches(rawPassword, encodedPassword);
}
}
TokenConstants
public class TokenConstants {
public static final String AUTHENTICATION = "Authorization";
public static final String PREFIX = "Bearer ";
public final static String SECRET = "zyxwvutsrqponmlkjihgfedcba";
}
public class FileExtractInfoUtils {
public static FileUpVO ExtractInfo(Object data, String code){
if (data instanceof LinkedHashMap) {
LinkedHashMap<?, ?> linkedHashMap = (LinkedHashMap<?, ?>) data;
Long id = Long.parseLong(linkedHashMap.get("id").toString());
String url = linkedHashMap.get("url").toString();
String name;
String[] parts = url.split("/");
if (code.equals("1")) {
name = linkedHashMap.get("originName").toString();
} else {
name = parts[parts.length - 1];
}
return new FileUpVO(name, id, url);
}
return null;
}
public static FileDownVO ExtractByte(Object data){
if (data instanceof LinkedHashMap) {
LinkedHashMap<?, ?> linkedHashMap = (LinkedHashMap<?, ?>) data;
String base64 = linkedHashMap.get("base64Data").toString();
LinkedHashMap<?, ?> headers = (LinkedHashMap<?, ?>) linkedHashMap.get("headersObj");
String contentType = headers.get("Content-Type").toString();
byte[] binaryData = Base64.getDecoder().decode(base64);
return new FileDownVO( binaryData, contentType);
}
return null;
}
}
NumberToChineseUtils
public class NumberToChineseUtils {
private static final String[] NUMBERS = {"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
private static final String[] INNIT = {"元","拾","佰","仟","万","拾","佰","仟","亿","拾","佰","仟","万","拾","佰","仟"};
private static final String[] DANI = {"角","分","厘"};
public static String toChinese(String str) {
if("0".equals(str) || "0.00".equals(str) || "0.0".equals(str)) {
return "零元";
}
if(str.length() > 13) {
return "数字金额异常数据";
}
boolean flag = false;
if(str.startsWith("-")){
flag = true;
str = str.replaceAll("-", "");
}
str = str.replaceAll(",", "");
String integerStr;
String decimalStr;
if(str.indexOf(".")>0) {
integerStr = str.substring(0,str.indexOf("."));
decimalStr = str.substring(str.indexOf(".") + 1);
}else if(str.indexOf(".")==0) {
integerStr = "";
decimalStr = str.substring(1);
}else {
integerStr = str;
decimalStr = "";
}
int[] integers = toIntArray(integerStr);
if (integers.length > 1 && integers[0] == 0) {
return "数字金额异常数据";
}
boolean isWan = isWan5(integerStr);
int[] decimals = toIntArray(decimalStr);
String result = getChineseInteger(integers, isWan) + getChineseDecimal(decimals);
if(flag){
return "负" + result;
}else{
return result;
}
}
private static int[] toIntArray(String number) {
int[] array = new int[number.length()];
for(int i = 0;i<number.length();i++) {
array[i] = Integer.parseInt(number.substring(i,i+1));
}
return array;
}
private static String getChineseInteger(int[] integers,boolean isWan) {
StringBuilder chineseInteger = new StringBuilder("");
int length = integers.length;
if (length == 1 && integers[0] == 0) {
return "";
}
for(int i=0; i<length; i++) {
String key = "";
if(integers[i] == 0) {
if((length - i) == 13)
key = INNIT[4];
else if((length - i) == 9) {
key = INNIT[8];
}else if((length - i) == 5 && isWan) {
key = INNIT[4];
}else if((length - i) == 1) {
key = INNIT[0];
}
if((length - i)>1 && integers[i+1]!=0) {
key += NUMBERS[0];
}
}
chineseInteger.append(integers[i]==0?key:(NUMBERS[integers[i]]+ INNIT[length - i -1]));
}
return chineseInteger.toString();
}
private static String getChineseDecimal(int[] decimals) {
StringBuilder chineseDecimal = new StringBuilder("");
for(int i = 0;i<decimals.length;i++) {
if(i == 3) {
break;
}
chineseDecimal.append(decimals[i]==0?"":(NUMBERS[decimals[i]]+ DANI[i]));
}
return chineseDecimal.toString();
}
private static boolean isWan5(String integerStr) {
int length = integerStr.length();
if(length > 4) {
String subInteger = "";
if(length > 8) {
subInteger = integerStr.substring(length- 8,length -4);
}else {
subInteger = integerStr.substring(0,length - 4);
}
return Integer.parseInt(subInteger) > 0;
}else {
return false;
}
}
}
LocalDataUtils
public class LocalDataUtils {
public static String dateFormat(String date ,Integer type) {
LocalDate localDate = LocalDate.parse(date);
switch (type) {
case 3: return DateTimeFormatter.ofPattern("yyyy-MM-dd").format(localDate);
case 4: return DateTimeFormatter.ofPattern("yyyy").format(localDate);
case 5: return DateTimeFormatter.ofPattern("MM").format(localDate);
case 6: return DateTimeFormatter.ofPattern("dd").format(localDate);
case 7: return DateTimeFormatter.ofPattern("MMMM dd, yyyy", Locale.ENGLISH).format(localDate);
case 8: return DateTimeFormatter.ofPattern("yyyy年MM月dd日", Locale.CHINA).format(localDate);
default: return DateTimeFormatter.ofPattern("yyyyMMdd").format(localDate);
}
}
}
FilePagesUtils
public class FilePagesUtils {
public static int filesPage(InputStream fileInputStream, String fileType) throws IOException {
int count = 0;
if (".doc".equals(fileType)) {
count = countWord2003Page(fileInputStream);
}
if (".docx".equals(fileType)) {
count = countWord2007Page(fileInputStream);
}
if (".pdf".equals(fileType)) {
count = countPdfPage(fileInputStream);
}
if (".pptx".equals(fileType)) {
count = countPPTXPage(fileInputStream);
}
if (".ppt".equals(fileType)) {
count = countPPTPage(fileInputStream);
}
return count;
}
public static int countPdfPage(InputStream fileInputStream) {
int pageCount = 0;
PdfReader reader = null;
try {
reader = new PdfReader(fileInputStream);
pageCount = reader.getNumberOfPages();
} catch (IOException e) {
e.printStackTrace();
} finally {
assert reader != null;
reader.close();
}
return pageCount;
}
public static int countPPTPage(InputStream fileInputStream) throws IOException {
int pageCount = 0;
ZipSecureFile.setMinInflateRatio(-1.0d);
HSLFSlideShow hslfSlideShow = new HSLFSlideShow(fileInputStream);
try {
pageCount = hslfSlideShow.getSlides().size();
} catch (Exception e) {
e.printStackTrace();
} finally {
fileInputStream.close();
}
return pageCount;
}
public static int countPPTXPage(InputStream fileInputStream) throws IOException {
int pageCount = 0;
ZipSecureFile.setMinInflateRatio(-1.0d);
try {
XMLSlideShow pptxFile = new XMLSlideShow(fileInputStream);
pageCount = pptxFile.getSlides().size();
} catch (IOException e) {
e.printStackTrace();
} finally {
fileInputStream.close();
}
return pageCount;
}
public static int countWord2007Page(InputStream fileInputStream) throws IOException {
int pageCount = 0;
ZipSecureFile.setMinInflateRatio(-1.0d);
XWPFDocument docx = null;
try {
docx = new XWPFDocument(fileInputStream);
pageCount = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();
} catch (IOException e) {
e.printStackTrace();
} finally {
assert docx != null;
docx.close();
}
return pageCount;
}
public static int countWord2003Page(InputStream fileInputStream) throws IOException {
int pageCount = 0;
WordExtractor doc = null;
ZipSecureFile.setMinInflateRatio(-1.0d);
try {
doc = new WordExtractor(fileInputStream);
pageCount = doc.getSummaryInformation().getPageCount();
} catch (IOException e) {
e.printStackTrace();
} finally {
assert doc != null;
doc.close();
}
return pageCount;
}
}
FileUtils
public class FileUtils {
public static MultipartFile setPDFMark(File file, String name) throws IOException {
PDDocument pdDocument = PDDocument.load(file);
PDExtendedGraphicsState state = new PDExtendedGraphicsState();
state.setNonStrokingAlphaConstant(0.1f);
state.setAlphaSourceFlag(true);
state.setBlendMode(BlendMode.MULTIPLY);
for (int i = 0; i < pdDocument.getNumberOfPages(); i++) {
PDPageContentStream stream = new PDPageContentStream(pdDocument, pdDocument.getPage(i), PDPageContentStream.AppendMode.APPEND, true, true);
stream.setFont(PDType1Font.HELVETICA_BOLD, 8);
stream.setNonStrokingColor(Color.BLACK);
stream.setGraphicsStateParameters(state);
stream.beginText();
float pageHeight = pdDocument.getPage(i).getMediaBox().getHeight();
float pageWidth = pdDocument.getPage(i).getMediaBox().getWidth();
for (int h = 10; h < pageHeight; h = h + 150) {
for (int w = -10; w < pageWidth; w = w + 150) {
stream.setTextMatrix(Matrix.getRotateInstance(0.3, w, h));
stream.showText("REACH24H");
}
}
stream.endText();
stream.close();
}
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
pdDocument.save(byteArrayOutputStream);
pdDocument.close();
ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
return new MultipartFileUtils(name, name, "application/pdf", byteArrayInputStream);
}
public static String setMd5(MultipartFile file) throws NoSuchAlgorithmException, IOException {
MessageDigest md = MessageDigest.getInstance("MD5");
try (InputStream inputStream = file.getInputStream()) {
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = inputStream.read(buffer)) != -1) {
md.update(buffer, 0, bytesRead);
}
}
byte[] md5Bytes = md.digest();
StringBuilder md5Hex = new StringBuilder();
for (byte b : md5Bytes) {
md5Hex.append(String.format("%02x", b));
}
return md5Hex.toString();
}
}
RedisUtils
@Component
public class RedisUtils {
@Resource
private RedisTemplate<String, Object> redisTemplate;
public boolean expire(String key, long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(Arrays.asList(key));
}
}
}
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
public Object hget(String key, String item) {
return redisTemplate.opsForHash().get(key, item);
}
public Map<Object, Object> hmget(String key) {
return redisTemplate.opsForHash().entries(key);
}
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public void hdel(String key, Object... item) {
redisTemplate.opsForHash().delete(key, item);
}
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
public long hincr(String key, String item, long by) {
return redisTemplate.opsForHash().increment(key, item, by);
}
public double hdecr(String key, String item, double by) {
return redisTemplate.opsForHash().increment(key, item, -by);
}
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if (time > 0) {
expire(key, time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public long setRemove(String key, Object... values) {
try {
Long count = redisTemplate.opsForSet().remove(key, values);
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if (time > 0) {
expire(key, time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
public long lRemove(String key, long count, Object value) {
try {
Long remove = redisTemplate.opsForList().remove(key, count, value);
return remove;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
private Set<String> keys(String keyPrefix) {
String realKey = keyPrefix + "*";
try {
return redisTemplate.execute((RedisCallback<Set<String>>) connection -> {
Set<String> binaryKeys = new HashSet<>();
Cursor<byte[]> cursor = connection.scan(ScanOptions.scanOptions().match(realKey).count(Integer.MAX_VALUE).build());
while (cursor.hasNext()) {
binaryKeys.add(new String(cursor.next()));
}
return binaryKeys;
});
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public void removeAll(String keyPrefix) {
try {
Set<String> keys = keys(keyPrefix);
redisTemplate.delete(keys);
} catch (Throwable e) {
e.printStackTrace();
}
}
}