BigDecimalUtil 金额计算工具类

  1. import java.math.BigDecimal;
  2.  
  3. public class BigDecimalUtil {
  4.  
  5. private BigDecimalUtil(){
  6.  
  7. }
  8.  
  9. public static BigDecimal add(double v1,double v2){
  10. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  11. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  12. return b1.add(b2);
  13. }
  14.  
  15. public static BigDecimal sub(double v1,double v2){
  16. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  17. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  18. return b1.subtract(b2);
  19. }
  20.  
  21. public static BigDecimal mul(double v1,double v2){
  22. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  23. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  24. return b1.multiply(b2);
  25. }
  26.  
  27. public static BigDecimal div(double v1,double v2){
  28. BigDecimal b1 = new BigDecimal(Double.toString(v1));
  29. BigDecimal b2 = new BigDecimal(Double.toString(v2));
  30. return b1.divide(b2,2,BigDecimal.ROUND_HALF_UP);//四舍五入,保留2位小数
  31.  
  32. //除不尽的情况
  33. }
  34. }

joda-time 时间工具类

  1. import org.apache.commons.lang3.StringUtils;
  2. import org.joda.time.DateTime;
  3. import org.joda.time.format.DateTimeFormat;
  4. import org.joda.time.format.DateTimeFormatter;
  5.  
  6. import java.util.Date;
  7.  
  8. public class DateTimeUtil {
  9.  
  10. //joda-time
  11.  
  12. //str->Date
  13. //Date->str
  14. public static final String STANDARD_FORMAT = "yyyy-MM-dd HH:mm:ss";
  15.  
  16. public static Date strToDate(String dateTimeStr,String formatStr){
  17. DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(formatStr);
  18. DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
  19. return dateTime.toDate();
  20. }
  21.  
  22. public static String dateToStr(Date date,String formatStr){
  23. if(date == null){
  24. return StringUtils.EMPTY;
  25. }
  26. DateTime dateTime = new DateTime(date);
  27. return dateTime.toString(formatStr);
  28. }
  29.  
  30. public static Date strToDate(String dateTimeStr){
  31. DateTimeFormatter dateTimeFormatter = DateTimeFormat.forPattern(STANDARD_FORMAT);
  32. DateTime dateTime = dateTimeFormatter.parseDateTime(dateTimeStr);
  33. return dateTime.toDate();
  34. }
  35.  
  36. public static String dateToStr(Date date){
  37. if(date == null){
  38. return StringUtils.EMPTY;
  39. }
  40. DateTime dateTime = new DateTime(date);
  41. return dateTime.toString(STANDARD_FORMAT);
  42. }
  43.  
  44. public static void main(String[] args) {
  45. System.out.println(DateTimeUtil.dateToStr(new Date(),"yyyy-MM-dd HH:mm:ss"));
  46. System.out.println(DateTimeUtil.strToDate("2010-01-01 11:11:11","yyyy-MM-dd HH:mm:ss"));
  47. }
  48. }

或者jdk自带的时间处理类

  1. import java.text.DateFormat;
  2. import java.text.ParseException;
  3. import java.text.SimpleDateFormat;
  4. import java.util.Date;
  5.  
  6. public class DateUtils {
  7. public static String transferdate(Date date,String dateFormatparam){
  8. DateFormat dateFormat = new SimpleDateFormat(dateFormatparam);
  9. return dateFormat.format(date);
  10.  
  11. }
  12.  
  13. public static Date transferdate(String datastring,String dateFormatparam){
  14. Date date = new Date();
  15. DateFormat dateFormat = new SimpleDateFormat(dateFormatparam);
  16. try {
  17. date = dateFormat.parse(datastring);
  18. } catch (ParseException e) {
  19. e.printStackTrace();
  20. }
  21. return date;
  22.  
  23. }
  24.  
  25. public static void main(String[] args) {
  26.  
  27. String stringDate = transferdate(new Date(), "yyyy-MM-dd hh:mm:ss");
  28. System.out.println(stringDate);
  29.  
  30. Date date = transferdate("20190101", "yyyy-MM-dd");
  31. System.out.println(date);
  32. }
  33. }

FTP工具类

  1. import org.apache.commons.net.ftp.FTPClient;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4.  
  5. import java.io.File;
  6. import java.io.FileInputStream;
  7. import java.io.IOException;
  8. import java.util.List;
  9.  
  10. public class FTPUtil {
  11.  
  12. private static final Logger logger = LoggerFactory.getLogger(FTPUtil.class);
  13.  
  14. private static String ftpIp = PropertiesUtil.getProperty("ftp.server.ip");
  15. private static String ftpUser = PropertiesUtil.getProperty("ftp.user");
  16. private static String ftpPass = PropertiesUtil.getProperty("ftp.pass");
  17.  
  18. public FTPUtil(String ip,int port,String user,String pwd){
  19. this.ip = ip;
  20. this.port = port;
  21. this.user = user;
  22. this.pwd = pwd;
  23. }
  24. public static boolean uploadFile(List<File> fileList) throws IOException {
  25. FTPUtil ftpUtil = new FTPUtil(ftpIp,21,ftpUser,ftpPass);
  26. logger.info("开始连接ftp服务器");
  27. boolean result = ftpUtil.uploadFile("img",fileList);
  28. logger.info("开始连接ftp服务器,结束上传,上传结果:{}");
  29. return result;
  30. }
  31.  
  32. private boolean uploadFile(String remotePath,List<File> fileList) throws IOException {
  33. boolean uploaded = true;
  34. FileInputStream fis = null;
  35. //连接FTP服务器
  36. if(connectServer(this.ip,this.port,this.user,this.pwd)){
  37. try {
  38. ftpClient.changeWorkingDirectory(remotePath);
  39. ftpClient.setBufferSize(1024);
  40. ftpClient.setControlEncoding("UTF-8");
  41. ftpClient.setFileType(FTPClient.BINARY_FILE_TYPE);
  42. ftpClient.enterLocalPassiveMode();
  43. for(File fileItem : fileList){
  44. fis = new FileInputStream(fileItem);
  45. ftpClient.storeFile(fileItem.getName(),fis);
  46. }
  47.  
  48. } catch (IOException e) {
  49. logger.error("上传文件异常",e);
  50. uploaded = false;
  51. e.printStackTrace();
  52. } finally {
  53. fis.close();
  54. ftpClient.disconnect();
  55. }
  56. }
  57. return uploaded;
  58. }
  59.  
  60. private boolean connectServer(String ip,int port,String user,String pwd){
  61.  
  62. boolean isSuccess = false;
  63. ftpClient = new FTPClient();
  64. try {
  65. ftpClient.connect(ip);
  66. isSuccess = ftpClient.login(user,pwd);
  67. } catch (IOException e) {
  68. logger.error("连接FTP服务器异常",e);
  69. }
  70. return isSuccess;
  71. }
  72.  
  73. private String ip;
  74. private int port;
  75. private String user;
  76. private String pwd;
  77. private FTPClient ftpClient;
  78.  
  79. public String getIp() {
  80. return ip;
  81. }
  82.  
  83. public void setIp(String ip) {
  84. this.ip = ip;
  85. }
  86.  
  87. public int getPort() {
  88. return port;
  89. }
  90.  
  91. public void setPort(int port) {
  92. this.port = port;
  93. }
  94.  
  95. public String getUser() {
  96. return user;
  97. }
  98.  
  99. public void setUser(String user) {
  100. this.user = user;
  101. }
  102.  
  103. public String getPwd() {
  104. return pwd;
  105. }
  106.  
  107. public void setPwd(String pwd) {
  108. this.pwd = pwd;
  109. }
  110.  
  111. public FTPClient getFtpClient() {
  112. return ftpClient;
  113. }
  114.  
  115. public void setFtpClient(FTPClient ftpClient) {
  116. this.ftpClient = ftpClient;
  117. }
  118. }

MD5Util

  1. import java.security.MessageDigest;
  2.  
  3. public class MD5Util {
  4.  
  5. private static String byteArrayToHexString(byte b[]) {
  6. StringBuffer resultSb = new StringBuffer();
  7. for (int i = 0; i < b.length; i++)
  8. resultSb.append(byteToHexString(b[i]));
  9.  
  10. return resultSb.toString();
  11. }
  12.  
  13. private static String byteToHexString(byte b) {
  14. int n = b;
  15. if (n < 0)
  16. n += 256;
  17. int d1 = n / 16;
  18. int d2 = n % 16;
  19. return hexDigits[d1] + hexDigits[d2];
  20. }
  21.  
  22. /**
  23. * 返回大写MD5
  24. *
  25. * @param origin
  26. * @param charsetname
  27. * @return
  28. */
  29. private static String MD5Encode(String origin, String charsetname) {
  30. String resultString = null;
  31. try {
  32. resultString = new String(origin);
  33. MessageDigest md = MessageDigest.getInstance("MD5");
  34. if (charsetname == null || "".equals(charsetname))
  35. resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
  36. else
  37. resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
  38. } catch (Exception exception) {
  39. }
  40. return resultString.toUpperCase();
  41. }
  42.  
  43. public static String MD5EncodeUtf8(String origin) {
  44. origin = origin + PropertiesUtil.getProperty("password.salt", "");
  45. return MD5Encode(origin, "utf-8");
  46. }
  47.  
  48. private static final String hexDigits[] = {"0", "1", "2", "3", "4", "5",
  49. "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};
  50.  
  51. }

或者这个

  1. import java.util.Random;
  2. import org.apache.commons.codec.binary.Hex;
  3. import java.security.NoSuchAlgorithmException;
  4. import java.security.MessageDigest;
  5.  
  6. /**
  7. * MD5工具类,加盐
  8. */
  9. public class MD5Util {
  10.  
  11. /**
  12. * 普通MD5
  13. * @param input
  14. * @return
  15. */
  16. public static String MD5(String input) {
  17. MessageDigest md5 = null;
  18. try {
  19. md5 = MessageDigest.getInstance("MD5");
  20. } catch (NoSuchAlgorithmException e) {
  21. return "check jdk";
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. return "";
  25. }
  26. char[] charArray = input.toCharArray();
  27. byte[] byteArray = new byte[charArray.length];
  28.  
  29. for (int i = 0; i < charArray.length; i++)
  30. byteArray[i] = (byte) charArray[i];
  31. byte[] md5Bytes = md5.digest(byteArray);
  32. StringBuffer hexValue = new StringBuffer();
  33. for (int i = 0; i < md5Bytes.length; i++) {
  34. int val = ((int) md5Bytes[i]) & 0xff;
  35. if (val < 16)
  36. hexValue.append("0");
  37. hexValue.append(Integer.toHexString(val));
  38. }
  39. return hexValue.toString();
  40.  
  41. }
  42.  
  43. /**
  44. * 加盐MD5
  45. * @param password
  46. * @return
  47. */
  48. public static String generate(String password) {
  49. Random r = new Random();
  50. StringBuilder sb = new StringBuilder(16);
  51. sb.append(r.nextInt(99999999)).append(r.nextInt(99999999));
  52. int len = sb.length();
  53. if (len < 16) {
  54. for (int i = 0; i < 16 - len; i++) {
  55. sb.append("0");
  56. }
  57. }
  58. String salt = sb.toString();
  59. password = md5Hex(password + salt);
  60. char[] cs = new char[48];
  61. for (int i = 0; i < 48; i += 3) {
  62. cs[i] = password.charAt(i / 3 * 2);
  63. char c = salt.charAt(i / 3);
  64. cs[i + 1] = c;
  65. cs[i + 2] = password.charAt(i / 3 * 2 + 1);
  66. }
  67. return new String(cs);
  68. }
  69.  
  70. /**
  71. * 校验加盐后是否和原文一致
  72. * @param password
  73. * @param md5
  74. * @return
  75. */
  76. public static boolean verify(String password, String md5) {
  77. char[] cs1 = new char[32];
  78. char[] cs2 = new char[16];
  79. for (int i = 0; i < 48; i += 3) {
  80. cs1[i / 3 * 2] = md5.charAt(i);
  81. cs1[i / 3 * 2 + 1] = md5.charAt(i + 2);
  82. cs2[i / 3] = md5.charAt(i + 1);
  83. }
  84. String salt = new String(cs2);
  85. return md5Hex(password + salt).equals(new String(cs1));
  86. }
  87.  
  88. /**
  89. * 获取十六进制字符串形式的MD5摘要
  90. */
  91. private static String md5Hex(String src) {
  92. try {
  93. MessageDigest md5 = MessageDigest.getInstance("MD5");
  94. byte[] bs = md5.digest(src.getBytes());
  95. return new String(new Hex().encode(bs));
  96. } catch (Exception e) {
  97. return null;
  98. }
  99. }
  100.  
  101. // 测试主函数
  102. public static void main(String args[]) {
  103. // 原文
  104. String plaintext = "testAddSalt123";
  105. System.out.println("原始:" + plaintext);
  106. System.out.println("普通MD5后:" + MD5Util.MD5(plaintext));
  107.  
  108. // 获取加盐后的MD5值
  109. String ciphertext = MD5Util.generate(plaintext);
  110. System.out.println("加盐后MD5:" + ciphertext);
  111. System.out.println("是否是同一字符串:" + MD5Util.verify(plaintext, ciphertext));
  112. /**
  113. * 其中某次plaintext="testAddSalt123"字符串加盐后的MD5值
  114. */
  115. String[] tempSalt = { "15af3d445524108642c22767922a4a797278b85b1ac29f09", "67301583c322b2946397bd3c42f35775c303f3486f01c24d", "632d2828022e42cf3bc4c41801a69a313c01b67b3d295a52" };
  116.  
  117. for (String temp : tempSalt) {
  118. System.out.println("是否是同一字符串:" + MD5Util.verify(plaintext, temp));
  119. }
  120.  
  121. }
  122.  
  123. }

PropertiesUtil

  1. import org.apache.commons.lang3.StringUtils;
  2. import org.slf4j.Logger;
  3. import org.slf4j.LoggerFactory;
  4.  
  5. import java.io.IOException;
  6. import java.io.InputStreamReader;
  7. import java.util.Properties;
  8.  
  9. public class PropertiesUtil {
  10.  
  11. private static Logger logger = LoggerFactory.getLogger(PropertiesUtil.class);
  12.  
  13. private static Properties props;
  14.  
  15. static {
  16. String fileName = "mmall.properties";
  17. props = new Properties();
  18. try {
  19. props.load(new InputStreamReader(PropertiesUtil.class.getClassLoader().getResourceAsStream(fileName),"UTF-8"));
  20. } catch (IOException e) {
  21. logger.error("配置文件读取异常",e);
  22. }
  23. }
  24.  
  25. public static String getProperty(String key){
  26. String value = props.getProperty(key.trim());
  27. if(StringUtils.isBlank(value)){
  28. return null;
  29. }
  30. return value.trim();
  31. }
  32.  
  33. public static String getProperty(String key,String defaultValue){
  34.  
  35. String value = props.getProperty(key.trim());
  36. if(StringUtils.isBlank(value)){
  37. value = defaultValue;
  38. }
  39. return value.trim();
  40. }
  41.  
  42. }

SpringMVC封装返回信息

  ServerResponse

  1. import org.codehaus.jackson.annotate.JsonIgnore;
  2. import org.codehaus.jackson.map.annotate.JsonSerialize;
  3.  
  4. import java.io.Serializable;
  5.  
  6. @JsonSerialize(include = JsonSerialize.Inclusion.NON_NULL)
  7. //保证序列化json的时候,如果是null的对象,key也会消失
  8. public class ServerResponse<T> implements Serializable {
  9.  
  10. private int status;
  11. private String msg;
  12. private T data;
  13.  
  14. private ServerResponse(int status){
  15. this.status = status;
  16. }
  17. private ServerResponse(int status,T data){
  18. this.status = status;
  19. this.data = data;
  20. }
  21.  
  22. private ServerResponse(int status,String msg,T data){
  23. this.status = status;
  24. this.msg = msg;
  25. this.data = data;
  26. }
  27.  
  28. private ServerResponse(int status,String msg){
  29. this.status = status;
  30. this.msg = msg;
  31. }
  32.  
  33. @JsonIgnore
  34. //使之不在json序列化结果当中
  35. public boolean isSuccess(){
  36. return this.status == ResponseCode.SUCCESS.getCode();
  37. }
  38.  
  39. public int getStatus(){
  40. return status;
  41. }
  42. public T getData(){
  43. return data;
  44. }
  45. public String getMsg(){
  46. return msg;
  47. }
  48.  
  49. public static <T> ServerResponse<T> createBySuccess(){
  50. return new ServerResponse<T>(ResponseCode.SUCCESS.getCode());
  51. }
  52.  
  53. public static <T> ServerResponse<T> createBySuccessMessage(String msg){
  54. return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg);
  55. }
  56.  
  57. public static <T> ServerResponse<T> createBySuccess(T data){
  58. return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),data);
  59. }
  60.  
  61. public static <T> ServerResponse<T> createBySuccess(String msg,T data){
  62. return new ServerResponse<T>(ResponseCode.SUCCESS.getCode(),msg,data);
  63. }
  64.  
  65. public static <T> ServerResponse<T> createByError(){
  66. return new ServerResponse<T>(ResponseCode.ERROR.getCode(),ResponseCode.ERROR.getDesc());
  67. }
  68.  
  69. public static <T> ServerResponse<T> createByErrorMessage(String errorMessage){
  70. return new ServerResponse<T>(ResponseCode.ERROR.getCode(),errorMessage);
  71. }
  72.  
  73. public static <T> ServerResponse<T> createByErrorCodeMessage(int errorCode,String errorMessage){
  74. return new ServerResponse<T>(errorCode,errorMessage);
  75. }
  76.  
  77. }

  ResponseCode

  1. public enum ResponseCode {
  2.  
  3. SUCCESS(0,"SUCCESS"),
  4. ERROR(1,"ERROR"),
  5. NEED_LOGIN(10,"NEED_LOGIN"),
  6. ILLEGAL_ARGUMENT(2,"ILLEGAL_ARGUMENT");
  7.  
  8. private final int code;
  9. private final String desc;
  10.  
  11. ResponseCode(int code,String desc){
  12. this.code = code;
  13. this.desc = desc;
  14. }
  15.  
  16. public int getCode(){
  17. return code;
  18. }
  19. public String getDesc(){
  20. return desc;
  21. }
  22.  
  23. }

RedisUtil redisTemplate工具类

  1. import java.util.List;
  2. import java.util.Map;
  3. import java.util.Set;
  4. import java.util.concurrent.TimeUnit;
  5.  
  6. import org.springframework.data.redis.core.RedisTemplate;
  7. import org.springframework.util.CollectionUtils;
  8.  
  9. /**
  10. * 基于spring和redis的redisTemplate工具类
  11. * 针对所有的hash 都是以h开头的方法
  12. * 针对所有的Set 都是以s开头的方法 不含通用方法
  13. * 针对所有的List 都是以l开头的方法
  14. */
  15. public class RedisUtil {
  16.  
  17. private RedisTemplate<String, Object> redisTemplate;
  18.  
  19. public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
  20. this.redisTemplate = redisTemplate;
  21. }
  22. //=============================common============================
  23. /**
  24. * 指定缓存失效时间
  25. * @param key 键
  26. * @param time 时间(秒)
  27. * @return
  28. */
  29. public boolean expire(String key,long time){
  30. try {
  31. if(time>0){
  32. redisTemplate.expire(key, time, TimeUnit.SECONDS);
  33. }
  34. return true;
  35. } catch (Exception e) {
  36. e.printStackTrace();
  37. return false;
  38. }
  39. }
  40.  
  41. /**
  42. * 根据key 获取过期时间
  43. * @param key 键 不能为null
  44. * @return 时间(秒) 返回0代表为永久有效
  45. */
  46. public long getExpire(String key){
  47. return redisTemplate.getExpire(key,TimeUnit.SECONDS);
  48. }
  49.  
  50. /**
  51. * 判断key是否存在
  52. * @param key 键
  53. * @return true 存在 false不存在
  54. */
  55. public boolean hasKey(String key){
  56. try {
  57. return redisTemplate.hasKey(key);
  58. } catch (Exception e) {
  59. e.printStackTrace();
  60. return false;
  61. }
  62. }
  63.  
  64. /**
  65. * 删除缓存
  66. * @param key 可以传一个值 或多个
  67. */
  68. @SuppressWarnings("unchecked")
  69. public void del(String ... key){
  70. if(key!=null&&key.length>0){
  71. if(key.length==1){
  72. redisTemplate.delete(key[0]);
  73. }else{
  74. redisTemplate.delete(CollectionUtils.arrayToList(key));
  75. }
  76. }
  77. }
  78.  
  79. //============================String=============================
  80. /**
  81. * 普通缓存获取
  82. * @param key 键
  83. * @return 值
  84. */
  85. public Object get(String key){
  86. return key==null?null:redisTemplate.opsForValue().get(key);
  87. }
  88.  
  89. /**
  90. * 普通缓存放入
  91. * @param key 键
  92. * @param value 值
  93. * @return true成功 false失败
  94. */
  95. public boolean set(String key,Object value) {
  96. try {
  97. redisTemplate.opsForValue().set(key, value);
  98. return true;
  99. } catch (Exception e) {
  100. e.printStackTrace();
  101. return false;
  102. }
  103.  
  104. }
  105.  
  106. /**
  107. * 普通缓存放入并设置时间
  108. * @param key 键
  109. * @param value 值
  110. * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
  111. * @return true成功 false 失败
  112. */
  113. public boolean set(String key,Object value,long time){
  114. try {
  115. if(time>0){
  116. redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  117. }else{
  118. set(key, value);
  119. }
  120. return true;
  121. } catch (Exception e) {
  122. e.printStackTrace();
  123. return false;
  124. }
  125. }
  126.  
  127. /**
  128. * 递增
  129. * @param key 键
  130. * @param by 要增加几(大于0)
  131. * @return
  132. */
  133. public long incr(String key, long delta){
  134. if(delta<0){
  135. throw new RuntimeException("递增因子必须大于0");
  136. }
  137. return redisTemplate.opsForValue().increment(key, delta);
  138. }
  139.  
  140. /**
  141. * 递减
  142. * @param key 键
  143. * @param by 要减少几(小于0)
  144. * @return
  145. */
  146. public long decr(String key, long delta){
  147. if(delta<0){
  148. throw new RuntimeException("递减因子必须大于0");
  149. }
  150. return redisTemplate.opsForValue().increment(key, -delta);
  151. }
  152.  
  153. //================================Map=================================
  154. /**
  155. * HashGet
  156. * @param key 键 不能为null
  157. * @param item 项 不能为null
  158. * @return 值
  159. */
  160. public Object hget(String key,String item){
  161. return redisTemplate.opsForHash().get(key, item);
  162. }
  163.  
  164. /**
  165. * 获取hashKey对应的所有键值
  166. * @param key 键
  167. * @return 对应的多个键值
  168. */
  169. public Map<Object,Object> hmget(String key){
  170. return redisTemplate.opsForHash().entries(key);
  171. }
  172.  
  173. /**
  174. * HashSet
  175. * @param key 键
  176. * @param map 对应多个键值
  177. * @return true 成功 false 失败
  178. */
  179. public boolean hmset(String key, Map<String,Object> map){
  180. try {
  181. redisTemplate.opsForHash().putAll(key, map);
  182. return true;
  183. } catch (Exception e) {
  184. e.printStackTrace();
  185. return false;
  186. }
  187. }
  188.  
  189. /**
  190. * HashSet 并设置时间
  191. * @param key 键
  192. * @param map 对应多个键值
  193. * @param time 时间(秒)
  194. * @return true成功 false失败
  195. */
  196. public boolean hmset(String key, Map<String,Object> map, long time){
  197. try {
  198. redisTemplate.opsForHash().putAll(key, map);
  199. if(time>0){
  200. expire(key, time);
  201. }
  202. return true;
  203. } catch (Exception e) {
  204. e.printStackTrace();
  205. return false;
  206. }
  207. }
  208.  
  209. /**
  210. * 向一张hash表中放入数据,如果不存在将创建
  211. * @param key 键
  212. * @param item 项
  213. * @param value 值
  214. * @return true 成功 false失败
  215. */
  216. public boolean hset(String key,String item,Object value) {
  217. try {
  218. redisTemplate.opsForHash().put(key, item, value);
  219. return true;
  220. } catch (Exception e) {
  221. e.printStackTrace();
  222. return false;
  223. }
  224. }
  225.  
  226. /**
  227. * 向一张hash表中放入数据,如果不存在将创建
  228. * @param key 键
  229. * @param item 项
  230. * @param value 值
  231. * @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
  232. * @return true 成功 false失败
  233. */
  234. public boolean hset(String key,String item,Object value,long time) {
  235. try {
  236. redisTemplate.opsForHash().put(key, item, value);
  237. if(time>0){
  238. expire(key, time);
  239. }
  240. return true;
  241. } catch (Exception e) {
  242. e.printStackTrace();
  243. return false;
  244. }
  245. }
  246.  
  247. /**
  248. * 删除hash表中的值
  249. * @param key 键 不能为null
  250. * @param item 项 可以使多个 不能为null
  251. */
  252. public void hdel(String key, Object... item){
  253. redisTemplate.opsForHash().delete(key,item);
  254. }
  255.  
  256. /**
  257. * 判断hash表中是否有该项的值
  258. * @param key 键 不能为null
  259. * @param item 项 不能为null
  260. * @return true 存在 false不存在
  261. */
  262. public boolean hHasKey(String key, String item){
  263. return redisTemplate.opsForHash().hasKey(key, item);
  264. }
  265.  
  266. /**
  267. * hash递增 如果不存在,就会创建一个 并把新增后的值返回
  268. * @param key 键
  269. * @param item 项
  270. * @param by 要增加几(大于0)
  271. * @return
  272. */
  273. public double hincr(String key, String item,double by){
  274. return redisTemplate.opsForHash().increment(key, item, by);
  275. }
  276.  
  277. /**
  278. * hash递减
  279. * @param key 键
  280. * @param item 项
  281. * @param by 要减少记(小于0)
  282. * @return
  283. */
  284. public double hdecr(String key, String item,double by){
  285. return redisTemplate.opsForHash().increment(key, item,-by);
  286. }
  287.  
  288. //============================set=============================
  289. /**
  290. * 根据key获取Set中的所有值
  291. * @param key 键
  292. * @return
  293. */
  294. public Set<Object> sGet(String key){
  295. try {
  296. return redisTemplate.opsForSet().members(key);
  297. } catch (Exception e) {
  298. e.printStackTrace();
  299. return null;
  300. }
  301. }
  302.  
  303. /**
  304. * 根据value从一个set中查询,是否存在
  305. * @param key 键
  306. * @param value 值
  307. * @return true 存在 false不存在
  308. */
  309. public boolean sHasKey(String key,Object value){
  310. try {
  311. return redisTemplate.opsForSet().isMember(key, value);
  312. } catch (Exception e) {
  313. e.printStackTrace();
  314. return false;
  315. }
  316. }
  317.  
  318. /**
  319. * 将数据放入set缓存
  320. * @param key 键
  321. * @param values 值 可以是多个
  322. * @return 成功个数
  323. */
  324. public long sSet(String key, Object...values) {
  325. try {
  326. return redisTemplate.opsForSet().add(key, values);
  327. } catch (Exception e) {
  328. e.printStackTrace();
  329. return 0;
  330. }
  331. }
  332.  
  333. /**
  334. * 将set数据放入缓存
  335. * @param key 键
  336. * @param time 时间(秒)
  337. * @param values 值 可以是多个
  338. * @return 成功个数
  339. */
  340. public long sSetAndTime(String key,long time,Object...values) {
  341. try {
  342. Long count = redisTemplate.opsForSet().add(key, values);
  343. if(time>0) expire(key, time);
  344. return count;
  345. } catch (Exception e) {
  346. e.printStackTrace();
  347. return 0;
  348. }
  349. }
  350.  
  351. /**
  352. * 获取set缓存的长度
  353. * @param key 键
  354. * @return
  355. */
  356. public long sGetSetSize(String key){
  357. try {
  358. return redisTemplate.opsForSet().size(key);
  359. } catch (Exception e) {
  360. e.printStackTrace();
  361. return 0;
  362. }
  363. }
  364.  
  365. /**
  366. * 移除值为value的
  367. * @param key 键
  368. * @param values 值 可以是多个
  369. * @return 移除的个数
  370. */
  371. public long setRemove(String key, Object ...values) {
  372. try {
  373. Long count = redisTemplate.opsForSet().remove(key, values);
  374. return count;
  375. } catch (Exception e) {
  376. e.printStackTrace();
  377. return 0;
  378. }
  379. }
  380. //===============================list=================================
  381.  
  382. /**
  383. * 获取list缓存的内容
  384. * @param key 键
  385. * @param start 开始
  386. * @param end 结束 0 到 -1代表所有值
  387. * @return
  388. */
  389. public List<Object> lGet(String key,long start, long end){
  390. try {
  391. return redisTemplate.opsForList().range(key, start, end);
  392. } catch (Exception e) {
  393. e.printStackTrace();
  394. return null;
  395. }
  396. }
  397.  
  398. /**
  399. * 获取list缓存的长度
  400. * @param key 键
  401. * @return
  402. */
  403. public long lGetListSize(String key){
  404. try {
  405. return redisTemplate.opsForList().size(key);
  406. } catch (Exception e) {
  407. e.printStackTrace();
  408. return 0;
  409. }
  410. }
  411.  
  412. /**
  413. * 通过索引 获取list中的值
  414. * @param key 键
  415. * @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
  416. * @return
  417. */
  418. public Object lGetIndex(String key,long index){
  419. try {
  420. return redisTemplate.opsForList().index(key, index);
  421. } catch (Exception e) {
  422. e.printStackTrace();
  423. return null;
  424. }
  425. }
  426.  
  427. /**
  428. * 将list放入缓存
  429. * @param key 键
  430. * @param value 值
  431. * @param time 时间(秒)
  432. * @return
  433. */
  434. public boolean lSet(String key, Object value) {
  435. try {
  436. redisTemplate.opsForList().rightPush(key, value);
  437. return true;
  438. } catch (Exception e) {
  439. e.printStackTrace();
  440. return false;
  441. }
  442. }
  443.  
  444. /**
  445. * 将list放入缓存
  446. * @param key 键
  447. * @param value 值
  448. * @param time 时间(秒)
  449. * @return
  450. */
  451. public boolean lSet(String key, Object value, long time) {
  452. try {
  453. redisTemplate.opsForList().rightPush(key, value);
  454. if (time > 0) expire(key, time);
  455. return true;
  456. } catch (Exception e) {
  457. e.printStackTrace();
  458. return false;
  459. }
  460. }
  461.  
  462. /**
  463. * 将list放入缓存
  464. * @param key 键
  465. * @param value 值
  466. * @param time 时间(秒)
  467. * @return
  468. */
  469. public boolean lSet(String key, List<Object> value) {
  470. try {
  471. redisTemplate.opsForList().rightPushAll(key, value);
  472. return true;
  473. } catch (Exception e) {
  474. e.printStackTrace();
  475. return false;
  476. }
  477. }
  478.  
  479. /**
  480. * 将list放入缓存
  481. * @param key 键
  482. * @param value 值
  483. * @param time 时间(秒)
  484. * @return
  485. */
  486. public boolean lSet(String key, List<Object> value, long time) {
  487. try {
  488. redisTemplate.opsForList().rightPushAll(key, value);
  489. if (time > 0) expire(key, time);
  490. return true;
  491. } catch (Exception e) {
  492. e.printStackTrace();
  493. return false;
  494. }
  495. }
  496.  
  497. /**
  498. * 根据索引修改list中的某条数据
  499. * @param key 键
  500. * @param index 索引
  501. * @param value 值
  502. * @return
  503. */
  504. public boolean lUpdateIndex(String key, long index,Object value) {
  505. try {
  506. redisTemplate.opsForList().set(key, index, value);
  507. return true;
  508. } catch (Exception e) {
  509. e.printStackTrace();
  510. return false;
  511. }
  512. }
  513.  
  514. /**
  515. * 移除N个值为value
  516. * @param key 键
  517. * @param count 移除多少个
  518. * @param value 值
  519. * @return 移除的个数
  520. */
  521. public long lRemove(String key,long count,Object value) {
  522. try {
  523. Long remove = redisTemplate.opsForList().remove(key, count, value);
  524. return remove;
  525. } catch (Exception e) {
  526. e.printStackTrace();
  527. return 0;
  528. }
  529. }
  530.  
  531. /** 获取集合长度
  532. * @param key
  533. * @return
  534. */
  535. public long getkeylistsize(String key){
  536. return redisTemplate.opsForList().size(key);
  537. }
  538.  
  539. public long pushlist(String key,String value){
  540. return redisTemplate.opsForList().leftPush(key, value);
  541. }
  542.  
  543. public Set<String> getkeys(String key){
  544. return redisTemplate.keys(key +"*");
  545. }
  546.  
  547. }

java 工具类使用的更多相关文章

  1. java工具类系列 (四.SerializationUtils)

    java工具类系列 (四.SerializationUtils) SerializationUtils该类为序列化工具类,也是lang包下的工具,主要用于序列化操作 import java.io.Se ...

  2. Java工具类——通过配置XML验证Map

    Java工具类--通过配置XML验证Map 背景 在JavaWeb项目中,接收前端过来的参数时通常是使用我们的实体类进行接收的.但是呢,我们不能去决定已经搭建好的框架是怎么样的,在我接触的框架中有一种 ...

  3. 排名前 16 的 Java 工具类

    在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...

  4. 排名前16的Java工具类

    原文:https://www.jianshu.com/p/9e937d178203 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法 ...

  5. 第一章 Java工具类目录

    在这一系列博客中,主要是记录在实际开发中会常用的一些Java工具类,方便后续开发中使用. 以下的目录会随着后边具体工具类的添加而改变. 浮点数精确计算 第二章 Java浮点数精确计算 crc32将任意 ...

  6. java工具类之按对象中某属性排序

    import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang ...

  7. 干货:排名前16的Java工具类

    在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码. 一. ...

  8. Java工具类:给程序增加版权信息

       我们九天鸟的p2p网贷系统,基本算是开发完成了.   现在,想给后端的Java代码,增加版权信息.   手动去copy-paste,太没有技术含量. 于是,写了个Java工具类,给Java源文件 ...

  9. 常用高效 Java 工具类总结

    一.前言 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类.以下工具类.方法按使用流行度排名,参考数据来源于Github上随机选取的5万个开源项目源码 ...

  10. 几种高效的Java工具类推荐

    本文将介绍了十二种常用的.高效的Java工具类 在Java中,工具类定义了一组公共方法,这篇文章将介绍Java中使用最频繁及最通用的Java工具类. 在开发中,使用这些工具类,不仅可以提高编码效率,还 ...

随机推荐

  1. [HG]走夜路 题解

    前言 整个机房就我一个人在想动态规划. 想了半天发现一堆性质,结果由于DP中出现折线挂了. 题目描述 某NOIP普及组原题加强版. \(Jim\) 非常怕黑,他有一个手电筒,设手电筒的电量上限为 \( ...

  2. KMP 串的模式匹配 (25 分)

    给定两个由英文字母组成的字符串 String 和 Pattern,要求找到 Pattern 在 String 中第一次出现的位置,并将此位置后的 String 的子串输出.如果找不到,则输出“Not ...

  3. 「CQOI2014」数三角形

    题目链接 问题分析 可以先任意选\(3\)个数,然后减去三点共线的部分. 三点共线又分\(2\)种情况: 横的或者竖的.这一部分方案数是\(n\times{m\choose 3}+m\times {n ...

  4. Codeforces Round #201.C-Alice and Bob

    C. Alice and Bob time limit per test 2 seconds memory limit per test 256 megabytes input standard in ...

  5. 通过Flink实现个推海量消息数据的实时统计

    背景 消息报表主要用于统计消息任务的下发情况.比如,单条推送消息下发APP用户总量有多少,成功推送到手机的数量有多少,又有多少APP用户点击了弹窗通知并打开APP等.通过消息报表,我们可以很直观地看到 ...

  6. C++入门经典-例2.1-利用实数精度进行实数比较

    1:代码如下: // 2.1.cpp : 定义控制台应用程序的入口点. // #include "stdafx.h" void main() { float eps = 0.000 ...

  7. 套接字之recvmsg系统调用

    recvmsg系统调用允许用户指定msghdr结构来接收数据,可以将数据接收到多个缓冲区中,并且可以接收控制信息:接收信息过程与其他接收系统调用核心一致,都是调用传输层的接收函数进行数据接收: SYS ...

  8. 线性回归和正则化(Regularization)

    python风控建模实战lendingClub(博主录制,包含大量回归建模脚本和和正则化解释,2K超清分辨率) https://study.163.com/course/courseMain.htm? ...

  9. 浏览器端-W3School-JavaScript:JavaScript RegExp 对象

    ylbtech-浏览器端-W3School-JavaScript:JavaScript RegExp 对象 1.返回顶部 1. JavaScript RegExp 对象 RegExp 对象 RegEx ...

  10. 编辑器UEditor入门学习

    优点:非常使用的富文本编辑器,对比于之前使用的summernote,比前者多出了更多的字体图标 废话少说,直接步骤: 1.导入资源(全部放在单独的文件下即可,下图为“UEditor”文件夹) 2.引用 ...