本文實例講述了Java操作redis實現增刪查改功能的方法。分享給大家供大家參考,具體如下:
首先,我們需要在windows下配置一個redis環境,具體配置教程請看:http://m.ythuaji.com.cn/article/24642.html
然后需要導入:jedis-2.7.3.jar這個包,看如下代碼:
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
|
package redis.main; import redis.clients.jedis.Jedis; import redis.clients.jedis.JedisPool; import redis.clients.jedis.JedisPoolConfig; public final class RedisPool { //Redis服務器IP private static String ADDR = "127.0.0.1" ; //Redis的端口號 private static int PORT = 6379 ; //訪問密碼 private static String AUTH = "123456" ; //可用連接實例的最大數目,默認值為8; //如果賦值為-1,則表示不限制;如果pool已經分配了maxActive個jedis實例,則此時pool的狀態為exhausted(耗盡)。 private static int MAX_ACTIVE = 1024 ; //控制一個pool最多有多少個狀態為idle(空閑的)的jedis實例,默認值也是8。 private static int MAX_IDLE = 200 ; //等待可用連接的最大時間,單位毫秒,默認值為-1,表示永不超時。如果超過等待時間,則直接拋出JedisConnectionException; private static int MAX_WAIT = 10000 ; private static int TIMEOUT = 10000 ; //在borrow一個jedis實例時,是否提前進行validate操作;如果為true,則得到的jedis實例均是可用的; private static boolean TEST_ON_BORROW = true ; private static JedisPool jedisPool = null ; /** * 初始化Redis連接池 */ static { try { JedisPoolConfig config = new JedisPoolConfig(); //config.setMaxActive(MAX_ACTIVE); config.setMaxTotal(MAX_ACTIVE); config.setMaxIdle(MAX_IDLE); config.setMaxWaitMillis(MAX_WAIT); config.setTestOnBorrow(TEST_ON_BORROW); jedisPool = new JedisPool(config, ADDR, PORT, TIMEOUT, AUTH); } catch (Exception e) { e.printStackTrace(); } } /** * 獲取Jedis實例 * @return */ public synchronized static Jedis getJedis() { try { if (jedisPool != null ) { Jedis resource = jedisPool.getResource(); return resource; } else { return null ; } } catch (Exception e) { e.printStackTrace(); return null ; } } /** * 釋放jedis資源 * @param jedis */ public static void returnResource( final Jedis jedis) { if (jedis != null ) { jedisPool.close(); } } } |
下面是main函數:
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 redis.main; import java.util.Set; import redis.clients.jedis.Jedis; /** * Hello world! * */ public class App { public static void main( String[] args ) { insert( "username" , "xiaoming1" ); System.out.println(get( "username" )); delete( "username" ); System.out.println(get( "username" )); } static void insert(String key, String value){ Jedis jedis = RedisPool.getJedis(); jedis.set(key, value); } static void delete(String key){ Jedis jedis = RedisPool.getJedis(); jedis.del(key); } static String get(String key){ Jedis jedis = RedisPool.getJedis(); return jedis.get(key); } } |
附:完整實例代碼點擊此處本站下載。
希望本文所述對大家java程序設計有所幫助。
原文鏈接:http://blog.csdn.net/zwc2xm/article/details/72870119