---
title: "redis实现异步消息处理"
author: "bigSeven"
date: "2019-01-18T13:58:54Z"
tags: []
categories: ["编程语言"]
slug: "redis"
draft: false
lastmod: "2019-01-18T14:22:01Z"
id: 2436778
url: "https://bigseven.iteye.com/blog/2436778"
---

如何使用redis实现消息的订阅与发布

 

 **测试类**

01. /\**
02. `*redis消息订阅发布测试类`
03. `*/`
04. `@Controller`
05. `@RequestMapping(value="/queue")`
06. `publicclassTestControlller{`
07. `@Autowired`
08. `privateRedisTemplate redisService;`
09. `static{`
10. `newTestControlller().initThread("msgQueue");`
11. `}`
12. `/**订阅消息-启动消费队列数据线程**/`
13. `public void initThread(String key){`
14. `newThread(new blpopMessageHandler(key)).start();`
15. `}`
16. `/**发布消息--往队列里写数据**/`
17. `@RequestMapping(value="/brpush")`
18. `@UnSession`
19. `@ResponseBody`
20. `publicboolean brpush(String key,String name,int age)throwsException{`
21. `boolean flag = redisService.rpush(key,JSON.toJSONString(newEdu(name,age)));`
22. `return flag;`
23. `}`
24. `/**线程实时监听获取数据**/`
25. `class blpopMessageHandler implementsRunnable{`
26. `privateString key;`
27. `privateRedisTemplate redisTemplate=(RedisTemplate)SpringContextUtil.getBean("redisTemplate");`
28. `publicString getKey(){`
29. `return key;`
30. `}`
31. `publicvoid setKey(String key){`
32. `this.key = key;`
33. `}`
34. `public blpopMessageHandler(String key){`
35. `this.key = key;`
36. `}`
37. `@Override`
38. `publicvoid run(){`
39. `do{`
40. `//获取到数据`
41. `String result = redisTemplate.blpop(1000,key);`
42. `if(EmptyUtil.isNotEmpty(result)){`
43. `//do something`
44. `Edu edu = JSON.parseObject(result,Edu.class);`
45. `System.out.println("【线程一】"+edu.getName()+"---->"+edu.getAge());`
46. `}`
47. `}while(true);`
48. `}`
49. `}`
50. `}`

**model类**

01. ` `
02. `publicclassEduimplementsSerializable{`
03. `privatestaticfinallong serialVersionUID =-6336530413316596246L;`
04. `privateString name;`
05. `privateint age;`
06. `publicString getName(){`
07. `return name;`
08. `}`
09. `publicvoid setName(String name){`
10. `this.name = name;`
11. `}`
12. `publicint getAge(){`
13. `return age;`
14. `}`
15. `publicvoid setAge(int age){`
16. `this.age = age;`
17. `}`
18. `publicEdu(String name,int age){`
19. `this.name = name;`
20. `this.age = age;`
21. `}`
22. `@Override`
23. `publicString toString(){`
24. `return"Edu{"+`
25. `"name='"+ name +'\''+`
26. `", age="+ age +`
27. `'}';`
28. `}`
29. `}`

**操作redis类**

01. ` `
02. `/**`
03. `* 实现Jedis对象的封装，实现操作`
04. `*/`
05. `@Component`
06. `publicclassRedisTemplate{`
07. `privatestaticLogger logger =LoggerFactory.getLogger(RedisTemplate.class);`
08. `// 封装一个pool池用于jedis对象的管理`
09. `privatePool<Jedis> jedisPool;`
10. `publicRedisTemplate(Pool<Jedis> jedisPool){`
11. `this.jedisPool = jedisPool;`
12. `}`
13. `/**`
14. `* 存储REDIS队列 顺序存储`
15. `* @param key reids键名`
16. `* @param value 键值`
17. `*/`
18. `publicboolean rpush(String key,String value){`
19. `Jedis jedis =null;`
20. `boolean flag =false;`
21. `try{`
22. `jedis = jedisPool.getResource();`
23. `jedis.rpush(key.getBytes("utf-8"),value.getBytes("utf-8"));`
24. `flag =true;`
25. `}catch(Exception e){`
26. `//释放redis对象`
27. `jedisPool.returnBrokenResource(jedis);`
28. `e.printStackTrace();`
29. `}finally{`
30. `//返还到连接池`
31. `close(jedis);`
32. `}`
33. `return flag;`
34. `}`
35. `/**`
36. `* 获取队列数据`
37. `* @param key 键名`
38. `* @return`
39. `*/`
40. `publicString lpop(String key){`
41. `byte[] bytes =null;`
42. `Jedis jedis =null;`
43. `try{`
44. `jedis = jedisPool.getResource();`
45. `bytes = jedis.lpop(key.getBytes("utf-8"));`
46. `}catch(Exception e){`
47. `//释放redis对象`
48. `jedisPool.returnBrokenResource(jedis);`
49. `e.printStackTrace();`
50. `}finally{`
51. `//返还到连接池`
52. `close(jedis);`
53. `}`
54. `if(EmptyUtil.isNotEmpty(bytes)){`
55. `try{`
56. `returnnewString(bytes,"utf-8");`
57. `}catch(UnsupportedEncodingException e){`
58. `e.printStackTrace();`
59. `}`
60. `}`
61. `returnnull;`
62. `}`
63. `/**`
64. `* 获取阻塞list中的数据`
65. `* @param timeout`
66. `* @param key`
67. `* @return`
68. `*/`
69. `publicString blpop(int timeout,String key){`
70. `List<String> list =newArrayList<>();`
71. `Jedis jedis =null;`
72. `try{`
73. `jedis = jedisPool.getResource();`
74. `list = jedis.blpop(timeout,key);`
75. `}catch(Exception e){`
76. `//释放redis对象`
77. `jedisPool.returnBrokenResource(jedis);`
78. `e.printStackTrace();`
79. `}finally{`
80. `//返还到连接池`
81. `close(jedis);`
82. `}`
83. `returnEmptyUtil.isNotEmpty(list)&& list.size()>1? list.get(1):null;`
84. `}`
85. `privatevoid close(Jedis jedis){`
86. `try{`
87. `jedisPool.returnResource(jedis);`
88. `}catch(Exception e){`
89. `if(jedis.isConnected()){`
90. `jedis.quit();`
91. `jedis.disconnect();`
92. `}`
93. `}`
94. `}`
95. `}`