经验首页 前端设计 程序设计 Java相关 移动开发 数据库/运维 软件/图像 大数据/云计算 其他经验
当前位置:技术经验 » 数据库/运维 » Redis » 查看文章
RedisTemplate常用方法封装
来源:cnblogs  作者:ccsert  时间:2021/5/17 9:16:44  对本文有异议

RedisTemplate常用方法封装

序列化和配置

  1. package com.gitee.ccsert.mall.common.redis.config;
  2. import com.fasterxml.jackson.annotation.JsonAutoDetect;
  3. import com.fasterxml.jackson.annotation.PropertyAccessor;
  4. import com.fasterxml.jackson.databind.ObjectMapper;
  5. import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
  6. import com.gitee.ccsert.mall.common.redis.RedisService;
  7. import com.gitee.ccsert.mall.common.redis.impl.RedisServiceImpl;
  8. import org.springframework.context.annotation.Bean;
  9. import org.springframework.data.redis.cache.RedisCacheConfiguration;
  10. import org.springframework.data.redis.cache.RedisCacheManager;
  11. import org.springframework.data.redis.cache.RedisCacheWriter;
  12. import org.springframework.data.redis.connection.RedisConnectionFactory;
  13. import org.springframework.data.redis.core.RedisTemplate;
  14. import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
  15. import org.springframework.data.redis.serializer.RedisSerializationContext;
  16. import org.springframework.data.redis.serializer.RedisSerializer;
  17. import org.springframework.data.redis.serializer.StringRedisSerializer;
  18. import java.time.Duration;
  19. /**
  20. * ClassName: RedisConfig <br/>
  21. * Description: redis连接配置类 <br/>
  22. */
  23. @Configuration
  24. public class BaseRedisConfig {
  25. @Bean
  26. public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
  27. RedisSerializer<Object> serializer = redisSerializer();
  28. RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
  29. redisTemplate.setConnectionFactory(redisConnectionFactory);
  30. redisTemplate.setKeySerializer(new StringRedisSerializer());
  31. redisTemplate.setValueSerializer(serializer);
  32. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
  33. redisTemplate.setHashValueSerializer(serializer);
  34. redisTemplate.afterPropertiesSet();
  35. return redisTemplate;
  36. }
  37. @Bean
  38. public RedisSerializer<Object> redisSerializer() {
  39. //创建JSON序列化器
  40. Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
  41. ObjectMapper objectMapper = new ObjectMapper();
  42. objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  43. //必须设置,否则无法将JSON转化为对象,会转化成Map类型
  44. objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL);
  45. serializer.setObjectMapper(objectMapper);
  46. return serializer;
  47. }
  48. @Bean
  49. public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory) {
  50. RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory);
  51. //设置Redis缓存有效期为1天
  52. RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig()
  53. .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer())).entryTtl(Duration.ofDays(1));
  54. return new RedisCacheManager(redisCacheWriter, redisCacheConfiguration);
  55. }
  56. @Bean
  57. public RedisService redisService(){
  58. return new RedisServiceImpl();
  59. }
  60. }

接口

  1. package com.gitee.ccsert.mall.common.redis;
  2. import org.springframework.data.domain.Sort;
  3. import org.springframework.data.geo.Distance;
  4. import org.springframework.data.geo.GeoResults;
  5. import org.springframework.data.geo.Point;
  6. import org.springframework.data.redis.connection.RedisGeoCommands;
  7. import java.util.List;
  8. import java.util.Map;
  9. import java.util.Set;
  10. /**
  11. * ClassName: RedisService <br/>
  12. * Description: redis操作接口 <br/>
  13. */
  14. public interface RedisService {
  15. /**
  16. * 保存属性
  17. *
  18. * @param key key值
  19. * @param value value值
  20. * @param time 时间戳
  21. */
  22. void set(String key, Object value, long time);
  23. /**
  24. * 保存属性
  25. *
  26. * @param key key值
  27. * @param value value值
  28. */
  29. void set(String key, Object value);
  30. /**
  31. * 获取属性
  32. *
  33. * @param key key值
  34. * @return 返回对象
  35. */
  36. Object get(String key);
  37. /**
  38. * 删除属性
  39. *
  40. * @param key key值
  41. * @return 返回成功
  42. */
  43. Boolean del(String key);
  44. /**
  45. * 批量删除属性
  46. *
  47. * @param keys key值集合
  48. * @return 返回删除数量
  49. */
  50. Long del(List<String> keys);
  51. /**
  52. * 设置过期时间
  53. *
  54. * @param key key值
  55. * @param time 时间戳
  56. * @return 返回成功
  57. */
  58. Boolean expire(String key, long time);
  59. /**
  60. * 获取过期时间
  61. *
  62. * @param key key值
  63. * @return 返回时间戳
  64. */
  65. Long getExpire(String key);
  66. /**
  67. * 判断key是否存在
  68. *
  69. * @param key key值
  70. * @return 返回
  71. */
  72. Boolean hasKey(String key);
  73. /**
  74. * 按delta递增
  75. *
  76. * @param key key值
  77. * @param delta delta值
  78. * @return 返回递增后结果
  79. */
  80. Long incr(String key, long delta);
  81. /**
  82. * 按delta递减
  83. *
  84. * @param key key值
  85. * @param delta delta值
  86. * @return 返回递减后结果
  87. */
  88. Long decr(String key, long delta);
  89. /**
  90. * 获取Hash结构中的属性
  91. *
  92. * @param key 外部key值
  93. * @param hashKey 内部key值
  94. * @return 返回内部key的value
  95. */
  96. Object hGet(String key, String hashKey);
  97. /**
  98. * 向Hash结构中放入一个属性
  99. *
  100. * @param key 外部key
  101. * @param hashKey 内部key
  102. * @param value 内部key的value
  103. * @param time 过期时间
  104. * @return 返回是否成功
  105. */
  106. Boolean hSet(String key, String hashKey, Object value, long time);
  107. /**
  108. * 向Hash结构中放入一个属性
  109. *
  110. * @param key 外部key
  111. * @param hashKey 内部key
  112. * @param value 内部key的value
  113. */
  114. void hSet(String key, String hashKey, Object value);
  115. /**
  116. * 直接获取整个Hash结构
  117. *
  118. * @param key 外部key值
  119. * @return 返回hashMap
  120. */
  121. Map<Object, Object> hGetAll(String key);
  122. /**
  123. * 直接设置整个Hash结构
  124. *
  125. * @param key 外部key
  126. * @param map hashMap值
  127. * @param time 过期时间
  128. * @return 返回是否成功
  129. */
  130. Boolean hSetAll(String key, Map<String, Object> map, long time);
  131. /**
  132. * 直接设置整个Hash结构
  133. *
  134. * @param key 外部key
  135. * @param map hashMap值
  136. */
  137. void hSetAll(String key, Map<String, ?> map);
  138. /**
  139. * 删除Hash结构中的属性
  140. *
  141. * @param key 外部key值
  142. * @param hashKey 内部key值
  143. */
  144. void hDel(String key, Object... hashKey);
  145. /**
  146. * 判断Hash结构中是否有该属性
  147. *
  148. * @param key 外部key
  149. * @param hashKey 内部key
  150. * @return 返回是否存在
  151. */
  152. Boolean hHasKey(String key, String hashKey);
  153. /**
  154. * Hash结构中属性递增
  155. *
  156. * @param key 外部key
  157. * @param hashKey 内部key
  158. * @param delta 递增条件
  159. * @return 返回递增后的数据
  160. */
  161. Long hIncr(String key, String hashKey, Long delta);
  162. /**
  163. * Hash结构中属性递减
  164. *
  165. * @param key 外部key
  166. * @param hashKey 内部key
  167. * @param delta 递增条件
  168. * @return 返回递减后的数据
  169. */
  170. Long hDecr(String key, String hashKey, Long delta);
  171. /**
  172. * 获取Set结构
  173. *
  174. * @param key key
  175. * @return 返回set集合
  176. */
  177. Set<Object> sMembers(String key);
  178. /**
  179. * 向Set结构中添加属性
  180. *
  181. * @param key key
  182. * @param values value集
  183. * @return 返回增加数量
  184. */
  185. Long sAdd(String key, Object... values);
  186. /**
  187. * 向Set结构中添加属性
  188. *
  189. * @param key key
  190. * @param time 过期时间
  191. * @param values 值集合
  192. * @return 返回添加的数量
  193. */
  194. Long sAdd(String key, long time, Object... values);
  195. /**
  196. * 是否为Set中的属性
  197. *
  198. * @param key key
  199. * @param value value
  200. * @return 返回是否存在
  201. */
  202. Boolean sIsMember(String key, Object value);
  203. /**
  204. * 获取Set结构的长度
  205. *
  206. * @param key key
  207. * @return 返回长度
  208. */
  209. Long sSize(String key);
  210. /**
  211. * 删除Set结构中的属性
  212. *
  213. * @param key key
  214. * @param values value集合
  215. * @return 删除掉的数据量
  216. */
  217. Long sRemove(String key, Object... values);
  218. /**
  219. * 获取List结构中的属性
  220. *
  221. * @param key key
  222. * @param start 开始
  223. * @param end 结束
  224. * @return 返回查询的集合
  225. */
  226. List<Object> lRange(String key, long start, long end);
  227. /**
  228. * 获取List结构的长度
  229. *
  230. * @param key key
  231. * @return 长度
  232. */
  233. Long lSize(String key);
  234. /**
  235. * 根据索引获取List中的属性
  236. *
  237. * @param key key
  238. * @param index 索引
  239. * @return 对象
  240. */
  241. Object lIndex(String key, long index);
  242. /**
  243. * 向List结构中添加属性
  244. *
  245. * @param key key
  246. * @param value value
  247. * @return 增加后的长度
  248. */
  249. Long lPush(String key, Object value);
  250. /**
  251. * 向List结构中添加属性
  252. *
  253. * @param key key
  254. * @param value value
  255. * @param time 过期时间
  256. * @return 增加后的长度
  257. */
  258. Long lPush(String key, Object value, long time);
  259. /**
  260. * 向List结构中批量添加属性
  261. *
  262. * @param key key
  263. * @param values value 集合
  264. * @return 增加后的长度
  265. */
  266. Long lPushAll(String key, Object... values);
  267. /**
  268. * 向List结构中批量添加属性
  269. *
  270. * @param key key
  271. * @param time 过期时间
  272. * @param values value集合
  273. * @return 增加后的长度
  274. */
  275. Long lPushAll(String key, Long time, Object... values);
  276. /**
  277. * 从List结构中移除属性
  278. *
  279. * @param key key
  280. * @param count 总量
  281. * @param value value
  282. * @return 返回删除后的长度
  283. */
  284. Long lRemove(String key, long count, Object value);
  285. /**
  286. * 向bitmap中新增值
  287. *
  288. * @param key key
  289. * @param offset 偏移量
  290. * @param b 状态
  291. * @return 结果
  292. */
  293. Boolean bitAdd(String key, int offset, boolean b);
  294. /**
  295. * 从bitmap中获取偏移量的值
  296. *
  297. * @param key key
  298. * @param offset 偏移量
  299. * @return 结果
  300. */
  301. Boolean bitGet(String key, int offset);
  302. /**
  303. * 获取bitmap的key值总和
  304. *
  305. * @param key key
  306. * @return 总和
  307. */
  308. Long bitCount(String key);
  309. /**
  310. * 获取bitmap范围值
  311. *
  312. * @param key key
  313. * @param limit 范围
  314. * @param offset 开始偏移量
  315. * @return long类型集合
  316. */
  317. List<Long> bitField(String key, int limit, int offset);
  318. /**
  319. * 获取所有bitmap
  320. *
  321. * @param key key
  322. * @return 以二进制字节数组返回
  323. */
  324. byte[] bitGetAll(String key);
  325. /**
  326. * 增加坐标
  327. *
  328. * @param key key
  329. * @param x x
  330. * @param y y
  331. * @param name 地点名称
  332. * @return 返回结果
  333. */
  334. Long geoAdd(String key, Double x, Double y, String name);
  335. /**
  336. * 根据城市名称获取坐标集合
  337. *
  338. * @param key key
  339. * @param place 地点
  340. * @return 坐标集合
  341. */
  342. List<Point> geoGetPointList(String key, Object... place);
  343. /**
  344. * 计算两个城市之间的距离
  345. *
  346. * @param key key
  347. * @param placeOne 地点1
  348. * @param placeTow 地点2
  349. * @return 返回距离
  350. */
  351. Distance geoCalculationDistance(String key, String placeOne, String placeTow);
  352. /**
  353. * 获取附该地点附近的其他地点
  354. *
  355. * @param key key
  356. * @param place 地点
  357. * @param distance 附近的范围
  358. * @param limit 查几条
  359. * @param sort 排序规则
  360. * @return 返回附近的地点集合
  361. */
  362. GeoResults<RedisGeoCommands.GeoLocation<Object>> geoNearByPlace(String key, String place, Distance distance, long limit, Sort.Direction sort);
  363. /**
  364. * 获取地点的hash
  365. *
  366. * @param key key
  367. * @param place 地点
  368. * @return 返回集合
  369. */
  370. List<String> geoGetHash(String key, String... place);
  371. }

实现

  1. package com.gitee.ccsert.mall.common.redis.impl;
  2. import com.gitee.ccsert.mall.common.redis.RedisService;
  3. import org.springframework.data.domain.Sort;
  4. import org.springframework.data.geo.Distance;
  5. import org.springframework.data.geo.GeoResults;
  6. import org.springframework.data.geo.Point;
  7. import org.springframework.data.redis.connection.BitFieldSubCommands;
  8. import org.springframework.data.redis.connection.RedisGeoCommands;
  9. import org.springframework.data.redis.core.RedisCallback;
  10. import org.springframework.data.redis.core.RedisTemplate;
  11. import javax.annotation.Resource;
  12. import java.util.List;
  13. import java.util.Map;
  14. import java.util.Set;
  15. import java.util.concurrent.TimeUnit;
  16. /**
  17. * ClassName: RedisServiceImpl <br/>
  18. * Description: redis操作的具体时间类 <br/>
  19. */
  20. public class RedisServiceImpl implements RedisService {
  21. @Resource
  22. private RedisTemplate<String, Object> redisTemplate;
  23. @Override
  24. public void set(String key, Object value, long time) {
  25. redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
  26. }
  27. @Override
  28. public void set(String key, Object value) {
  29. redisTemplate.opsForValue().set(key, value);
  30. }
  31. @Override
  32. public Object get(String key) {
  33. return redisTemplate.opsForValue().get(key);
  34. }
  35. @Override
  36. public Boolean del(String key) {
  37. return redisTemplate.delete(key);
  38. }
  39. @Override
  40. public Long del(List<String> keys) {
  41. return redisTemplate.delete(keys);
  42. }
  43. @Override
  44. public Boolean expire(String key, long time) {
  45. return redisTemplate.expire(key, time, TimeUnit.SECONDS);
  46. }
  47. @Override
  48. public Long getExpire(String key) {
  49. return redisTemplate.getExpire(key, TimeUnit.SECONDS);
  50. }
  51. @Override
  52. public Boolean hasKey(String key) {
  53. return redisTemplate.hasKey(key);
  54. }
  55. @Override
  56. public Long incr(String key, long delta) {
  57. return redisTemplate.opsForValue().increment(key, delta);
  58. }
  59. @Override
  60. public Long decr(String key, long delta) {
  61. return redisTemplate.opsForValue().increment(key, -delta);
  62. }
  63. @Override
  64. public Object hGet(String key, String hashKey) {
  65. return redisTemplate.opsForHash().get(key, hashKey);
  66. }
  67. @Override
  68. public Boolean hSet(String key, String hashKey, Object value, long time) {
  69. redisTemplate.opsForHash().put(key, hashKey, value);
  70. return expire(key, time);
  71. }
  72. @Override
  73. public void hSet(String key, String hashKey, Object value) {
  74. redisTemplate.opsForHash().put(key, hashKey, value);
  75. }
  76. @Override
  77. public Map<Object, Object> hGetAll(String key) {
  78. return redisTemplate.opsForHash().entries(key);
  79. }
  80. @Override
  81. public Boolean hSetAll(String key, Map<String, Object> map, long time) {
  82. redisTemplate.opsForHash().putAll(key, map);
  83. return expire(key, time);
  84. }
  85. @Override
  86. public void hSetAll(String key, Map<String, ?> map) {
  87. redisTemplate.opsForHash().putAll(key, map);
  88. }
  89. @Override
  90. public void hDel(String key, Object... hashKey) {
  91. redisTemplate.opsForHash().delete(key, hashKey);
  92. }
  93. @Override
  94. public Boolean hHasKey(String key, String hashKey) {
  95. return redisTemplate.opsForHash().hasKey(key, hashKey);
  96. }
  97. @Override
  98. public Long hIncr(String key, String hashKey, Long delta) {
  99. return redisTemplate.opsForHash().increment(key, hashKey, delta);
  100. }
  101. @Override
  102. public Long hDecr(String key, String hashKey, Long delta) {
  103. return redisTemplate.opsForHash().increment(key, hashKey, -delta);
  104. }
  105. @Override
  106. public Set<Object> sMembers(String key) {
  107. return redisTemplate.opsForSet().members(key);
  108. }
  109. @Override
  110. public Long sAdd(String key, Object... values) {
  111. return redisTemplate.opsForSet().add(key, values);
  112. }
  113. @Override
  114. public Long sAdd(String key, long time, Object... values) {
  115. Long count = redisTemplate.opsForSet().add(key, values);
  116. expire(key, time);
  117. return count;
  118. }
  119. @Override
  120. public Boolean sIsMember(String key, Object value) {
  121. return redisTemplate.opsForSet().isMember(key, value);
  122. }
  123. @Override
  124. public Long sSize(String key) {
  125. return redisTemplate.opsForSet().size(key);
  126. }
  127. @Override
  128. public Long sRemove(String key, Object... values) {
  129. return redisTemplate.opsForSet().remove(key, values);
  130. }
  131. @Override
  132. public List<Object> lRange(String key, long start, long end) {
  133. return redisTemplate.opsForList().range(key, start, end);
  134. }
  135. @Override
  136. public Long lSize(String key) {
  137. return redisTemplate.opsForList().size(key);
  138. }
  139. @Override
  140. public Object lIndex(String key, long index) {
  141. return redisTemplate.opsForList().index(key, index);
  142. }
  143. @Override
  144. public Long lPush(String key, Object value) {
  145. return redisTemplate.opsForList().rightPush(key, value);
  146. }
  147. @Override
  148. public Long lPush(String key, Object value, long time) {
  149. Long index = redisTemplate.opsForList().rightPush(key, value);
  150. expire(key, time);
  151. return index;
  152. }
  153. @Override
  154. public Long lPushAll(String key, Object... values) {
  155. return redisTemplate.opsForList().rightPushAll(key, values);
  156. }
  157. @Override
  158. public Long lPushAll(String key, Long time, Object... values) {
  159. Long count = redisTemplate.opsForList().rightPushAll(key, values);
  160. expire(key, time);
  161. return count;
  162. }
  163. @Override
  164. public Long lRemove(String key, long count, Object value) {
  165. return redisTemplate.opsForList().remove(key, count, value);
  166. }
  167. @Override
  168. public Boolean bitAdd(String key, int offset, boolean b) {
  169. return redisTemplate.opsForValue().setBit(key, offset, b);
  170. }
  171. @Override
  172. public Boolean bitGet(String key, int offset) {
  173. return redisTemplate.opsForValue().getBit(key, offset);
  174. }
  175. @Override
  176. public Long bitCount(String key) {
  177. return redisTemplate.execute((RedisCallback<Long>) con -> con.bitCount(key.getBytes()));
  178. }
  179. @Override
  180. public List<Long> bitField(String key, int limit, int offset) {
  181. return redisTemplate.execute((RedisCallback<List<Long>>) con ->
  182. con.bitField(key.getBytes(),
  183. BitFieldSubCommands.create().get(BitFieldSubCommands.BitFieldType.unsigned(limit)).valueAt(offset)));
  184. }
  185. @Override
  186. public byte[] bitGetAll(String key) {
  187. return redisTemplate.execute((RedisCallback<byte[]>) con -> con.get(key.getBytes()));
  188. }
  189. @Override
  190. public Long geoAdd(String key, Double x, Double y, String name) {
  191. return redisTemplate.opsForGeo().add(key, new Point(x, y), name);
  192. }
  193. @Override
  194. public List<Point> geoGetPointList(String key, Object... place) {
  195. return redisTemplate.opsForGeo().position(key, place);
  196. }
  197. @Override
  198. public Distance geoCalculationDistance(String key, String placeOne, String placeTow) {
  199. return redisTemplate.opsForGeo()
  200. .distance(key, placeOne, placeTow, RedisGeoCommands.DistanceUnit.KILOMETERS);
  201. }
  202. @Override
  203. public GeoResults<RedisGeoCommands.GeoLocation<Object>> geoNearByPlace(String key, String place, Distance distance, long limit, Sort.Direction sort) {
  204. RedisGeoCommands.GeoRadiusCommandArgs args = RedisGeoCommands.GeoRadiusCommandArgs.newGeoRadiusArgs().includeDistance().includeCoordinates();
  205. // 判断排序方式
  206. if (Sort.Direction.ASC == sort) {
  207. args.sortAscending();
  208. } else {
  209. args.sortDescending();
  210. }
  211. args.limit(limit);
  212. return redisTemplate.opsForGeo()
  213. .radius(key, place, distance, args);
  214. }
  215. @Override
  216. public List<String> geoGetHash(String key, String... place) {
  217. return redisTemplate.opsForGeo()
  218. .hash(key, place);
  219. }
  220. }

原文链接:http://www.cnblogs.com/ccsert/p/14755583.html

 友情链接:直通硅谷  点职佳  北美留学生论坛

本站QQ群:前端 618073944 | Java 606181507 | Python 626812652 | C/C++ 612253063 | 微信 634508462 | 苹果 692586424 | C#/.net 182808419 | PHP 305140648 | 运维 608723728

W3xue 的所有内容仅供测试,对任何法律问题及风险不承担任何责任。通过使用本站内容随之而来的风险与本站无关。
关于我们  |  意见建议  |  捐助我们  |  报错有奖  |  广告合作、友情链接(目前9元/月)请联系QQ:27243702 沸活量
皖ICP备17017327号-2 皖公网安备34020702000426号