本文介绍了Java利用Redis实现消息队列的示例代码,分享给大家,具体如下:
应用场景
为什么要用redis?
二进制存储、java序列化传输、IO连接数高、连接频繁
一、序列化
这里编写了一个java序列化的工具,主要是将对象转化为byte数组,和根据byte数组反序列化成java对象; 主要是用到了ByteArrayOutputStream和ByteArrayInputStream; 注意:每个需要序列化的对象都要实现Serializable接口;
其代码如下:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
|
package Utils;
import java.io.*;
/**
* Created by Kinglf on 2016/10/17.
*/
public class ObjectUtil {
/**
* 对象转byte[]
* @param obj
* @return
* @throws IOException
*/
public static byte [] object2Bytes(Object obj) throws IOException{
ByteArrayOutputStream bo= new ByteArrayOutputStream();
ObjectOutputStream oo= new ObjectOutputStream(bo);
oo.writeObject(obj);
byte [] bytes=bo.toByteArray();
bo.close();
oo.close();
return bytes;
}
/**
* byte[]转对象
* @param bytes
* @return
* @throws Exception
*/
public static Object bytes2Object( byte [] bytes) throws Exception{
ByteArrayInputStream in= new ByteArrayInputStream(bytes);
ObjectInputStream sIn= new ObjectInputStream(in);
return sIn.readObject();
}
}
|
二、消息类(实现Serializable接口)
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package Model;
import java.io.Serializable;
/**
* Created by Kinglf on 2016/10/17.
*/
public class Message implements Serializable {
private static final long serialVersionUID = -389326121047047723L;
private int id;
private String content;
public Message( int id, String content) {
this .id = id;
this .content = content;
}
public int getId() {
return id;
}
public void setId( int id) {
this .id = id;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this .content = content;
}
}
|
三、Redis的操作
利用redis做队列,我们采用的是redis中list的push和pop操作;
结合队列的特点:
只允许在一端插入新元素只能在队列的尾部FIFO:先进先出原则
Redis中lpush头入(rpop尾出)或rpush尾入(lpop头出)可以满足要求,而Redis中list药push或 pop的对象仅需要转换成byte[]即可
java采用Jedis进行Redis的存储和Redis的连接池设置
上代码:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
|