jedis、jedisPool、jedisCluster的使用方法

jedis 连接redis(单机):

    使用jedis如何操作redis,但是其实方法是跟redis的操作大部分是相对应的。

  所有的redis命令都对应jedis的一个方法 

    1、在maven工程中引入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连接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();
    }

进集群服务器查看值

JedisCluster设置密码、

1. 修改配置文件,通过requirePass指定密码

2. 通过JedisCluster构造方法指定密码

new JedisCluster(node, connectionTimeout, soTimeout, maxAttempts, password, poolConfig)
new JedisCluster(jedisClusterNode, connectionTimeout, soTimeout, maxAttempts, password, poolConfig)

 

 

 

 

 

 

 

 

 

 

 

 

 

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值