黑猴子的家:Redis 之 jedis、jedisPool、jedisCluster

1、jedis 连接redis(单机)

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();
    }
}

2、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();
}

3、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();
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容