玖叶教程网

前端编程开发入门

使用RedisTemplate(JDK序列化策略)缓存实体类

一、相关配置

1.spring-redis.xml:

[java] view plain copy

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4. xmlns:context="http://www.springframework.org/schema/context"
  5. xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:cache="http://www.springframework.org/schema/cache"
  6. xsi:schemaLocation="http://www.springframework.org/schema/beans
  7. http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
  8. http://www.springframework.org/schema/context
  9. http://www.springframework.org/schema/context/spring-context-4.2.xsd
  10. http://www.springframework.org/schema/mvc
  11. http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
  12. http://www.springframework.org/schema/cache
  13. http://www.springframework.org/schema/cache/spring-cache-4.2.xsd">
  14. <context:property-placeholder location="classpath:redis.porperties" />
  15. <!-- 这里注入RedisUtil工具类,service层注解调用-->
  16. <context:component-scan base-package="com.xian.manager.util" />
  17. <!-- redis 相关配置 -->
  18. <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
  19. <property name="maxIdle" value="${redis.maxIdle}" />
  20. <property name="maxWaitMillis" value="${redis.maxWait}" />
  21. <property name="testOnBorrow" value="${redis.testOnBorrow}" />
  22. </bean>
  23. <bean id="connectionFactory" class="org.springframework.data.redis.connection.jedis.JedisConnectionFactory">
  24. <property name="poolConfig" ref="poolConfig" />
  25. <property name="port" value="${redis.port}" />
  26. <property name="hostName" value="${redis.host}" />
  27. <property name="password" value="${redis.pass}" />
  28. <property name="timeout" value="${redis.timeout}" />
  29. </bean>
  30. <bean id="redisTemplate" class="org.springframework.data.redis.core.RedisTemplate">
  31. <property name="connectionFactory" ref="connectionFactory" />
  32. </bean>
  33. </beans>

使用的是RedisTemplate默认的JDK序列化策略。

2.相关工具类:

1).Redis工具类

[java] view plain copy

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

2).序列化反序列化工具类

[java] view plain copy

  1. package com.xian.manager.util;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.ObjectInputStream;
  5. import java.io.ObjectOutputStream;
  6. import org.apache.log4j.Logger;
  7. public class SerializeUtil {
  8. private static Logger logger = Logger.getLogger(SerializeUtil.class);
  9. /*
  10. * 序列化
  11. */
  12. public static byte[] serialize(Object object) {
  13. ObjectOutputStream oos = null;
  14. ByteArrayOutputStream baos = null;
  15. try {
  16. baos = new ByteArrayOutputStream();
  17. oos = new ObjectOutputStream(baos);
  18. oos.writeObject(object);
  19. byte[] bytes = baos.toByteArray();
  20. return bytes;
  21. } catch (Exception e) {
  22. logger.warn("序列化对象出现异常: ", e);
  23. }
  24. return null;
  25. }
  26. /*
  27. * 反序列化
  28. */
  29. public static Object deserialize(byte[] bytes) {
  30. ByteArrayInputStream bais = null;
  31. try {
  32. bais = new ByteArrayInputStream(bytes);
  33. ObjectInputStream ois = new ObjectInputStream(bais);
  34. return ois.readObject();
  35. } catch (Exception e) {
  36. logger.warn("反序列化对象出现异常: ", e);
  37. }
  38. return null;
  39. }
  40. }

3). 实体类与字节数组互转工具类

[java] view plain copy

  1. package com.xian.manager.util;
  2. import java.io.ByteArrayInputStream;
  3. import java.io.ByteArrayOutputStream;
  4. import java.io.IOException;
  5. import java.io.ObjectInputStream;
  6. import java.io.ObjectOutputStream;
  7. public class ObjectAndByteUtil {
  8. /**
  9. * 对象转数组
  10. * @param obj
  11. * @return
  12. */
  13. public static byte[] toByteArray (Object obj) {
  14. byte[] bytes = null;
  15. ByteArrayOutputStream bos = new ByteArrayOutputStream();
  16. try {
  17. ObjectOutputStream oos = new ObjectOutputStream(bos);
  18. oos.writeObject(obj);
  19. oos.flush();
  20. bytes = bos.toByteArray ();
  21. oos.close();
  22. bos.close();
  23. } catch (IOException ex) {
  24. ex.printStackTrace();
  25. }
  26. return bytes;
  27. }
  28. /**
  29. * 数组转对象
  30. * @param bytes
  31. * @return
  32. */
  33. public static Object toObject (byte[] bytes) {
  34. Object obj = null;
  35. try {
  36. ByteArrayInputStream bis = new ByteArrayInputStream (bytes);
  37. ObjectInputStream ois = new ObjectInputStream (bis);
  38. obj = ois.readObject();
  39. ois.close();
  40. bis.close();
  41. } catch (IOException ex) {
  42. ex.printStackTrace();
  43. } catch (ClassNotFoundException ex) {
  44. ex.printStackTrace();
  45. }
  46. return obj;
  47. }
  48. }

三、具体使用

1.设值:

User user = new User();

user.setUsername("夜gg");

user.setPassword("123456");

redisUtil.set("user", user);

注意点:实体类User需要实现Serializable接口,而且重写toString()方法。

[java] view plain copy

  1. package com.xian.manager.entity;
  2. import java.io.Serializable;
  3. public class User implements Serializable{
  4. private int id;
  5. private String username;
  6. private String password;
  7. private int sex;
  8. private int age;
  9. private int state;
  10. public User() {
  11. }
  12. public String getUsername() {
  13. return username;
  14. }
  15. public void setUsername(String username) {
  16. this.username = username;
  17. }
  18. public String getPassword() {
  19. return password;
  20. }
  21. public void setPassword(String password) {
  22. this.password = password;
  23. }
  24. public int getSex() {
  25. return sex;
  26. }
  27. public void setSex(int sex) {
  28. this.sex = sex;
  29. }
  30. public int getAge() {
  31. return age;
  32. }
  33. public void setAge(int age) {
  34. this.age = age;
  35. }
  36. public int getId() {
  37. return id;
  38. }
  39. public void setId(int id) {
  40. this.id = id;
  41. }
  42. public int getState() {
  43. return state;
  44. }
  45. public void setState(int state) {
  46. this.state = state;
  47. }
  48. @Override
  49. public String toString() {
  50. return "User [id=" + id + ", username=" + username + ", password=" + password + ", sex=" + sex + ", age=" + age
  51. + ", state=" + state + "]";
  52. }
  53. }

2.取值:

User user = (User) SerializeUtil.deserialize(ObjectAndByteUtil.toByteArray(redisUtil.get("user")));

System.out.println(user.getUsername());

使用可视化工具RedisDesktopManager查看(以字节数组的形式):

发表评论:

控制面板
您好,欢迎到访网站!
  查看权限
网站分类
最新留言