redis在Java開發中的串連使用

來源:互聯網
上載者:User

標籤:資料   地址   set   key   jar   trace   demo   引入   demo1   

此貼僅作為本人redis入門學習的筆記記錄。
redis是什麼呢?簡單直接點說,就是一個Key-Value類型的資料庫。關於它的優缺點,本人暫時沒有深入學習和瞭解,不敢妄言。

jedis:redis官方首選的Java用戶端開發包。

因為redis是安裝在Linux環境下的,所以在使用之前,我們需要做如下準備工作:
1、裝虛擬機器
2、搭建Linux環境
3、安裝redis
4、在Java項目中引入jedis的jar包,並添加到項目的構建路徑中

準備工作做好之後,就可以在程式開發中使用redis了。和其他關係型資料庫一樣,redis的使用也可以分為以下4個步驟:
1、建立串連
2、儲存資料
3、擷取資料
4、釋放串連

和jdbc類似,jedis也提供兩種串連模式:單例模式、串連池模式,程式碼範例如下:

public class JedisDemo {

@Test
/**
* 單例模式串連
*/
public void demo1(){
//1、設定ip地址和連接埠
Jedis jedis = new Jedis("192.168.130.1",6379);
//2、儲存資料
jedis.set("name1","java");
//3、讀取資料
String value1 = jedis.get("name1");
System.out.println(value1);
//4、釋放資源
jedis.close();
}

@Test
/**
* 串連池模式串連
*/
public void demo2(){
//1、獲得串連池的設定物件
JedisPoolConfig config = new JedisPoolConfig();
//2、設定最大串連數
config.setMaxTotal(30);
//3、設定最大空閑串連數
config.setMaxIdle(10);
//4、獲得串連池
JedisPool jedisPool = new JedisPool(config,"192.168.130.1",6379);
//5、獲得核心對象
Jedis jedis = null;
try{
//6、通過串連池來獲得連結
jedis = jedisPool.getResource();
//7、儲存資料
jedis.set("name2","python");
//8、擷取資料
String value2 = jedis.get("name2");
System.out.println(value2);
} catch(Exception e){
e.printStackTrace();
} finally{
//9、釋放資源
if(jedis != null){
jedis.close();;
}
if(jedisPool != null){
jedisPool.close();
}
}
}
  
  @Test
public static void main(String[] args) {
JedisDemo jedisDemo = new JedisDemo();
jedisDemo.demo1();
jedisDemo.demo2();
}
}

redis在Java開發中的串連使用

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.