Java连接redis的使用示例

Java 连接 redis 的使用示例

         Redis 是开源的 key-value 存储工具,redis 通常用来存储结构化的数据,因为 redis 的 key 可以包含 String、hash、listset 和 sorted list。

         Redisserver 目前最稳定的版本是 2.8.9,可以到官网http://redis.io/download下载。根据机器的类型及位数下载对应的版本安装即可,reids 支持 linux 和 windows 操作系统。

         Redisclient 支持多种语言,包括:c、C++、C#、php、java、python、go 等语言,根据自己的开发语言,选择合适的 redis client 版本类型即可。我是使用 java 语言开发的,针对 java 语言,redis client 也提供了多种客户端支持,按照推荐类型依次是:Jedis、Redisson、JRedis、JDBC-Redis、RJC、redis-protocol、aredis、lettuce。前两种类型是比较推荐的,我们采用了 Redisson 类型版本作为 redisclient 的使用。

         Redisson 的源码工程所在位置:https://github.com/mrniko/redisson。这里有使用示例及一些介绍,这里不再详细的介绍。

 

 

Redis Java 客户端 jedis 工具类

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
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
 
import redis.clients.jedis.Builder;
import redis.clients.jedis.ShardedJedis;
import redis.clients.jedis.ShardedJedisPipeline;
import redis.clients.jedis.ShardedJedisPool;
import redis.clients.util.SafeEncoder;
 
/**
 * The RedisUtil represents
 * @version $Id$
 * @author fengjc
 */
public class RedisUtil {
 
    /**
     * 数据源
     */
    private ShardedJedisPool shardedJedisPool;
 
    /** ======================================Strings====================================== */
 
    /**
     * Set the string value as value of the key. The string can't be longer than
     * 1073741824 bytes (1 GB).
     * Time complexity: O(1)
     * @param key
     * @param value
     * @return Status code reply
     */
    public String setString(String key, String value) {
        ShardedJedis jedis = this.shardedJedisPool.getResource();
        String status = jedis.set(key, value);
        this.shardedJedisPool.returnResource(jedis);
        return status;
    }
 
    /**
     * Get the value of the specified key. If the key does not exist the special
     * value 'nil' is returned. If the value stored at key is not a string an
     * error is returned because GET can only handle string values.
     * Time complexity: O(1)
     * @param key
     * @return Bulk reply
     */
    public String getString(String key) {
        ShardedJedis jedis = this.shardedJedisPool.getResource();
        String value = jedis.get(key);
        this.shardedJedisPool.returnResource(jedis);
        return value;
    }
 
    /**
     * This Stirng的批量更新
     * @param pairs
     */
    public List<Object> batchSetString(final List<Pair<String, String>> pairs) {
        final ShardedJedis jedis = this.shardedJedisPool.getResource();
        List<Object> status = jedis.pipelined(new ShardedJedisPipeline() {
 
            @Override
            public void execute() {
                for (Pair<String, String> pair : pairs) {
                    set(pair.getKey(), pair.getValue());
                }
            }
        });
        this.shardedJedisPool.returnResource(jedis);
        return status;
    }
 
    /**
     * This String的批量获得
     * @param keys
     * @return
     */
    public List<String> batchGetString(final List<String> keys) {
        final ShardedJedis jedis = this.shardedJedisPool.getResource();
        List<Object> dataList = jedis.pipelined(new ShardedJedisPipeline() {
 
            @Override
            public void execute() {
                for (String key : keys) {
                    get(key);
                }
            }
        });
        this.shardedJedisPool.returnResource(jedis);
        List<String> rtnDataList = new ArrayList<String>();
        for (Object data : dataList) {
            rtnDataList.add(STRING.build(data));
        }
        return rtnDataList;
    }
 
    /** ======================================Hashes====================================== */
 
    /**
     * Set the specified hash field to the specified value.
     * If key does not exist, a new key holding a hash is created.
     * Time complexity: O(1)
     * @param key
     * @param field
     * @param value
     * @return If the field already exists, and the HSET just produced an update
     *         of the value, 0 is returned, otherwise if a new field is created
     *         1 is returned.
     */
    public long hashSet(String key, String field, String value) {
        ShardedJedis jedis = this.shardedJedisPool.getResource();
        long count = jedis.hset(key, field, value);
        this.shardedJedisPool.returnResource(jedis);
        return count;
    }
 
    /**
     * If key holds a hash, retrieve the value associated to the specified
     * field.
     * If the field is not found or the key does not exist, a special 'nil'
     * value is returned.
     * Time complexity:O(1)
     * @param key
     * @param field
     * @return Bulk reply
     */
    public String hashGet(String key, String field) {
        ShardedJedis jedis = this.shardedJedisPool.getResource();
        String value = jedis.hget(key, field);
        this.shardedJedisPool.returnResource(jedis);
        return value;
    }
 
    /**
     * Set the respective fields to the respective values. HMSET replaces old
     * values with new values.
     * If key does not exist, a new key holding a hash is created.
     * Time complexity: O(N) (with N being the number of fields)
     * @param key
     * @param hash
     * @return Return OK or Exception if hash is empty
     */
    public String hashMultipleSet(String key, Map<String, String> hash) {
        ShardedJedis jedis = this.shardedJedisPool.getResource();
        String status = jedis.hmset(key, hash);
        this.shardedJedisPool.returnResource(jedis);
        return status;
    }
 
    /**
     * Retrieve the values associated to the specified fields.
     * If some of the specified fields do not exist, nil values are returned.
     * Non existing keys are considered like empty hashes.
     * Time complexity: O(N) (with N being the number of fields)
     * @param key
     * @param fields
     * @return Multi Bulk Reply specifically a list of all the values associated
     *         with the specified fields, in the same order of the request.
     */
    public List<String> hashMultipleGet(String key, String... fields) {
        ShardedJedis jedis = this.shardedJedisPool.getResource();
        List<String> dataList = jedis.hmget(key, fields);
        this.shardedJedisPool.returnResource(jedis);
        return dataList;
    }
 
    /**
     * This 批量的HashMultipleSet
     * @param pairs
     * @return
     */
    public List<Object> batchHashMultipleSet(final List<Pair<String, Map<String, String>>> pairs) {
        final ShardedJedis jedis = this.shardedJedisPool.getResource();
        List<Object> status = jedis.pipelined(new ShardedJedisPipeline() {
 
            @Override
            public void execute() {
                for (Pair<String, Map<String, String>> pair : pairs) {
                    hmset(pair.getKey(), pair.getValue());
                }
            }
        });
        this.shardedJedisPool.returnResource(jedis);
        return status;
    }
 
    /**
     * This 批量的HashMultipleGet
     * @param pairs
     * @return
     */
    public List<List<String>> batchHashMultipleGet(final List<Pair<String, String[]>> pairs) {
        final ShardedJedis jedis = this.shardedJedisPool.getResource();
        List<Object> dataList = jedis.pipelined(new ShardedJedisPipeline() {
 
            @Override
            public void execute() {
                for (Pair<String, String[]> pair : pairs) {
                    hmget(pair.getKey(), pair.getValue());
                }
            }
        });
        this.shardedJedisPool.returnResource(jedis);
        List<List<String>> rtnDataList = new ArrayList<List<String>>();
        for (Object data : dataList) {
            rtnDataList.add(STRING_LIST.build(data));
        }
        return rtnDataList;
    }
 
    /**
     * Return all the fields and associated values in a hash.
     * Time complexity: O(N), where N is the total number of entries
     * @param key
     * @return All the fields and values contained into a hash.
     */
    public Map<String, String> hashGetAll(String key) {
        ShardedJedis jedis = this.shardedJedisPool.getResource();
        Map<String, String> hash = jedis.hgetAll(key);
        this.shardedJedisPool.returnResource(jedis);
        return hash;
    }
 
    /**
     * This 批量的hashMultipleGet
     * @param keys
     * @return
     */
    public List<Map<String, String>> batchHashGetAll(final List<String> keys) {
        final ShardedJedis jedis = this.shardedJedisPool.getResource();
        List<Object> dataList = jedis.pipelined(new ShardedJedisPipeline() {
 
            @Override
            public void execute() {
                for (String key : keys) {
                    hgetAll(key);
                }
            }
        });
        this.shardedJedisPool.returnResource(jedis);
        List<Map<String, String>> rtnDataList = new ArrayList<Map<String, String>>();
        for (Object data : dataList) {
            rtnDataList.add(STRING_MAP.build(data));
        }
        return rtnDataList;
    }
 
    /** ======================================Builder====================================== */
 
    public static final Builder<Double> DOUBLE = new Builder<Double>() {
 
        @Override
        public Double build(Object data) {
            return Double.valueOf(STRING.build(data));
        }
 
        @Override
        public String toString() {
            return "double";
        }
    };
 
    public static final Builder<Boolean> BOOLEAN = new Builder<Boolean>() {
 
        @Override
        public Boolean build(Object data) {
            return ((Long) data) == 1;
        }
 
        @Override
        public String toString() {
            return "boolean";
        }
    };
 
    public static final Builder<Long> LONG = new Builder<Long>() {
 
        @Override
        public Long build(Object data) {
            return (Long) data;
        }
 
        @Override
        public String toString() {
            return "long";
        }
 
    };
 
    public static final Builder<String> STRING = new Builder<String>() {
 
        @Override
        public String build(Object data) {
            return SafeEncoder.encode((byte[]) data);
        }
 
        @Override
        public String toString() {
            return "string";
        }
 
    };
 
    public static final Builder<List<String>> STRING_LIST = new Builder<List<String>>() {
 
        @Override
        @SuppressWarnings("unchecked")
        public List<String> build(Object data) {
            if (null == data) {
                return null;
            }
            List<byte[]> l = (List<byte[]>) data;
            final ArrayList<String> result = new ArrayList<String>(l.size());
            for (final byte[] barray : l) {
                if (barray == null) {
                    result.add(null);
                } else {
                    result.add(SafeEncoder.encode(barray));
                }
            }
            return result;
        }
 
        @Override
        public String toString() {
            return "List<String>";
        }
 
    };
 
    public static final Builder<Map<String, String>> STRING_MAP = new Builder<Map<String, String>>() {
 
        @Override
        @SuppressWarnings("unchecked")
        public Map<String, String> build(Object data) {
            final List<byte[]> flatHash = (List<byte[]>) data;
            final Map<String, String> hash = new HashMap<String, String>();
            final Iterator<byte[]> iterator = flatHash.iterator();
            while (iterator.hasNext()) {
                hash.put(SafeEncoder.encode(iterator.next()), SafeEncoder.encode(iterator.next()));
            }
 
            return hash;
        }
 
        @Override
        public String toString() {
            return "Map<String, String>";
        }
 
    };
 
    public static final Builder<Set<String>> STRING_SET = new Builder<Set<String>>() {
 
        @Override
        @SuppressWarnings("unchecked")
        public Set<String> build(Object data) {
            if (null == data) {
                return null;
            }
            List<byte[]> l = (List<byte[]>) data;
            final Set<String> result = new HashSet<String>(l.size());
            for (final byte[] barray : l) {
                if (barray == null) {
                    result.add(null);
                } else {
                    result.add(SafeEncoder.encode(barray));
                }
            }
            return result;
        }
 
        @Override
        public String toString() {
            return "Set<String>";
        }
 
    };
 
    public static final Builder<Set<String>> STRING_ZSET = new Builder<Set<String>>() {
 
        @Override
        @SuppressWarnings("unchecked")
        public Set<String> build(Object data) {
            if (null == data) {
                return null;
            }
            List<byte[]> l = (List<byte[]>) data;
            final Set<String> result = new LinkedHashSet<String>(l.size());
            for (final byte[] barray : l) {
                if (barray == null) {
                    result.add(null);
                } else {
                    result.add(SafeEncoder.encode(barray));
                }
            }
            return result;
        }
 
        @Override
        public String toString() {
            return "ZSet<String>";
        }
 
    };
 
    /** ======================================Other====================================== */
 
    public void setShardedJedisPool(ShardedJedisPool shardedJedisPool) {
        this.shardedJedisPool = shardedJedisPool;
    }
 
    /**
     * This 构造Pair
     * @param key
     * @param value
     * @return
     */
    public <K, V> Pair<K, V> makePair(K key, V value) {
        return new Pair<K, V>(key, value);
    }
 
    /**
     * The Pair represents 键值对
     * @version $Id$
     * @author fengjc
     * @param <K>
     * @param <V>
     */
    public class Pair<K, V> {
 
        private K key;
        private V value;
 
        public Pair(K key, V value) {
            this.key = key;
            this.value = value;
        }
 
        public K getKey() {
            return this.key;
        }
 
        public void setKey(K key) {
            this.key = key;
        }
 
        public V getValue() {
            return this.value;
        }
 
        public void setValue(V value) {
            this.value = value;
        }
 
    }
}

 

 

 

 

原文参考:http://blog.csdn.net/wgw335363240/article/details/24471311