當前位置:
首頁 > 知識 > 使用RedisTemplate(JDK序列化策略)緩存實體類

使用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查看(以位元組數組的形式):

使用RedisTemplate(JDK序列化策略)緩存實體類

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

XML DOM 節點樹
W3C辭彙和術語表

TAG:程序員小新人學習 |