Java使用Jedis操作Redis服務器的實例代碼
這幾天Java項目中需要用到Redis,于是學習了一下使用Jedis來操作Redis服務器的相關知識,下面為具體的配置和代碼。
1、Maven中配置Jedis
在maven項目的pom.xml中添加依賴
<dependencies> <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>2.9.0</version> <type>jar</type> <scope>compile</scope> </dependency> </dependencies>
2、簡單應用
Jedis jedis = new Jedis("localhost");
jedis.set("foo", "bar");
String value = jedis.get("foo");
3、JedisPool的實現(xiàn)
創(chuàng)建Jedis連接池:
JedisPoolConfig config= new JedisPoolConfig();// Jedis池配置文件 config.setMaxTotal(1024); // 最大連接實例數(shù) config.setMaxIdle(200); // 最大閑置實例數(shù) config.setMaxWaitMillis(15000); // 等待可用連接的最大時間 config.setTestOnBorrow(true); // JedisPool pool = new JedisPool(config,ADDR,PORT,TIMEOUT,AUTH); // 創(chuàng)建一個Jedis連接池
從連接池中取出實例數(shù):
Jedis jedis = pool.getResource(); // 取出實例
jedis.set("foo","bar");
jedis.close(); // 歸還實例資源給連接池
4、使用pipeline批量操作
由于Redis是單線程,因此上述對redis的操作模式均為:請求-響應,請求響應….。下一次請求必須等上一次請求響應回來之后才可以。在Jedis中使用管道可以改變這種模式,客戶算一次發(fā)送多個命令,無需等待服務器的返回,即請求,請求,請求,響應,響應,響應這種模式。這樣一來大大減小了影響性能的關鍵因素:網(wǎng)絡返回時間。
具體操作如下:
Jedis jedis = new Jedis("localhost",6379,15000);
Pipeline pip = jedis.pipelined();
Map<String,String> mp = new HashMap<String, String>();
long start = System.currentTimeMillis();
for (int i = 0 ; i < 10000 ; i++){
mp.clear();
mp.put("k"+i,"v"+i);
pip.hmset("keys"+i,mp);
}
簡單的測試一下,運行10000個數(shù)據(jù)的存儲花費93ms左右的時間。而采用請求-響應,請求-響應的模式,操作如下:
Jedis jedis = new Jedis("localhost",6379,15000);
Map<String,String> mp = new HashMap<String, String>();
long start = System.currentTimeMillis();
for (int i = 0 ; i < 10000 ; i++){
mp.clear();
mp.put("k"+i,"v"+i);
jedis.hmset("keys"+i,mp);
}
測試時間826ms??梢姶罅康臅r間均花費在網(wǎng)絡交互上,Redis本身的處理能力還是很強的。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
基于UncategorizedSQLException異常處理方案
這篇文章主要介紹了基于UncategorizedSQLException異常處理方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
SpringBoot里使用Servlet進行請求的實現(xiàn)示例
這篇文章主要介紹了SpringBoot里使用Servlet進行請求的實現(xiàn)示例,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2021-01-01
springboot+thymeleaf找不到視圖的解決方案
這篇文章主要介紹了springboot+thymeleaf找不到視圖的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-06-06

