java redis使用之利用jedis实现redis消息队列

来源:互联网 发布:geekbench mac下载 编辑:程序博客网 时间:2024/05/20 16:00

应用场景

最近在公司做项目,需要对聊天内容进行存储,考虑到数据库查询的IO连接数高、连接频繁的因素,决定利用缓存做。

从网上了解到redis可以对所有的内容进行二进制的存储,而java是可以对所有对象进行序列化的,序列化的方法会在下面的代码中提供实现。

序列化

这里我编写了一个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
packagecom.bean.util;
 
importjava.io.ByteArrayInputStream;
importjava.io.ByteArrayOutputStream;
importjava.io.IOException;
importjava.io.ObjectInputStream;
importjava.io.ObjectOutputStream;
publicclass ObjectUtil {
    /**对象转byte[]
     * @param obj
     * @return
     * @throws IOException
     */
    publicstatic byte[] objectToBytes(Object obj) throwsException{
        ByteArrayOutputStream bo = newByteArrayOutputStream();
        ObjectOutputStream oo = newObjectOutputStream(bo);
        oo.writeObject(obj);
        byte[] bytes = bo.toByteArray();
        bo.close();
        oo.close();
        returnbytes;
    }
    /**byte[]转对象
     * @param bytes
     * @return
     * @throws Exception
     */
    publicstatic Object bytesToObject(byte[] bytes) throwsException{
        ByteArrayInputStream in = newByteArrayInputStream(bytes);
        ObjectInputStream sIn = newObjectInputStream(in);
        returnsIn.readObject();
    }
}

定义一个消息类,主要用于接收消息内容和消息下表的设置。

?
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
packagecom.bean;
 
importjava.io.Serializable;
 
/**定义消息类接收消息内容和设置消息的下标
 * @author lenovo
 *
 */
publicclass Message implementsSerializable{
    privatestatic final long serialVersionUID = 7792729L;
    privateint id;
    privateString content;
    publicint getId() {
        returnid;
    }
    publicvoid setId(intid) {
        this.id = id;
    }
    publicString getContent() {
        returncontent;
    }
    publicvoid setContent(String content) {
        this.content = content;
    }
}

利用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
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
packagecom.redis.util;
 
importjava.util.List;
importjava.util.Map;
importjava.util.Set;
 
importredis.clients.jedis.Jedis;
importredis.clients.jedis.JedisPool;
importredis.clients.jedis.JedisPoolConfig;
 
publicclass JedisUtil {
 
    privatestatic String JEDIS_IP;
    privatestatic int JEDIS_PORT;
    privatestatic String JEDIS_PASSWORD;
    //private static String JEDIS_SLAVE;
 
    privatestatic JedisPool jedisPool;
 
    static{
        Configuration conf = Configuration.getInstance();
        JEDIS_IP = conf.getString("jedis.ip","127.0.0.1");
        JEDIS_PORT = conf.getInt("jedis.port",6379);
        JEDIS_PASSWORD = conf.getString("jedis.password",null);
        JedisPoolConfig config = newJedisPoolConfig();
        config.setMaxActive(5000);
        config.setMaxIdle(256);//20
        config.setMaxWait(5000L);
        config.setTestOnBorrow(true);
        config.setTestOnReturn(true);
        config.setTestWhileIdle(true);
        config.setMinEvictableIdleTimeMillis(60000l);
        config.setTimeBetweenEvictionRunsMillis(3000l);
        config.setNumTestsPerEvictionRun(-1);
        jedisPool = newJedisPool(config, JEDIS_IP, JEDIS_PORT, 60000);
    }
 
    /**
     * 获取数据
     * @param key
     * @return
     */
    publicstatic String get(String key) {
 
        String value = null;
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            value = jedis.get(key);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        }finally{
            //返还到连接池
            close(jedis);
        }
 
        returnvalue;
    }
 
    publicstatic void close(Jedis jedis) {
        try{
            jedisPool.returnResource(jedis);
 
        }catch(Exception e) {
            if(jedis.isConnected()) {
                jedis.quit();
                jedis.disconnect();
            }
        }
    }
 
    /**
     * 获取数据
     *
     * @param key
     * @return
     */
    publicstatic byte[] get(byte[] key) {
 
        byte[] value = null;
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            value = jedis.get(key);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        }finally{
            //返还到连接池
            close(jedis);
        }
 
        returnvalue;
    }
 
    publicstatic void set(byte[] key, byte[] value) {
 
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.set(key, value);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        }finally{
            //返还到连接池
            close(jedis);
        }
    }
 
    publicstatic void set(byte[] key, byte[] value, inttime) {
 
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.set(key, value);
            jedis.expire(key, time);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        }finally{
            //返还到连接池
            close(jedis);
        }
    }
 
    publicstatic void hset(byte[] key, byte[] field, byte[] value) {
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.hset(key, field, value);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        }finally{
            //返还到连接池
            close(jedis);
        }
    }
 
    publicstatic void hset(String key, String field, String value) {
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.hset(key, field, value);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        }finally{
            //返还到连接池
            close(jedis);
        }
    }
 
    /**
     * 获取数据
     *
     * @param key
     * @return
     */
    publicstatic String hget(String key, String field) {
 
        String value = null;
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            value = jedis.hget(key, field);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        }finally{
            //返还到连接池
            close(jedis);
        }
 
        returnvalue;
    }
 
    /**
     * 获取数据
     *
     * @param key
     * @return
     */
    publicstatic byte[] hget(byte[] key, byte[] field) {
 
        byte[] value = null;
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            value = jedis.hget(key, field);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        }finally{
            //返还到连接池
            close(jedis);
        }
 
        returnvalue;
    }
 
    publicstatic void hdel(byte[] key, byte[] field) {
 
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.hdel(key, field);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        }finally{
            //返还到连接池
            close(jedis);
        }
    }
 
    /**
     * 存储REDIS队列 顺序存储
     * @param byte[] key reids键名
     * @param byte[] value 键值
     */
    publicstatic void lpush(byte[] key, byte[] value) {
 
        Jedis jedis = null;
        try{
 
            jedis = jedisPool.getResource();
            jedis.lpush(key, value);
 
        }catch(Exception e) {
 
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        }finally{
 
            //返还到连接池
            close(jedis);
 
        }
    }
 
    /**
     * 存储REDIS队列 反向存储
     * @param byte[] key reids键名
     * @param byte[] value 键值
     */
    publicstatic void rpush(byte[] key, byte[] value) {
 
        Jedis jedis = null;
        try{
 
            jedis = jedisPool.getResource();
            jedis.rpush(key, value);
 
        }catch(Exception e) {
 
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        }finally{
 
            //返还到连接池
            close(jedis);
 
        }
    }
 
    /**
     * 将列表 source 中的最后一个元素(尾元素)弹出,并返回给客户端
     * @param byte[] key reids键名
     * @param byte[] value 键值
     */
    publicstatic void rpoplpush(byte[] key, byte[] destination) {
 
        Jedis jedis = null;
        try{
 
            jedis = jedisPool.getResource();
            jedis.rpoplpush(key, destination);
 
        }catch(Exception e) {
 
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        }finally{
 
            //返还到连接池
            close(jedis);
 
        }
    }
 
    /**
     * 获取队列数据
     * @param byte[] key 键名
     * @return
     */
    publicstatic List<byte[]> lpopList(byte[] key) {
 
        List<byte[]> list = null;
        Jedis jedis = null;
        try{
 
            jedis = jedisPool.getResource();
            list = jedis.lrange(key, 0, -1);
 
        }catch(Exception e) {
 
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        }finally{
 
            //返还到连接池
            close(jedis);
 
        }
        returnlist;
    }
 
    /**
     * 获取队列数据
     * @param byte[] key 键名
     * @return
     */
    publicstatic byte[] rpop(byte[] key) {
 
        byte[] bytes = null;
        Jedis jedis = null;
        try{
 
            jedis = jedisPool.getResource();
            bytes = jedis.rpop(key);
 
        }catch(Exception e) {
 
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        }finally{
 
            //返还到连接池
            close(jedis);
 
        }
        returnbytes;
    }
 
    publicstatic void hmset(Object key, Map<string, string=""> hash) {
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.hmset(key.toString(), hash);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        }finally{
            //返还到连接池
            close(jedis);
 
        }
    }
 
    publicstatic void hmset(Object key, Map<string, string=""> hash, inttime) {
        Jedis jedis = null;
        try{
 
            jedis = jedisPool.getResource();
            jedis.hmset(key.toString(), hash);
            jedis.expire(key.toString(), time);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        }finally{
            //返还到连接池
            close(jedis);
 
        }
    }
 
    publicstatic List<string> hmget(Object key, String... fields) {
        List<string> result = null;
        Jedis jedis = null;
        try{
 
            jedis = jedisPool.getResource();
            result = jedis.hmget(key.toString(), fields);
 
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        }finally{
            //返还到连接池
            close(jedis);
 
        }
        returnresult;
    }
 
    publicstatic Set<string> hkeys(String key) {
        Set<string> result = null;
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            result = jedis.hkeys(key);
 
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        }finally{
            //返还到连接池
            close(jedis);
 
        }
        returnresult;
    }
 
    publicstatic List<byte[]> lrange(byte[] key, intfrom, intto) {
        List<byte[]> result = null;
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            result = jedis.lrange(key, from, to);
 
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        }finally{
            //返还到连接池
            close(jedis);
 
        }
        returnresult;
    }
 
    publicstatic Map<byte[],> hgetAll(byte[] key) {
        Map<byte[],> result = null;
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            result = jedis.hgetAll(key);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
 
        }finally{
            //返还到连接池
            close(jedis);
        }
        returnresult;
    }
 
    publicstatic void del(byte[] key) {
 
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.del(key);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        }finally{
            //返还到连接池
            close(jedis);
        }
    }
 
    publicstatic long llen(byte[] key) {
 
        longlen = 0;
        Jedis jedis = null;
        try{
            jedis = jedisPool.getResource();
            jedis.llen(key);
        }catch(Exception e) {
            //释放redis对象
            jedisPool.returnBrokenResource(jedis);
            e.printStackTrace();
        }finally{
            //返还到连接池
            close(jedis);
        }
        returnlen;
    }
 
}
</byte[],></byte[],></byte[]></byte[]></string></string></string></string></string,></string,></byte[]></byte[]>

Configuration主要用于读取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
packagecom.redis.util;
 
importjava.io.IOException;
importjava.io.InputStream;
importjava.util.Properties;
 
publicclass Configuration extendsProperties {
 
    privatestatic final long serialVersionUID = 50440463580273222L;
 
    privatestatic Configuration instance = null;
 
    publicstatic synchronized Configuration getInstance() {
        if(instance == null) {
            instance = newConfiguration();
        }
        returninstance;
    }
 
    publicString getProperty(String key, String defaultValue) {
        String val = getProperty(key);
        return(val == null|| val.isEmpty()) ? defaultValue : val;
    }
 
    publicString getString(String name, String defaultValue) {
        returnthis.getProperty(name, defaultValue);
    }
 
    publicint getInt(String name, intdefaultValue) {
        String val = this.getProperty(name);
        return(val == null|| val.isEmpty()) ? defaultValue : Integer.parseInt(val);
    }
 
    publiclong getLong(String name, longdefaultValue) {
        String val = this.getProperty(name);
        return(val == null|| val.isEmpty()) ? defaultValue : Integer.parseInt(val);
    }
 
    publicfloat getFloat(String name, floatdefaultValue) {
        String val = this.getProperty(name);
        return(val == null|| val.isEmpty()) ? defaultValue : Float.parseFloat(val);
    }
 
    publicdouble getDouble(String name, doubledefaultValue) {
        String val = this.getProperty(name);
        return(val == null|| val.isEmpty()) ? defaultValue : Double.parseDouble(val);
    }
 
    publicbyte getByte(String name, bytedefaultValue) {
        String val = this.getProperty(name);
        return(val == null|| val.isEmpty()) ? defaultValue : Byte.parseByte(val);
    }
 
    publicConfiguration() {
        InputStream in = ClassLoader.getSystemClassLoader().getResourceAsStream("config.xml");
        try{
            this.loadFromXML(in);
            in.close();
        }catch(IOException e) {
        }
    }
}


测试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
packagecom.quene.test;
 
importcom.bean.Message;
importcom.bean.util.ObjectUtil;
importcom.redis.util.JedisUtil;
 
publicclass TestRedisQuene {
    publicstatic byte[] redisKey = "key".getBytes();
    static{
        init();
    }
    publicstatic void main(String[] args) {
        pop();
    }
 
    privatestatic void pop() {
        byte[] bytes = JedisUtil.rpop(redisKey);
        Message msg = (Message) ObjectUtil.bytesToObject(bytes);
        if(msg != null){
            System.out.println(msg.getId()+"   "+msg.getContent());
        }
    }
 
    privatestatic void init() {
        Message msg1 = newMessage(1,"内容1");
        JedisUtil.lpush(redisKey, ObjectUtil.objectToBytes(msg1));
        Message msg2 = newMessage(2,"内容2");
        JedisUtil.lpush(redisKey, ObjectUtil.objectToBytes(msg2));
        Message msg3 = newMessage(3,"内容3");
        JedisUtil.lpush(redisKey, ObjectUtil.objectToBytes(msg3));
    }
 
}
测试结果如下:
?
1
1  内容1
?
1
2  内容2
?
1
3  内容3
0 0
原创粉丝点击