本文實例為大家分享了jedis操作redis數(shù)據(jù)庫的具體代碼,供大家參考,具體內(nèi)容如下
關(guān)于nosql的介紹不寫了,直接上代碼
第一步導(dǎo)包,不多講
基本操作:
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
|
package demo; import org.junit.test; import redis.clients.jedis.jedis; import redis.clients.jedis.jedispool; import redis.clients.jedis.jedispoolconfig; public class demo { // 通過java程序訪問redis數(shù)據(jù)庫 @test public void test1() { // 獲得連接對象 jedis jedis = new jedis( "localhost" , 6379 ); // 存儲、獲得數(shù)據(jù) jedis.set( "username" , "yiqing" ); string username = jedis.get( "username" ); system.out.println(username); } // jedis連接池獲得jedis連接對象 @test public void test2() { // 配置并創(chuàng)建redis連接池 jedispoolconfig poolconfig = new jedispoolconfig(); // 最大(小)閑置個數(shù) poolconfig.setmaxidle( 30 ); poolconfig.setminidle( 10 ); // 最大連接數(shù) poolconfig.setmaxtotal( 50 ); jedispool pool = new jedispool(poolconfig, "localhost" , 6379 ); // 獲取資源 jedis jedis = pool.getresource(); jedis.set( "username" , "yiqing" ); string username = jedis.get( "username" ); system.out.println(username); // 關(guān)閉資源 jedis.close(); // 開發(fā)中不會關(guān)閉連接池 // pool.close(); } } |
注意:如果運(yùn)行失敗,那么原因只有一條:沒有打開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
|
package demo; import java.io.ioexception; import java.io.inputstream; import java.util.properties; import redis.clients.jedis.jedis; import redis.clients.jedis.jedispool; import redis.clients.jedis.jedispoolconfig; public class jedispoolutils { private static jedispool pool = null ; static { // 加載配置文件 inputstream in = jedispoolutils. class .getclassloader().getresourceasstream( "redis.properties" ); properties pro = new properties(); try { pro.load(in); } catch (ioexception e) { e.printstacktrace(); } // 獲得池子對象 jedispoolconfig poolconfig = new jedispoolconfig(); poolconfig.setmaxidle(integer.parseint(pro.get( "redis.maxidle" ).tostring())); // 最大閑置個數(shù) poolconfig.setminidle(integer.parseint(pro.get( "redis.minidle" ).tostring())); // 最小閑置個數(shù) poolconfig.setmaxtotal(integer.parseint(pro.get( "redis.maxtotal" ).tostring())); // 最大連接數(shù) pool = new jedispool(poolconfig, pro.getproperty( "redis.url" ), integer.parseint(pro.get( "redis.port" ).tostring())); } // 獲得jedis資源 public static jedis getjedis() { return pool.getresource(); } } |
在src下新建一個文件:redis.properties:
1
2
3
4
5
|
redis.maxidle= 30 redis.minidle= 10 redis.maxtotal= 100 redis.url=localhost redis.port= 6379 |
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://www.cnblogs.com/xuyiqing/archive/2018/04/16/8850001.html