RedisCache.java 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. package com.zskk.pacsonline.utils;
  2. import org.springframework.beans.factory.annotation.Autowired;
  3. import org.springframework.data.redis.core.RedisTemplate;
  4. import org.springframework.stereotype.Component;
  5. import java.util.concurrent.TimeUnit;
  6. /**
  7. * Redis缓存工具类
  8. *
  9. * @author admin
  10. */
  11. @Component
  12. public class RedisCache {
  13. @Autowired
  14. private RedisTemplate<String, Object> redisTemplate;
  15. /**
  16. * 缓存基本的对象
  17. *
  18. * @param key 缓存的键
  19. * @param value 缓存的值
  20. */
  21. public <T> void set(String key, T value) {
  22. redisTemplate.opsForValue().set(key, value);
  23. }
  24. /**
  25. * 缓存基本的对象,带过期时间
  26. *
  27. * @param key 缓存的键
  28. * @param value 缓存的值
  29. * @param timeout 时间
  30. * @param timeUnit 时间单位
  31. */
  32. public <T> void set(String key, T value, long timeout, TimeUnit timeUnit) {
  33. redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
  34. }
  35. /**
  36. * 获得缓存的基本对象
  37. *
  38. * @param key 缓存键
  39. * @return 缓存值
  40. */
  41. public <T> T get(String key) {
  42. return (T) redisTemplate.opsForValue().get(key);
  43. }
  44. /**
  45. * 删除单个对象
  46. *
  47. * @param key 缓存键
  48. */
  49. public void delete(String key) {
  50. redisTemplate.delete(key);
  51. }
  52. /**
  53. * 判断key是否存在
  54. *
  55. * @param key 缓存键
  56. * @return true存在 false不存在
  57. */
  58. public boolean hasKey(String key) {
  59. return Boolean.TRUE.equals(redisTemplate.hasKey(key));
  60. }
  61. /**
  62. * 设置有效时间
  63. *
  64. * @param key 缓存键
  65. * @param timeout 超时时间
  66. * @return true=设置成功;false=设置失败
  67. */
  68. public boolean expire(String key, long timeout) {
  69. return expire(key, timeout, TimeUnit.SECONDS);
  70. }
  71. /**
  72. * 设置有效时间
  73. *
  74. * @param key 缓存键
  75. * @param timeout 超时时间
  76. * @param timeUnit 时间单位
  77. * @return true=设置成功;false=设置失败
  78. */
  79. public boolean expire(String key, long timeout, TimeUnit timeUnit) {
  80. return Boolean.TRUE.equals(redisTemplate.expire(key, timeout, timeUnit));
  81. }
  82. /**
  83. * 获取过期时间
  84. *
  85. * @param key 缓存键
  86. * @return 过期时间(秒)
  87. */
  88. public long getExpire(String key) {
  89. Long expire = redisTemplate.getExpire(key, TimeUnit.SECONDS);
  90. return expire != null ? expire : -1;
  91. }
  92. }