一、测试未序列化的结果

  1. com.xxx目录下新建pojo文件夹用于保存实体类,并添加User用户类用于测试

    1. @Component // 添加为组件,方便直接调用
    2. @AllArgsConstructor
    3. @NoArgsConstructor
    4. @Data
    5. public class User {
    6. private String name;
    7. private Integer age;
    8. }
  2. 在测试类中添加测试函数 ```java @Test // 表明此为测试函数 public void test() throws JsonProcessingException { // 真实开发一般使用 json 传递对象 User user = new User(“xiaohe”, 20); // 将对象转换成 json 字符串进行传值 String jsonUser = new ObjectMapper().writeValueAsString(user);

    // 创建一个键值对,key = user,value = jsonUser redisTemplate.opsForValue().set(“user”, jsonUser);

    // 获取加入 redis 中的数据 System.out.println(redisTemplate.opsForValue().get(“user”)); }

// 得到如下结果 {“name”:”xiaohe”, “age”:20}

  1. 3. 测试直接将对象传递给`redisTemplate.opsForValue().set(key, value);`
  2. ```java
  3. @Test // 表明此为测试函数
  4. public void test() throws JsonProcessingException {
  5. // 真实开发一般使用 json 传递对象
  6. User user = new User("xiaohe", 20);
  7. // 创建一个键值对,key = user,value = jsonUser
  8. redisTemplate.opsForValue().set("user", user);
  9. // 获取加入 redis 中的数据
  10. System.out.println(redisTemplate.opsForValue().get("user"));
  11. }
  12. // 得到如下报错结果
  13. // Cannot serialize 表示没有序列化,对象无法进行传输
  14. org.springframework.data.redis.serializer.SerializationException: Cannot serialize; nested exception is org.springframework.core.serializer.support.SerializationFailedException: Failed to serialize object using DefaultSerializer; nested exception is java.lang.IllegalArgumentException: DefaultSerializer requires a Serializable payload but received an object of type [com.hyh.pojo.User]
  15. at org.springframework.data.redis.serializer.JdkSerializationRedisSerializer.serialize(JdkSerializationRedisSerializer.java:96)
  16. at org.springframework.data.redis.core.AbstractOperations.rawValue(AbstractOperations.java:128)
  17. at org.springframework.data.redis.core.DefaultValueOperations.set(DefaultValueOperations.java:304)
  18. at com.hyh.SpringbootRedisApplicationTests.test(SpringbootRedisApplicationTests.java:67)
  19. at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  20. at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  21. at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  22. at java.lang.reflect.Method.invoke(Method.java:498)
  23. ...
  1. 将实体类进行序列化

    1. // 实践中,一般所有的实体类都会序列化
    2. @Component // 添加为组件,方便直接调用
    3. @AllArgsConstructor
    4. @NoArgsConstructor
    5. @Data
    6. public class User implements Serializable {
    7. private String name;
    8. private Integer age;
    9. }
  2. 序列化后再次测试直接传入对象 ```java @Test // 表明此为测试函数 public void test() throws JsonProcessingException { // 真实开发一般使用 json 传递对象 User user = new User(“xiaohe”, 20);

    // 创建一个键值对,key = user,value = jsonUser redisTemplate.opsForValue().set(“user”, user);

    // 获取加入 redis 中的数据 System.out.println(redisTemplate.opsForValue().get(“user”)); }

// 得到结果 User(name=xiaohe, age=20)

  1. <a name="cMI5U"></a>
  2. # 二、自定义`Redis`配置类用于序列化
  3. 1. 项目主文件夹下添加`config`目录,新增`RedisConfig`用于自定义`RedisTemplate`
  4. 1. `com.xxx`目录下新建`config`文件夹,并添加`RedisConfig`配置类
  5. 1. 添加自己的`RedisTemplate``myRedisTemplate`
  6. ```java
  7. @Bean
  8. @SuppressWarnings("all")
  9. public RedisTemplate<String, Object> myRedisTemplate(RedisConnectionFactory factory) {
  10. // 为了自己开发方便,一般直接使用 <String, Object>
  11. RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
  12. template.setConnectionFactory(factory);
  13. // 设置 Json 序列化配置
  14. Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
  15. ObjectMapper om = new ObjectMapper();
  16. om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
  17. om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
  18. jackson2JsonRedisSerializer.setObjectMapper(om);
  19. // 设置 String 类型序列化
  20. StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
  21. // 设置 key 采用 String 的序列化方式
  22. template.setKeySerializer(stringRedisSerializer);
  23. // 设置 hash 的 key 也采用 String 的序列化方式
  24. template.setHashKeySerializer(stringRedisSerializer);
  25. // 设置 value 序列化方式采用 jackson
  26. template.setValueSerializer(jackson2JsonRedisSerializer);
  27. // 设置 hash 的 value 序列化方式采用 jackson
  28. template.setHashValueSerializer(jackson2JsonRedisSerializer);
  29. template.afterPropertiesSet();
  30. return template;
  31. }
  1. 添加自己的序列化myRedisTemplate后,重新执行test,此时的对象User user会被一个String类型接管 ```java @Test // 表明此为测试函数 public void test() throws JsonProcessingException { // 真实开发一般使用 json 传递对象 User user = new User(“xiaohe”, 20);

    // 创建一个键值对,key = user,value = jsonUser redisTemplate.opsForValue().set(“user”, user);

    // 获取加入 redis 中的数据 System.out.println(redisTemplate.opsForValue().get(“user”)); }

// 得到结果 User(name=xiaohe, age=20)

// cmd 查询结果 127.0.0.1:6379> keys * 1) “user” // 被String 类型接管

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

    1. 添加自定义工具类RedisUtil的注入

      1. @Autowired
      2. private RedisUtil redisUtil;
    2. 添加测试类testRedisUtil,然后就会发现使用redisUtil可以直接像在cmd窗口中一样使用各种熟悉的命令!简直妙啊!

image.png