PageRenderTime 3541ms CodeModel.GetById 25ms RepoModel.GetById 0ms app.codeStats 1ms

/src/main/java/com/tts/component/redis/AbstractRedisTemplate.java

https://gitlab.com/Fish-Potato/TTStreet-core
Java | 1124 lines | 832 code | 128 blank | 164 comment | 128 complexity | 789d2bb8dd497533dc83fe1bc22c8c92 MD5 | raw file
  1. package com.tts.component.redis;
  2. import com.alibaba.fastjson.JSON;
  3. import com.google.common.collect.Lists;
  4. import com.google.common.collect.Maps;
  5. import com.google.common.collect.Sets;
  6. import com.tts.util.JsonUtil;
  7. import org.apache.commons.collections.CollectionUtils;
  8. import org.apache.commons.collections.MapUtils;
  9. import org.apache.commons.lang.StringUtils;
  10. import org.slf4j.Logger;
  11. import org.slf4j.LoggerFactory;
  12. import org.springframework.dao.DataAccessException;
  13. import org.springframework.data.redis.connection.RedisConnection;
  14. import org.springframework.data.redis.core.RedisCallback;
  15. import org.springframework.data.redis.core.ZSetOperations;
  16. import org.springframework.data.redis.serializer.RedisSerializer;
  17. import org.springframework.data.redis.serializer.StringRedisSerializer;
  18. import java.util.*;
  19. import java.util.concurrent.TimeUnit;
  20. /**
  21. * Created by zhaoqi on 2016/8/11 0011.
  22. */
  23. public abstract class AbstractRedisTemplate {
  24. // 缓存统计信息打印,本身logback是异步打印,不需要自己起线程异步去打印了
  25. private final Logger logger = LoggerFactory.getLogger("cacheStatistic");
  26. private final Logger redisTimeOutLogger = LoggerFactory.getLogger("redisTimeOut");
  27. private final Logger warnLogger = LoggerFactory.getLogger(TTSRedisTemplate.class);
  28. private final static Integer TIMEOUT_THRESHOLD = 40;
  29. private static volatile boolean IS_CACHED = true;
  30. abstract TTSRedisTemplate<String, String> getRedisTemplate();
  31. abstract GracefulValueOperations<String, String> getValueOperations();
  32. abstract GracefulListOperations<String, String> getListOperations();
  33. abstract GracefulZSetOperations<String, String> getZsetOperations();
  34. public void setCached(boolean isCache) {
  35. IS_CACHED = isCache;
  36. }
  37. /**
  38. * @param key
  39. * @param value
  40. * @param timeout
  41. * 默认单位秒
  42. */
  43. public void setEx(String key, Object value, long timeout) {
  44. if (!IS_CACHED) {
  45. return;
  46. }
  47. String redisValue = null;
  48. if (value instanceof String) {
  49. redisValue = (String) value;
  50. } else {
  51. redisValue = JSON.toJSONString(value);
  52. }
  53. long beginTime = System.currentTimeMillis();
  54. try {
  55. getValueOperations().set(key, redisValue, timeout, TimeUnit.SECONDS);
  56. } catch (Exception e) {
  57. warnLogger.warn("add cache failed!!! cachekey is:{}", key, e);
  58. } finally {
  59. long endTime = System.currentTimeMillis();
  60. long costTime = endTime - beginTime;
  61. if (costTime > TIMEOUT_THRESHOLD) {
  62. redisTimeOutLogger.warn("add into cache timeOut cachekey is:{} cost time:{}", key, costTime);
  63. }
  64. }
  65. }
  66. /**
  67. *
  68. * @param map
  69. * @param timeout
  70. */
  71. public void mset(Map<String, ? extends Object> map, long timeout) {
  72. if (!IS_CACHED) {
  73. return;
  74. }
  75. if (MapUtils.isEmpty(map)) {
  76. return;
  77. }
  78. long beginTime = System.currentTimeMillis();
  79. getRedisTemplate().mset(map, timeout);
  80. long costTime = System.currentTimeMillis() - beginTime;
  81. if (costTime > TIMEOUT_THRESHOLD) {
  82. redisTimeOutLogger.warn("add into cache timeOut map is:{} cost time:{}", map.keySet(), costTime);
  83. }
  84. }
  85. /**
  86. * @param key
  87. */
  88. public boolean hasKey(String key) {
  89. if (!IS_CACHED) {
  90. return false;
  91. }
  92. long beginTime = System.currentTimeMillis();
  93. try {
  94. // 此处是读的操作
  95. // TODO
  96. boolean hasKey = getRedisTemplate().hasKey(key);
  97. if (hasKey) {
  98. } else {
  99. }
  100. return hasKey;
  101. } catch (Exception e) {
  102. warnLogger.warn("hasKey cache failed!!! key is: {}", key, e);
  103. } finally {
  104. long endTime = System.currentTimeMillis();
  105. long costTime = endTime - beginTime;
  106. if (costTime > TIMEOUT_THRESHOLD) {
  107. redisTimeOutLogger.warn("hasKey cache timeOut key is:{} cost time:{}", key, costTime);
  108. }
  109. }
  110. return false;
  111. }
  112. /**
  113. * setex命令不支持long expire 需要将这两个命令拆开,拆开之后命令就不是原子性的了,可能会出现set 命令成功 expire命令失败
  114. * 这样就会出现key永久有效的情况
  115. *
  116. * @param key
  117. */
  118. public void expire(String key, long timeout) {
  119. if (!IS_CACHED) {
  120. return;
  121. }
  122. long beginTime = System.currentTimeMillis();
  123. try {
  124. getRedisTemplate().longExpire(key, timeout, TimeUnit.SECONDS);
  125. } catch (Exception e) {
  126. warnLogger.error("expire cache failed!!! key is: {}", key, e);
  127. // 如果设置有效期失败,将之前塞进去的key删除
  128. this.deleteQuietly(key);
  129. } finally {
  130. long endTime = System.currentTimeMillis();
  131. long costTime = endTime - beginTime;
  132. if (costTime > TIMEOUT_THRESHOLD) {
  133. redisTimeOutLogger.warn("expire cache timeOut key is:{} cost time:{}", key, costTime);
  134. }
  135. }
  136. }
  137. public Long getExpire(String key) {
  138. if (!IS_CACHED) { return null; }
  139. long beginTime = System.currentTimeMillis();
  140. try {
  141. return getRedisTemplate().getExpire(key);
  142. } catch (Exception e) {
  143. warnLogger.error("Get expire failed!!! key is: {}", key, e);
  144. } finally {
  145. long endTime = System.currentTimeMillis();
  146. long costTime = endTime - beginTime;
  147. if (costTime > TIMEOUT_THRESHOLD) {
  148. redisTimeOutLogger.warn("Get expire cache timeOut key is:{} cost time:{}", key, costTime);
  149. }
  150. }
  151. return null;
  152. }
  153. private void deleteQuietly(String key) {
  154. try {
  155. getRedisTemplate().delete(key);
  156. } catch (Exception e) {
  157. warnLogger.error("delete cache failed!!! key is: {}", key, e);
  158. }
  159. }
  160. /**
  161. * @param keys
  162. * @param clazz
  163. * @return 传入的都返回,有数据返回数据,没有数据返回 NULL
  164. */
  165. public <T> Map<String, T> mget(List<String> keys, Class<T> clazz) {
  166. if (!IS_CACHED) {
  167. return null;
  168. }
  169. long beginTime = System.currentTimeMillis();
  170. long redistime=0L;
  171. try {
  172. List<String> multiGet = getValueOperations().multiGet(keys);
  173. redistime=System.currentTimeMillis()-beginTime;
  174. int size = multiGet.size();
  175. Map<String, T> result = new HashMap<String, T>(size);
  176. String curItem;
  177. for (int i = 0; i < size; i++) {
  178. curItem = multiGet.get(i);
  179. if (null == curItem) {
  180. result.put(keys.get(i), null);
  181. } else {
  182. result.put(keys.get(i), getValue(curItem, clazz));
  183. }
  184. }
  185. return result;
  186. } catch (Exception e) {
  187. warnLogger.warn("get from cache failed!!! keys is: {}", keys, e);
  188. HashMap<String, T> hashMap = new HashMap<String, T>(keys.size());
  189. for (String key : keys) {
  190. hashMap.put(key, null);
  191. }
  192. return hashMap;
  193. } finally {
  194. long endTime = System.currentTimeMillis();
  195. long costTime = endTime - beginTime;
  196. if (costTime > TIMEOUT_THRESHOLD) {
  197. redisTimeOutLogger.warn("get from cache timeout!!! keys is:{} cost time:{} redis time :{}", keys, costTime,redistime);
  198. }
  199. }
  200. }
  201. public List<String> multiGet(List<String> keys) {
  202. if (!IS_CACHED) {
  203. return null;
  204. }
  205. long beginTime = System.currentTimeMillis();
  206. long redisTime=0L;
  207. try {
  208. List<String> multiGet = getValueOperations().multiGet(keys);
  209. redisTime=System.currentTimeMillis()-beginTime;
  210. return multiGet;
  211. } catch (Exception e) {
  212. warnLogger.warn("get from cache failed!!! keys is: {}", keys, e);
  213. return Lists.newArrayList();
  214. } finally {
  215. long endTime = System.currentTimeMillis();
  216. long costTime = endTime - beginTime;
  217. if (costTime > TIMEOUT_THRESHOLD) {
  218. redisTimeOutLogger.warn("get from cache timeout!!! keys is:{} cost time:{} redis time :{}", keys, costTime,redisTime);
  219. }
  220. }
  221. }
  222. /**
  223. * 获取存在的 map 列表(不含 NULL)
  224. */
  225. public <T> Map<String, T> multiGetMapNotNULL(List<String> keys, Class<T> clazz) {
  226. if (CollectionUtils.isEmpty(keys)) return null;
  227. Map<String, T> result = mget(keys, clazz);
  228. return Maps.filterEntries(result, entity -> entity.getValue() != null);
  229. }
  230. /**
  231. *
  232. * @param keys
  233. * 批量获取int类型的value
  234. * @return
  235. */
  236. public Map<String, Integer> mgetIntValue(List<String> keys) {
  237. if (!IS_CACHED) {
  238. return null;
  239. }
  240. long beginTime = System.currentTimeMillis();
  241. long redistime=0L;
  242. try {
  243. List<String> multiGet = getValueOperations().multiGet(keys);
  244. redistime=System.currentTimeMillis()-beginTime;
  245. int size = multiGet.size();
  246. Map<String, Integer> result = new HashMap<String, Integer>(size);
  247. String curItem;
  248. for (int i = 0; i < size; i++) {
  249. curItem = multiGet.get(i);
  250. if (null == curItem) {
  251. result.put(keys.get(i), null);
  252. } else {
  253. result.put(keys.get(i), Integer.valueOf(curItem));
  254. }
  255. }
  256. return result;
  257. } catch (Exception e) {
  258. warnLogger.warn("get from cache failed!!! keys is: {}", keys, e);
  259. HashMap<String, Integer> hashMap = new HashMap<String, Integer>(keys.size());
  260. for (String key : keys) {
  261. hashMap.put(key, null);
  262. }
  263. return hashMap;
  264. } finally {
  265. long endTime = System.currentTimeMillis();
  266. long costTime = endTime - beginTime;
  267. if (costTime > TIMEOUT_THRESHOLD) {
  268. redisTimeOutLogger.warn("get from cache timeout!!! keys is:{} cost time:{} redis time :{}", keys, costTime,redistime);
  269. }
  270. }
  271. }
  272. /**
  273. * @param keys
  274. * @param clazz
  275. * @return
  276. */
  277. public <T> Map<String, List<T>> mgetList(final List<String> keys, final Class<T> clazz) {
  278. if (!IS_CACHED) {
  279. return null;
  280. }
  281. long beginTime = System.currentTimeMillis();
  282. long redistime=0L;
  283. try {
  284. List<String> multiGet = getValueOperations().multiGet(keys);
  285. redistime=System.currentTimeMillis()-beginTime;
  286. int size = multiGet.size();
  287. Map<String, List<T>> result = new HashMap<String, List<T>>(size);
  288. String curItem;
  289. for (int i = 0; i < size; i++) {
  290. curItem = multiGet.get(i);
  291. if (null == curItem) {
  292. result.put(keys.get(i), null);
  293. } else {
  294. result.put(keys.get(i), JSON.parseArray(curItem, clazz));
  295. }
  296. }
  297. return result;
  298. } catch (Exception e) {
  299. warnLogger.warn("get from cache failed!!! keys is: {}", keys, e);
  300. HashMap<String, List<T>> hashMap = new HashMap<String, List<T>>(keys.size());
  301. for (String key : keys) {
  302. hashMap.put(key, null);
  303. }
  304. return hashMap;
  305. } finally {
  306. long endTime = System.currentTimeMillis();
  307. long costTime = endTime - beginTime;
  308. if (costTime > TIMEOUT_THRESHOLD) {
  309. redisTimeOutLogger.warn("get from cache timeout!!! keys is:{} cost time:{} redis time :{}", keys, costTime,redistime);
  310. }
  311. }
  312. }
  313. /**
  314. * @param key
  315. * @param value
  316. */
  317. public void set(String key, Object value) {
  318. if (!IS_CACHED) {
  319. return;
  320. }
  321. String redisValue = null;
  322. if (value instanceof String) {
  323. redisValue = (String) value;
  324. } else {
  325. redisValue = JSON.toJSONString(value);
  326. }
  327. long beginTime = System.currentTimeMillis();
  328. try {
  329. getValueOperations().set(key, redisValue);
  330. } catch (Exception e) {
  331. warnLogger.warn("add cache failed!!! cachekey is:{}", key, e);
  332. } finally {
  333. long endTime = System.currentTimeMillis();
  334. long costTime = endTime - beginTime;
  335. if (costTime > TIMEOUT_THRESHOLD) {
  336. redisTimeOutLogger.warn("add into cache timeOut cachekey is:{} cost time:{}", key, costTime);
  337. }
  338. }
  339. }
  340. /**
  341. * 有序set的单个元素插入
  342. *
  343. * @param key
  344. * @param value
  345. */
  346. public void setSortedSet(String key, Object value, double score) {
  347. if (!IS_CACHED) {
  348. return;
  349. }
  350. String redisValue = null;
  351. if (value instanceof String) {
  352. redisValue = (String) value;
  353. } else {
  354. redisValue = JsonUtil.toString(value);
  355. }
  356. long beginTime = System.currentTimeMillis();
  357. try {
  358. getZsetOperations().add(key, redisValue, score);
  359. } catch (Exception e) {
  360. warnLogger.warn("add sortedSet cache failed!!! cachekey is " + key + "value is " + value, e);
  361. } finally {
  362. long costTime = System.currentTimeMillis() - beginTime;
  363. if (costTime > TIMEOUT_THRESHOLD) {
  364. redisTimeOutLogger.warn("add into cache timeOut cachekey is:{} cost time:{}", key, costTime);
  365. }
  366. }
  367. }
  368. /**
  369. * @param key
  370. * @param value
  371. */
  372. public void setIfAbsent(String key, Object value) {
  373. if (!IS_CACHED) {
  374. return;
  375. }
  376. String redisValue = null;
  377. if (value instanceof String) {
  378. redisValue = (String) value;
  379. } else {
  380. redisValue = JSON.toJSONString(value);
  381. }
  382. long beginTime = System.currentTimeMillis();
  383. try {
  384. getValueOperations().setIfAbsent(key, redisValue);
  385. } catch (Exception e) {
  386. warnLogger.warn("add cache failed!!! cachekey is:{}", key, e);
  387. } finally {
  388. long endTime = System.currentTimeMillis();
  389. long costTime = endTime - beginTime;
  390. if (costTime > TIMEOUT_THRESHOLD) {
  391. redisTimeOutLogger.warn("add into cache timeOut cachekey is:{} cost time:{}", key, costTime);
  392. }
  393. }
  394. }
  395. /**
  396. * @param key
  397. * @param clazz
  398. * @return
  399. */
  400. public <T> List<T> getList(String key, Class<T> clazz) {
  401. if (!IS_CACHED) {
  402. return null;
  403. }
  404. long beginTime = System.currentTimeMillis();
  405. List<T> t = null;
  406. try {
  407. String value = getValueOperations().get(key);
  408. if (StringUtils.isBlank(value)) {
  409. logger.info("cache miss key is:{}", key);
  410. return null;
  411. }
  412. t = JSON.parseArray(value, clazz);
  413. logger.info("cache hit key is:{}", key);
  414. return t;
  415. } catch (Exception e) {
  416. warnLogger.warn("get from cache failed!!! key is:{}", key, e);
  417. return null;
  418. } finally {
  419. long endTime = System.currentTimeMillis();
  420. long costTime = endTime - beginTime;
  421. if (costTime > TIMEOUT_THRESHOLD) {
  422. redisTimeOutLogger.warn("get from cache timeout!!! key is:{} cost time:{}", key, costTime);
  423. }
  424. }
  425. }
  426. /**
  427. * redis list 获取值列表, 全部记录
  428. *
  429. * @param key
  430. * @param startIndex
  431. * @param endIndex
  432. * @return
  433. */
  434. public List<String> getValueList(String key, int startIndex, int endIndex) {
  435. if (!IS_CACHED) {
  436. return Lists.newArrayList();
  437. }
  438. long beginTime = System.currentTimeMillis();
  439. try {
  440. List<String> valueList = getListOperations().range(key, startIndex, endIndex);
  441. if (CollectionUtils.isEmpty(valueList)) {
  442. logger.info("cache miss key is:{}", key);
  443. return Lists.newArrayList();
  444. }
  445. logger.info("cache hit key is:{}", key);
  446. return valueList;
  447. } catch (Exception e) {
  448. warnLogger.warn("get from cache failed!!! key is:{}", key, e);
  449. return Lists.newArrayList();
  450. } finally {
  451. long endTime = System.currentTimeMillis();
  452. long costTime = endTime - beginTime;
  453. if (costTime > TIMEOUT_THRESHOLD) {
  454. redisTimeOutLogger.warn("get from cache timeout!!! key is:{} cost time:{}", key, costTime);
  455. }
  456. }
  457. }
  458. /**
  459. * redis list 设置, 左塞
  460. *
  461. * @param key
  462. * @param value
  463. * @return
  464. */
  465. public void leftSetValueList(String key, String value) {
  466. if (!IS_CACHED) {
  467. return;
  468. }
  469. long beginTime = System.currentTimeMillis();
  470. try {
  471. getListOperations().leftPush(key, value);
  472. } catch (Exception e) {
  473. warnLogger.warn("set cache failed!!! key is: {},value is:{}", key, value, e);
  474. } finally {
  475. long endTime = System.currentTimeMillis();
  476. long costTime = endTime - beginTime;
  477. if (costTime > TIMEOUT_THRESHOLD) {
  478. redisTimeOutLogger.warn("get from cache timeout!!! key is:{} cost time:{}", key, costTime);
  479. }
  480. }
  481. }
  482. /**
  483. * redis list 设置, 左塞 (批量接口)
  484. *
  485. * @param key
  486. * @param values
  487. * @return
  488. */
  489. public void batchLeftSetValueList(String key, List<String> values) {
  490. if (!IS_CACHED) {
  491. return;
  492. }
  493. if (CollectionUtils.isEmpty(values)) {
  494. return;
  495. }
  496. long beginTime = System.currentTimeMillis();
  497. try {
  498. getListOperations().leftPushAll(key, values);
  499. } catch (Exception e) {
  500. warnLogger.warn("batchLeftSetValueList cache failed!!! key is:{} ,values is:{}", key, values, e);
  501. } finally {
  502. long endTime = System.currentTimeMillis();
  503. long costTime = endTime - beginTime;
  504. if (costTime > TIMEOUT_THRESHOLD) {
  505. redisTimeOutLogger.warn("batchLeftSetValueList cache timeout!!! key is:{} cost time:{}", key, costTime);
  506. }
  507. }
  508. }
  509. /**
  510. *
  511. * @param key
  512. * @param value
  513. * object
  514. */
  515. public void leftSetObjectValueList(String key, Object value) {
  516. if (!IS_CACHED) {
  517. return;
  518. }
  519. long beginTime = System.currentTimeMillis();
  520. try {
  521. getListOperations().leftPush(key, JSON.toJSONString(value));
  522. } catch (Exception e) {
  523. warnLogger.warn("set cache failed!!! key is:{},value is:{} ", key, value, e);
  524. } finally {
  525. long endTime = System.currentTimeMillis();
  526. long costTime = endTime - beginTime;
  527. if (costTime > TIMEOUT_THRESHOLD) {
  528. redisTimeOutLogger.warn("get from cache timeout!!! key is:{} cost time:{}", key, costTime);
  529. }
  530. }
  531. }
  532. /**
  533. *
  534. * @param key
  535. * @param values
  536. */
  537. public void batchLeftSetObjectValueList(String key, List<? extends Object> values) {
  538. if (!IS_CACHED) {
  539. return;
  540. }
  541. long beginTime = System.currentTimeMillis();
  542. if (CollectionUtils.isEmpty(values)) {
  543. return;
  544. }
  545. List<String> jsonValues = Lists.newArrayList();
  546. for (Object object : values) {
  547. jsonValues.add(JSON.toJSONString(object));
  548. }
  549. try {
  550. getListOperations().leftPushAll(key, jsonValues);
  551. } catch (Exception e) {
  552. warnLogger.warn("set cache failed!!! key is:{} ", key, e);
  553. } finally {
  554. long endTime = System.currentTimeMillis();
  555. long costTime = endTime - beginTime;
  556. if (costTime > TIMEOUT_THRESHOLD) {
  557. redisTimeOutLogger.warn("get from cache timeout!!! key is:{} cost time:{}", key, costTime);
  558. }
  559. }
  560. }
  561. /**
  562. *
  563. * @param key
  564. * @param values
  565. */
  566. public void batchRightSetObjectValueList(String key, List<? extends Object> values) {
  567. if (!IS_CACHED) {
  568. return;
  569. }
  570. long beginTime = System.currentTimeMillis();
  571. if (CollectionUtils.isEmpty(values)) {
  572. return;
  573. }
  574. List<String> jsonValues = Lists.newArrayList();
  575. for (Object object : values) {
  576. jsonValues.add(JSON.toJSONString(object));
  577. }
  578. try {
  579. getListOperations().rightPushAll(key, jsonValues);
  580. } catch (Exception e) {
  581. warnLogger.warn("set cache failed!!! key is:{} ", key, e);
  582. } finally {
  583. long endTime = System.currentTimeMillis();
  584. long costTime = endTime - beginTime;
  585. if (costTime > TIMEOUT_THRESHOLD) {
  586. redisTimeOutLogger.warn("get from cache timeout!!! key is:{} cost time:{}", key, costTime);
  587. }
  588. }
  589. }
  590. /**
  591. * redis list 设置, 右塞 (批量接口)
  592. *
  593. * @param key
  594. * @param values
  595. * @return
  596. */
  597. public void batchRightSetValueList(String key, List<String> values) {
  598. if (!IS_CACHED) {
  599. return;
  600. }
  601. if (CollectionUtils.isEmpty(values)) {
  602. return;
  603. }
  604. long beginTime = System.currentTimeMillis();
  605. try {
  606. getListOperations().rightPushAll(key, values);
  607. } catch (Exception e) {
  608. warnLogger.warn("batchLeftSetValueList cache failed!!! key is:{} ", key, e);
  609. } finally {
  610. long endTime = System.currentTimeMillis();
  611. long costTime = endTime - beginTime;
  612. if (costTime > TIMEOUT_THRESHOLD) {
  613. redisTimeOutLogger.warn("batchLeftSetValueList cache timeout!!! key is:{} cost time:{}", key, costTime);
  614. }
  615. }
  616. }
  617. /**
  618. * @param key
  619. * @param startIndex
  620. * @param length
  621. * @param clazz
  622. * @return
  623. */
  624. public <T> List<T> getValueObjectList(String key, int startIndex, int length, Class<T> clazz) {
  625. if (!IS_CACHED) {
  626. return Lists.newArrayList();
  627. }
  628. long beginTime = System.currentTimeMillis();
  629. try {
  630. List<String> valueList = getListOperations().range(key, startIndex, length);
  631. if (CollectionUtils.isEmpty(valueList)) {
  632. logger.info("cache miss key is:{}", key);
  633. return Lists.newArrayList();
  634. }
  635. logger.info("cache hit key is:{}", key);
  636. List<T> list = Lists.newArrayList();
  637. for (String value : valueList) {
  638. T t = JSON.parseObject(value, clazz);
  639. if (null != t) {
  640. list.add(t);
  641. }
  642. }
  643. return list;
  644. } catch (Exception e) {
  645. warnLogger.warn("get from cache failed!!! key is:{}", key, e);
  646. return Lists.newArrayList();
  647. } finally {
  648. long endTime = System.currentTimeMillis();
  649. long costTime = endTime - beginTime;
  650. if (costTime > TIMEOUT_THRESHOLD) {
  651. redisTimeOutLogger.warn("get from cache timeout!!! key is:{} cost time:{}", key, costTime);
  652. }
  653. }
  654. }
  655. /**
  656. * @param key
  657. * @return
  658. */
  659. public String getString(String key) {
  660. if (!IS_CACHED) {
  661. return null;
  662. }
  663. long beginTime = System.currentTimeMillis();
  664. String value = null;
  665. try {
  666. value = getValueOperations().get(key);
  667. if (StringUtils.isBlank(value)) {
  668. logger.info("cache miss key is:{}", key);
  669. } else {
  670. logger.info("cache hit key is:{}", key);
  671. }
  672. return value;
  673. } catch (Exception e) {
  674. warnLogger.warn("get from cache failed!!! key is:{}", key, e);
  675. return null;
  676. } finally {
  677. long endTime = System.currentTimeMillis();
  678. long costTime = endTime - beginTime;
  679. if (costTime > TIMEOUT_THRESHOLD) {
  680. redisTimeOutLogger.warn("get from cache timeout!!! key is:{} cost time:{}", key, costTime);
  681. }
  682. }
  683. }
  684. public Long incr(String key, long delta) {
  685. if (!IS_CACHED) {
  686. return null;
  687. }
  688. long beginTime = System.currentTimeMillis();
  689. try {
  690. return getValueOperations().increment(key, delta);
  691. } catch (Exception e) {
  692. warnLogger.warn("incr failed!!! key is:{}", key, e);
  693. return null;
  694. } finally {
  695. long endTime = System.currentTimeMillis();
  696. long costTime = endTime - beginTime;
  697. if (costTime > TIMEOUT_THRESHOLD) {
  698. redisTimeOutLogger.warn("incr to cache timeout!!! key is:{} cost time:{}", key, costTime);
  699. }
  700. }
  701. }
  702. /**
  703. * @param key
  704. * @param clazz
  705. * @return
  706. */
  707. public <T> T get(String key, Class<T> clazz) {
  708. if (!IS_CACHED) {
  709. return null;
  710. }
  711. long beginTime = System.currentTimeMillis();
  712. T t = null;
  713. try {
  714. String value = getValueOperations().get(key);
  715. if (StringUtils.isBlank(value)) {
  716. logger.info("cache miss key is:{}", key);
  717. return null;
  718. }
  719. t = getValue(value, clazz);
  720. logger.info("cache hit key is:{}", key);
  721. return t;
  722. } catch (Exception e) {
  723. warnLogger.warn("get from cache failed!!! key is:{}", key, e);
  724. return null;
  725. } finally {
  726. long endTime = System.currentTimeMillis();
  727. long costTime = endTime - beginTime;
  728. if (costTime > TIMEOUT_THRESHOLD) {
  729. redisTimeOutLogger.warn("get from cache timeout!!! key is:{} cost time:{}", key, costTime);
  730. }
  731. }
  732. }
  733. /**
  734. * @param keys
  735. */
  736. public void delete(Collection<String> keys) {
  737. if (!IS_CACHED) {
  738. return;
  739. }
  740. long beginTime = System.currentTimeMillis();
  741. try {
  742. getRedisTemplate().delete(keys);
  743. } catch (Exception e) {
  744. warnLogger.warn("delete from cache failed!!! key is:{}", keys, e);
  745. } finally {
  746. long endTime = System.currentTimeMillis();
  747. long costTime = endTime - beginTime;
  748. if (costTime > TIMEOUT_THRESHOLD) {
  749. redisTimeOutLogger.warn("delete from cache timeout!!! key is:{} cost time:{}", keys, costTime);
  750. }
  751. }
  752. }
  753. public void evictFromList(String key, String value, long count) {
  754. if (!IS_CACHED) {
  755. return;
  756. }
  757. long beginTime = System.currentTimeMillis();
  758. try {
  759. getListOperations().remove(key, count, value);
  760. } catch (Exception e) {
  761. warnLogger.warn("remove cache failed!!! key is: " + key + "; value = " + value, e);
  762. } finally {
  763. long endTime = System.currentTimeMillis();
  764. long costTime = endTime - beginTime;
  765. if (costTime > TIMEOUT_THRESHOLD) {
  766. redisTimeOutLogger.warn("get from cache timeout!!! key is:{} cost time:{}", key, costTime);
  767. }
  768. }
  769. }
  770. /**
  771. * 查询某键值对应list列表的长度
  772. *
  773. * @param key
  774. * @return
  775. */
  776. public long getValueListCount(String key) {
  777. if (!IS_CACHED) {
  778. return 0;
  779. }
  780. long beginTime = System.currentTimeMillis();
  781. try {
  782. Long size = getListOperations().size(key);
  783. if (null == size) {
  784. return 0;
  785. } else {
  786. return size;
  787. }
  788. } catch (Exception e) {
  789. warnLogger.warn("getValueListCount cache failed!!! key is:{} ", key, e);
  790. return 0;
  791. } finally {
  792. long endTime = System.currentTimeMillis();
  793. long costTime = endTime - beginTime;
  794. if (costTime > TIMEOUT_THRESHOLD) {
  795. redisTimeOutLogger.warn("get from cache timeout!!! key is:{} cost time:{}", key, costTime);
  796. }
  797. }
  798. }
  799. /**
  800. * 批量插入sortSet元素,只支持同一键值
  801. *
  802. * @param valueAndScoreMap
  803. * 键值为存储的值,map值为当前值的score(用于排序) 默认是升序
  804. */
  805. public void msetSortSet(String key, Map<Object, Double> valueAndScoreMap) {
  806. if (!IS_CACHED || MapUtils.isEmpty(valueAndScoreMap)) {
  807. return;
  808. }
  809. Set<ZSetOperations.TypedTuple<String>> typedTuples = new HashSet<ZSetOperations.TypedTuple<String>>(valueAndScoreMap.size());
  810. Object curValue;
  811. for (Map.Entry<Object, Double> entry : valueAndScoreMap.entrySet()) {
  812. final String curValueStr;
  813. curValue = entry.getKey();
  814. if (curValue instanceof String) {
  815. curValueStr = (String) curValue;
  816. } else {
  817. curValueStr = JSON.toJSONString(curValue);
  818. }
  819. typedTuples.add(new ZSetOperations.TypedTuple<String>() {
  820. @Override
  821. public int compareTo(ZSetOperations.TypedTuple<String> o) {
  822. return this.getScore() >= o.getScore() ? 1 : -1;
  823. }
  824. @Override
  825. public String getValue() {
  826. return curValueStr;
  827. }
  828. @Override
  829. public Double getScore() {
  830. return entry.getValue();
  831. }
  832. });
  833. }
  834. long beginTime = System.currentTimeMillis();
  835. try {
  836. getZsetOperations().add(key, typedTuples);
  837. } catch (Exception e) {
  838. warnLogger.warn("add zSetOperations cache failed!!! map key is" + key + "; valueAndScoreMap is " + valueAndScoreMap, e);
  839. } finally {
  840. long endTime = System.currentTimeMillis();
  841. long costTime = endTime - beginTime;
  842. if (costTime > TIMEOUT_THRESHOLD) {
  843. redisTimeOutLogger.warn("add into cache timeOut key is:{} cost time:{}", key, costTime);
  844. }
  845. }
  846. }
  847. /**
  848. * 查询sortedSet的长度
  849. */
  850. public Long countSortSet(String key) {
  851. if (!IS_CACHED) {
  852. return null;
  853. }
  854. long beginTime = System.currentTimeMillis();
  855. try {
  856. return getZsetOperations().size(key);
  857. } catch (Exception e) {
  858. warnLogger.warn("count zSetOperations cache failed!!! key is" + key, e);
  859. } finally {
  860. long endTime = System.currentTimeMillis();
  861. long costTime = endTime - beginTime;
  862. if (costTime > TIMEOUT_THRESHOLD) {
  863. redisTimeOutLogger.warn("count cache timeOut key is:{} cost time:{}", key, costTime);
  864. }
  865. }
  866. return null;
  867. }
  868. /**
  869. * 查询sortedSet的长度
  870. */
  871. public Long removeSortSet(String key, Object... values) {
  872. if (!IS_CACHED || null == values || 0 == values.length) {
  873. return null;
  874. }
  875. long beginTime = System.currentTimeMillis();
  876. try {
  877. return getZsetOperations().remove(key, values);
  878. } catch (Exception e) {
  879. warnLogger.warn("remove zSetOperations cache failed!!! key is" + key + "; values is " + values, e);
  880. } finally {
  881. long endTime = System.currentTimeMillis();
  882. long costTime = endTime - beginTime;
  883. if (costTime > TIMEOUT_THRESHOLD) {
  884. redisTimeOutLogger.warn("count cache timeOut key is:{} cost time:{}", key, costTime);
  885. }
  886. }
  887. return null;
  888. }
  889. /**
  890. * 分页查询sortedSet 查询失败则返回空的set
  891. */
  892. public Set<String> rangeSortSet(String key, long start, long end) {
  893. if (!IS_CACHED) {
  894. return null;
  895. }
  896. long beginTime = System.currentTimeMillis();
  897. try {
  898. return getZsetOperations().reverseRange(key, start, end);
  899. } catch (Exception e) {
  900. warnLogger.warn("range zSetOperations cache failed!!! key is" + key + "; start is " + start + "; end is " + end, e);
  901. } finally {
  902. long endTime = System.currentTimeMillis();
  903. long costTime = endTime - beginTime;
  904. if (costTime > TIMEOUT_THRESHOLD) {
  905. redisTimeOutLogger.warn("range cache timeOut key is:{} cost time:{}", key, costTime);
  906. }
  907. }
  908. return new HashSet<String>(0);
  909. }
  910. /**
  911. * 查询sortSet中有无当前的值 是否在set已有
  912. */
  913. public boolean existSortSet(String key, Object value) {
  914. if (!IS_CACHED) {
  915. return false;
  916. }
  917. long beginTime = System.currentTimeMillis();
  918. try {
  919. return null != getZsetOperations().score(key, value);
  920. } catch (Exception e) {
  921. warnLogger.warn("score zSetOperations cache failed!!! key is" + key + "; value is " + value, e);
  922. } finally {
  923. long endTime = System.currentTimeMillis();
  924. long costTime = endTime - beginTime;
  925. if (costTime > TIMEOUT_THRESHOLD) {
  926. redisTimeOutLogger.warn("score cache timeOut key is:{} cost time:{}", key, costTime);
  927. }
  928. }
  929. return false;
  930. }
  931. @SuppressWarnings("unchecked")
  932. private <T> T getValue(String value, Class<T> clazz) {
  933. T t = null;
  934. if (clazz.equals(String.class)) {
  935. t = (T) value;
  936. } else if (clazz.equals(Integer.class)) {
  937. t = (T) Integer.valueOf(value);
  938. } else {
  939. try
  940. {
  941. t = JSON.parseObject(value, clazz);
  942. }catch (Exception e) {
  943. warnLogger.warn("get value cache failed!!! value is: "+ value,e);
  944. }
  945. }
  946. return t;
  947. }
  948. /**
  949. * 获取keys
  950. * @param pattern
  951. * @return
  952. */
  953. public Set<String> getKeys(String pattern) {
  954. long beginTime = System.currentTimeMillis();
  955. try {
  956. return getRedisTemplate().keys(pattern);
  957. } catch (Exception e) {
  958. warnLogger.warn("getKeys failed!!! keys is: "+ pattern,e);
  959. } finally {
  960. long endTime = System.currentTimeMillis();
  961. long costTime = endTime - beginTime;
  962. if (costTime > TIMEOUT_THRESHOLD) {
  963. redisTimeOutLogger.warn("get keys cache timeOut pattern is:{} cost time:{}", pattern, costTime);
  964. }
  965. }
  966. return Sets.newHashSet();
  967. }
  968. /**
  969. * 批量获取keys
  970. * @param keysPattern
  971. * @return
  972. */
  973. public Set<String> getKeysBatch(Set<String> keysPattern) {
  974. Set<String> keysSet = Sets.newHashSet();
  975. List<Object> results = this.getRedisTemplate().executePipelined(new RedisCallback<Object>() {
  976. @Override
  977. public Object doInRedis(RedisConnection connection) throws DataAccessException {
  978. // connection.openPipeline();
  979. RedisSerializer<String> keySerializer=new StringRedisSerializer();
  980. for (String keyPattern : keysPattern) {
  981. connection.keys(keySerializer.serialize(keyPattern));
  982. }
  983. return null;
  984. }
  985. });
  986. for (Object result: results){
  987. if (result instanceof LinkedHashSet) {
  988. LinkedHashSet result1 = (LinkedHashSet) result;
  989. if (CollectionUtils.isNotEmpty(result1)) {
  990. keysSet.addAll(result1);
  991. }
  992. }
  993. }
  994. return keysSet;
  995. }
  996. }