jedis、jedisPool、jedisCluster的使用方法


jedis 連接redis(單機):

    使用jedis如何操作redis,但是其實方法是跟redis的操作大部分是相對應的。

  所有的redis命令都對應jedis的一個方法 

    1、在macen工程中引入jedis的jar包     

       <dependency>
          <groupId>redis.clients</groupId>
          <artifactId>jedis</artifactId>
       </dependency>

     2、建立測試工程

復制代碼
public class JedisTest {

    @Test
    public void testJedis()throws Exception{
        Jedis jedis = new Jedis("192.168.241.133",6379);
        jedis.set("test", "my forst jedis");
        String str = jedis.get("test");
        System.out.println(str);
        jedis.close();
    }
}
復制代碼

      3.點擊運行

         若報下面連接超時,則須關閉防火牆(命令 service iptables stop)

              

                再次運行

               

               每次連接需要創建一個連接、執行完后就關閉,非常浪費資源,所以使用jedispool(連接池)連接 

jedisPool連接redis (單機)        

復制代碼
@Test
    public void testJedisPool()throws Exception{
        //創建連接池對象
        JedisPool jedispool = new JedisPool("192.168.241.133",6379);
        //從連接池中獲取一個連接
        Jedis  jedis = jedispool.getResource(); 
        //使用jedis操作redis
        jedis.set("test", "my forst jedis");
        String str = jedis.get("test");
        System.out.println(str);
        //使用完畢 ,關閉連接,連接池回收資源
        jedis.close();
        //關閉連接池
        jedispool.close();
    }
復制代碼

jedisCluster連接redis(集群)

      jedisCluster專門用來連接redis集群 

      jedisCluster在單例存在的

復制代碼
@Test
    public void testJedisCluster()throws Exception{
        //創建jedisCluster對象,有一個參數 nodes是Set類型,Set包含若干個HostAndPort對象
        Set<HostAndPort> nodes = new HashSet<>();
        nodes.add(new HostAndPort("192.168.241.133",7001));
        nodes.add(new HostAndPort("192.168.241.133",7002));
        nodes.add(new HostAndPort("192.168.241.133",7003));
        nodes.add(new HostAndPort("192.168.241.133",7004));
        nodes.add(new HostAndPort("192.168.241.133",7005));
        nodes.add(new HostAndPort("192.168.241.133",7006));
        JedisCluster jedisCluster = new JedisCluster(nodes);
        //使用jedisCluster操作redis
        jedisCluster.set("test", "my forst jedis");
        String str = jedisCluster.get("test");
        System.out.println(str);
        //關閉連接池
        jedisCluster.close();
    }
復制代碼

      進集群服務器查看值

       


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM