java访问redis工具jedis简介

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/liuxing9345/article/details/82428408

首先定义两个常量字段,分别表示主机和端口号:

public static final String HOST = "192.168.9.131";
public static final int PORT = 6379;

获得单一 jedis 对象操作 redis:

@Test
public void test01() throws Exception {
    // 1.获得连接对象
    Jedis jedis = new Jedis(HOST, PORT);

    // 2.获得数据
    String username = jedis.get("username");
    System.out.println(username);

    // 3.存储数据
    jedis.set("addr", "北京");
    System.out.println(jedis.get("addr"));
    jedis.set("jedis-key", "1234");

    jedis.close();
}

通过 jedis 的 pool 获得 jedis 连接对象:

@Test
public void test02() throws Exception {
    // 0.创建池子的配置对象
    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    poolConfig.setMaxIdle(30);  // 最大闲置个数
    poolConfig.setMinIdle(10);  // 最小闲置个数
    poolConfig.setMaxTotal(50); // 最大连接数

    // 1.创建一个 jedis 连接池
    JedisPool pool = new JedisPool(poolConfig, HOST, PORT);

    // 2.从池子中获取 jedis 连接资源
    Jedis jedis = pool.getResource();

    // 3.操作 redis
    jedis.set("xxx", "yyy");
    System.out.println(jedis.get("xxx"));

    // 4.释放资源
    jedis.close();
    pool.close();
}

通过 jedis 连接 redis 集群:

    @Test
    public void testCluster() throws Exception {
        // 1.创建 JedisCluster 对象,构造参数 Set 类型,集合中每个元素时 HostAndPort 类型
        Set<HostAndPort> nodes = new HashSet<HostAndPort>();
        nodes.add(new HostAndPort(HOST, 7001));
        nodes.add(new HostAndPort(HOST, 7002));
        nodes.add(new HostAndPort(HOST, 7003));
        nodes.add(new HostAndPort(HOST, 7004));
        nodes.add(new HostAndPort(HOST, 7005));
        nodes.add(new HostAndPort(HOST, 7006));
        JedisCluster jedisCluster = new JedisCluster(nodes);
        // 2.直接使用 JedisCluster 操作 redis,JedisCluster 对象自带连接池,并且是单例的
        jedisCluster.set("cluster-test", "hello jedis cluster");
        String string = jedisCluster.get("cluster-test");
        System.out.println(string);
        // 3.系统关闭前关闭 JedisCluster
        jedisCluster.close();
    }

猜你喜欢

转载自blog.csdn.net/liuxing9345/article/details/82428408