• spring redis 工具类


    1. import org.apache.commons.lang3.StringUtils;
    2. import org.slf4j.Logger;
    3. import org.slf4j.LoggerFactory;
    4. import org.springframework.beans.factory.annotation.Autowired;
    5. import org.springframework.boot.actuate.health.HealthContributor;
    6. import org.springframework.data.redis.RedisConnectionFailureException;
    7. import org.springframework.data.redis.core.ListOperations;
    8. import org.springframework.data.redis.core.RedisConnectionUtils;
    9. import org.springframework.data.redis.core.RedisTemplate;
    10. import org.springframework.data.redis.core.ValueOperations;
    11. import org.springframework.stereotype.Component;
    12. import java.util.Collection;
    13. import java.util.List;
    14. import java.util.Set;
    15. import java.util.concurrent.TimeUnit;
    16. /**
    17. * spring redis 工具类
    18. *
    19. * @author
    20. **/
    21. @SuppressWarnings(value = {"unchecked", "rawtypes"})
    22. @Component
    23. public class RedisService {
    24. private static final Logger log = LoggerFactory.getLogger(RedisService.class);
    25. @Autowired
    26. public RedisTemplate redisTemplate;
    27. /**
    28. *
    29. *返回存储在键中的列表的指定元素
    30. *
    31. */
    32. public List range(String key, long start, long end) {
    33. if (RedisStatusTask.redisUp()) {
    34. try {
    35. ListOperations listOperations = redisTemplate.opsForList();
    36. return listOperations.range(key,start,end);
    37. } catch (RedisConnectionFailureException e) {
    38. log.error(e.getMessage());
    39. RedisStatusTask.redisMayDown();
    40. }
    41. }
    42. return null;
    43. }
    44. /**
    45. * 缓存基本的list集合对象等
    46. */
    47. public void leftPush(final String key,final T obj) {
    48. if (RedisStatusTask.redisUp()) {
    49. try {
    50. ListOperations listOperations = redisTemplate.opsForList();
    51. listOperations.leftPush(key,obj);
    52. } catch (RedisConnectionFailureException e) {
    53. log.error(e.getMessage());
    54. RedisStatusTask.redisMayDown();
    55. }
    56. }
    57. }
    58. /**
    59. * redis对唯一键值加锁
    60. * @param lockPrefix
    61. * @param key
    62. * @param timeout
    63. * @return
    64. */
    65. public boolean setNx(final String lockPrefix,final String key, long timeout) {
    66. if (RedisStatusTask.redisUp()) {
    67. try {
    68. return redisTemplate.opsForValue().setIfAbsent(lockPrefix + key, System.currentTimeMillis(),timeout,TimeUnit.SECONDS);
    69. } catch (RedisConnectionFailureException e) {
    70. log.error(e.getMessage());
    71. RedisStatusTask.redisMayDown();
    72. }
    73. }
    74. return true;
    75. }
    76. /**
    77. * 缓存基本的对象,Integer、String、实体类等
    78. *
    79. * @param key 缓存的键值
    80. * @param value 缓存的值
    81. */
    82. public void setCacheObject(final String key, final T value) {
    83. if (RedisStatusTask.redisUp()) {
    84. try {
    85. redisTemplate.opsForValue().set(key, value);
    86. } catch (RedisConnectionFailureException e) {
    87. log.error(e.getMessage());
    88. RedisStatusTask.redisMayDown();
    89. }
    90. }
    91. }
    92. /**
    93. * 缓存基本的对象,Integer、String、实体类等
    94. *
    95. * @param keys 缓存的键值
    96. * @param value 缓存的值
    97. */
    98. public void setCacheObject(final T value, final String... keys) {
    99. String key = StringUtils.join(keys, ":");
    100. setCacheObject(key, value);
    101. }
    102. /**
    103. * 缓存基本的对象,Integer、String、实体类等
    104. *
    105. * @param key 缓存的键值
    106. * @param value 缓存的值
    107. * @param timeout 时间
    108. * @param timeUnit 时间颗粒度
    109. */
    110. public void setCacheObject(final String key, final T value, final Long timeout, final TimeUnit timeUnit) {
    111. if (RedisStatusTask.redisUp()) {
    112. try {
    113. redisTemplate.opsForValue().set(key, value, timeout, timeUnit);
    114. } catch (RedisConnectionFailureException e) {
    115. log.error(e.getMessage());
    116. RedisStatusTask.redisMayDown();
    117. }
    118. }
    119. }
    120. public void setCacheObject(final T value, final Long timeout, final TimeUnit timeUnit, final String... keys) {
    121. String key = StringUtils.join(keys, ":");
    122. setCacheObject(key, value, timeout, timeUnit);
    123. }
    124. /**
    125. * 设置有效时间
    126. *
    127. * @param key Redis键
    128. * @param timeout 超时时间
    129. * @return true=设置成功;false=设置失败
    130. */
    131. public boolean expire(final String key, final long timeout) {
    132. return expire(key, timeout, TimeUnit.SECONDS);
    133. }
    134. /**
    135. * 设置有效时间
    136. *
    137. * @param keys Redis键
    138. * @param timeout 超时时间
    139. * @return true=设置成功;false=设置失败
    140. */
    141. public boolean expire(final long timeout,final TimeUnit unit,final String...keys) {
    142. String key = StringUtils.join(keys, ":");
    143. return expire(key, timeout, unit);
    144. }
    145. /**
    146. * 设置有效时间
    147. *
    148. * @param key Redis键
    149. * @param timeout 超时时间
    150. * @param unit 时间单位
    151. * @return true=设置成功;false=设置失败
    152. */
    153. public boolean expire(final String key, final long timeout, final TimeUnit unit) {
    154. if (RedisStatusTask.redisUp()) {
    155. try {
    156. return redisTemplate.expire(key, timeout, unit);
    157. } catch (RedisConnectionFailureException e) {
    158. log.error(e.getMessage());
    159. RedisStatusTask.redisMayDown();
    160. }
    161. }
    162. return false;
    163. }
    164. /**
    165. * 获得缓存的基本对象。
    166. *
    167. * @param key 缓存键值
    168. * @return 缓存键值对应的数据
    169. */
    170. public T getCacheObject(final String key) {
    171. if (RedisStatusTask.redisUp()) {
    172. try {
    173. ValueOperations operation = redisTemplate.opsForValue();
    174. return operation.get(key);
    175. } catch (RedisConnectionFailureException e) {
    176. log.error(e.getMessage());
    177. RedisStatusTask.redisMayDown();
    178. }
    179. }
    180. return null;
    181. }
    182. /**
    183. * 获得缓存的基本对象。
    184. *
    185. * @param keys 缓存键值
    186. * @return 缓存键值对应的数据
    187. */
    188. public T getCacheObject(final String... keys) {
    189. String key = StringUtils.join(keys, ":");
    190. return getCacheObject(key);
    191. }
    192. /**
    193. * 删除单个对象
    194. *
    195. * @param key
    196. */
    197. public boolean deleteObject(final String key) {
    198. if (RedisStatusTask.redisUp()) {
    199. try {
    200. return redisTemplate.delete(key);
    201. } catch (RedisConnectionFailureException e) {
    202. log.error(e.getMessage());
    203. RedisStatusTask.redisMayDown();
    204. }
    205. }
    206. return false;
    207. }
    208. /**
    209. * 删除单个对象
    210. *
    211. * @param keys
    212. */
    213. public boolean deleteObject(final String... keys) {
    214. String key = StringUtils.join(keys, ":");
    215. return deleteObject(key);
    216. }
    217. /**
    218. * 删除集合对象
    219. *
    220. * @param collection 多个对象
    221. * @return
    222. */
    223. public long deleteObject(final Collection collection) {
    224. if (RedisStatusTask.redisUp()) {
    225. try {
    226. return redisTemplate.delete(collection);
    227. } catch (RedisConnectionFailureException e) {
    228. log.error(e.getMessage());
    229. RedisStatusTask.redisMayDown();
    230. }
    231. }
    232. return 0l;
    233. }
    234. /**
    235. * 获得缓存的基本对象列表
    236. *
    237. * @param pattern 字符串前缀
    238. * @return 对象列表
    239. */
    240. public Collection keys(final String pattern) {
    241. if (RedisStatusTask.redisUp()) {
    242. try {
    243. return redisTemplate.keys(pattern);
    244. } catch (RedisConnectionFailureException e) {
    245. log.error(e.getMessage());
    246. RedisStatusTask.redisMayDown();
    247. }
    248. }
    249. return null;
    250. }
    251. public Long incrBy(Long incr, String... keys) {
    252. if (RedisStatusTask.redisUp()) {
    253. try {
    254. String key = StringUtils.join(keys, ":");
    255. return redisTemplate.opsForValue().increment(key, incr);
    256. } catch (RedisConnectionFailureException e) {
    257. log.error(e.getMessage());
    258. RedisStatusTask.redisMayDown();
    259. }
    260. }
    261. return 0l;
    262. }
    263. public Long decrBy(Long decr, String... keys) {
    264. if (RedisStatusTask.redisUp()) {
    265. try {
    266. String key = StringUtils.join(keys, ":");
    267. return redisTemplate.opsForValue().decrement(key, decr);
    268. } catch (RedisConnectionFailureException e) {
    269. log.error(e.getMessage());
    270. RedisStatusTask.redisMayDown();
    271. }
    272. }
    273. return 0l;
    274. }
    275. /**
    276. *
    277. *返回存储在键中的列表的指定元素
    278. *
    279. */
    280. public Set members(final String key) {
    281. if (RedisStatusTask.redisUp()) {
    282. try {
    283. return redisTemplate.opsForSet().members(key);
    284. } catch (RedisConnectionFailureException e) {
    285. log.error(e.getMessage());
    286. RedisStatusTask.redisMayDown();
    287. }
    288. }
    289. return null;
    290. }
    291. /**
    292. * set中增加元素,支持一次增加多个元素,逗号分隔即可,结果返回添加的个数
    293. *
    294. * @param key
    295. * @param value
    296. * @return
    297. */
    298. public Long addSet(String key, Object... value) {
    299. if (RedisStatusTask.redisUp()) {
    300. Long size = null;
    301. try {
    302. size = redisTemplate.opsForSet().add(key, value);
    303. return size;
    304. } catch (RedisConnectionFailureException e) {
    305. log.error(e.getMessage());
    306. RedisStatusTask.redisMayDown();
    307. }
    308. }
    309. return 0L;
    310. }
    311. /**
    312. * set中移除指定元素
    313. *
    314. * @param key
    315. * @param value
    316. * @return
    317. */
    318. public Long removeSet(String key, Object value) {
    319. if (RedisStatusTask.redisUp()) {
    320. Long size = null;
    321. try {
    322. size = redisTemplate.opsForSet().remove(key, value);
    323. return size;
    324. } catch (Exception e) {
    325. log.error(e.getMessage());
    326. RedisStatusTask.redisMayDown();
    327. }
    328. }
    329. return 0L;
    330. }
    331. /**
    332. * 计算set集合大小
    333. *
    334. * @param key
    335. * @return
    336. */
    337. public Long countSet(String key) {
    338. if (RedisStatusTask.redisUp()) {
    339. Long size = null;
    340. try {
    341. size = redisTemplate.opsForSet().size(key);
    342. return size;
    343. } catch (Exception e) {
    344. log.error(e.getMessage());
    345. RedisStatusTask.redisMayDown();
    346. }
    347. }
    348. return null;
    349. }
    350. /**
    351. * 判断set中是否存在某元素
    352. *
    353. * @param key
    354. * @param value
    355. * @return
    356. */
    357. public Boolean hasMemberSet(String key, Object value) {
    358. if (RedisStatusTask.redisUp()) {
    359. Boolean exist = false;
    360. try {
    361. exist = redisTemplate.opsForSet().isMember(key, value);
    362. return exist;
    363. } catch (Exception e) {
    364. log.error(e.getMessage());
    365. RedisStatusTask.redisMayDown();
    366. }
    367. }
    368. return false;
    369. }
    370. /**
    371. * 判断key是否存在
    372. *
    373. * @param key
    374. * @return
    375. */
    376. public Boolean hasKey(String key) {
    377. if (RedisStatusTask.redisUp()) {
    378. Boolean exist = false;
    379. try {
    380. exist = redisTemplate.hasKey(key);
    381. return exist;
    382. } catch (Exception e) {
    383. log.error(e.getMessage());
    384. RedisStatusTask.redisMayDown();
    385. }
    386. }
    387. return false;
    388. }
    389. /**
    390. * 获得缓存的基本对象。
    391. *
    392. * @param keys 缓存键值
    393. * @return 缓存键值对应的数据
    394. */
    395. public List getCacheList(final String... keys) {
    396. String key = StringUtils.join(keys, ":");
    397. return getCacheList(key);
    398. }
    399. /**
    400. * 获得缓存的基本对象。
    401. *
    402. * @param key 缓存键值
    403. * @return 缓存键值对应的数据
    404. */
    405. public List getCacheList(final String key) {
    406. if (RedisStatusTask.redisUp()) {
    407. try {
    408. Collection keys = keys(key);
    409. ValueOperations operation = redisTemplate.opsForValue();
    410. return operation.multiGet(keys);
    411. } catch (RedisConnectionFailureException e) {
    412. log.error(e.getMessage());
    413. RedisStatusTask.redisMayDown();
    414. }
    415. }
    416. return null;
    417. }
    418. }
    419. import org.springframework.beans.factory.annotation.Autowired;
    420. import org.springframework.boot.actuate.health.Health;
    421. import org.springframework.boot.actuate.health.Status;
    422. import org.springframework.boot.actuate.redis.RedisHealthIndicator;
    423. import org.springframework.data.redis.connection.RedisConnectionFactory;
    424. import org.springframework.scheduling.annotation.Scheduled;
    425. import org.springframework.stereotype.Component;
    426. /**
    427. * 检测redis状态
    428. */
    429. @Component
    430. public class RedisStatusTask {
    431. private static int status = 3;
    432. @Autowired
    433. private RedisConnectionFactory redisConnectionFactory;
    434. @Scheduled(fixedDelay = 1*60*1000)
    435. public void redisOK(){
    436. RedisHealthIndicator redisHealthIndicator = new RedisHealthIndicator(redisConnectionFactory);
    437. Health health = redisHealthIndicator.getHealth(false);
    438. String code = health.getStatus().getCode();
    439. if(code.equals(Status.UP.getCode()) && status<3){
    440. status = status + 1;
    441. }else if(status>0){
    442. status = status - 1;
    443. }
    444. }
    445. public static boolean redisUp(){
    446. return RedisStatusTask.status > 0;
    447. }
    448. public static void redisMayDown(){
    449. if(status>0){
    450. status = status - 1;
    451. }
    452. }
    453. }

  • 相关阅读:
    指针篇章-(4)+qsort函数的模拟
    国货之光!ATECLOUD—功能如此强大的测试测量上位机开发工具软件!
    LeetCode25:K个一组翻转链表
    积分简明笔记-第二类曲线积分的类型
    Azure Data Factory(十)Data Flow 组件详解
    温湿度传感器——I²C总线
    【Java基础面试三十七】、说一说Java的异常机制
    [WPF]浅析资源引用(pack URI)
    【35分钟掌握金融风控策略2】场景概述2
    【CGAL_网格】Surface_mesh
  • 原文地址:https://blog.csdn.net/IT_ziliang/article/details/126526677