jedis 鏈接redis(單機):node
使用jedis如何操做redis,可是其實方法是跟redis的操做大部分是相對應的。redis
全部的redis命令都對應jedis的一個方法 服務器
一、在macen工程中引入jedis的jar包 測試
<dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> </dependency>
二、創建測試工程spa
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.點擊運行code
若報下面鏈接超時,則須關閉防火牆(命令 service iptables stop)對象
再次運行blog
每次鏈接須要建立一個鏈接、執行完後就關閉,很是浪費資源,因此使用jedispool(鏈接池)鏈接 ip
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(); }
進集羣服務器查看值