使用jedis操作redis

來源:互聯網
上載者:User

標籤:

首先來簡單介紹一下jedis,其實一句話就可以概括的,就是java操作redis的一種api。我們知道redis提供了基本上所有常用程式設計語言的clients,大家可以到http://redis.io/clients 上面去查看,包含C,C++,C#等等。

1、download jedis的源碼:https://github.com/xetorthio/jedis/releases/tag/jedis-2.1.0 ,jedis採用的是git託管的,這邊使用的是2.1.0版本;

2、解壓開啟可以看到,jedis採用的是maven構建工程的,所以我們的開發工具最好能支援maven工程,關於maven工程的支援,這邊就不介紹了,大家可以去網上尋找,或者查看本人寫的關於maven的博文,之所以要選擇maven工程呢,是為了更好的去查看jedis的源碼。

3、eclipse匯入jedis工程,在Package Exploer右鍵Import,選擇maven工程

點擊Finish即可完成匯入工作,工程結構如下:

4、完成基本串連操作

修改pom.xml檔案,將此處的localhost修改為自己的redis server IP 

<properties>    <redis-hosts>192.168.2.105:6379,192.168.2.105:6380</redis-hosts>  </properties>

建立RedisClient類:(本人習慣將常用的進行封裝)

package com.enson.redis.client;import com.enson.redis.common.Constant;import redis.clients.jedis.Jedis;public class RedisClient {    public static Jedis jedis = null;    public static Jedis getClient(){    if(jedis == null){      jedis = new Jedis(Constant.HOST, Constant.PORT);    }    return jedis;  }}

Constant類:

package com.enson.redis.common;public class Constant {  //redis主機IP地址  public static final String HOST = "192.168.2.105";  //redis主機連接埠  public static final Integer PORT = 6379;}


在src/test/java 下面建立一個JUnit Test Case:RedisTest

package test.enson.redis;import org.junit.AfterClass;import org.junit.BeforeClass;import org.junit.Test;import com.enson.redis.client.RedisClient;public class RedisTest {  @BeforeClass  public static void setUpBeforeClass() throws Exception {  }  @AfterClass  public static void tearDownAfterClass() throws Exception {  }  @Test  public void test() {    System.out.println(RedisClient.getClient().set("key","123456"));    System.out.println(RedisClient.getClient().get("key"));  }}

此時此刻,測試代碼已經寫好了, 開啟redis-server 
junit方式運行test方法:

 

使用jedis操作redis

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.