Redis系列-04客户端(Jedis)

152 阅读1分钟

Jedis是什么

image-20200604180042995

Jedis使用

maven依赖

<!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.3.0</version>
</dependency>

Jedis直连

image-20200604191029127

    // 1 生成jedis对象
    Jedis jedis = new Jedis("127.0.0.1",6379 );
    // 2 执行jedis命令
    jedis.hset("k1", "f1", "v1");
    jedis.hset("k1", "f2", "v2");
    // 3 返回执行结果
    Map<String, String> k1 = jedis.hgetAll("k1");
    k1.forEach((k, v) -> {
      System.out.println(k + " : " + v);
    });
    // 4 关闭jedis
    jedis.close();

Jedis连接池

image-20200604191233561

    GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
    JedisPool jedisPool = new JedisPool(poolConfig, "127.0.0.1",6379);
    
    Jedis jedis = null;
    try {
      // 1 从连接池中获取jedis对象
      jedis = jedisPool.getResource();
    } catch(Exception e) {
      // 2 执行jedis命令
      jedis.set("name", "hello");
      // 3 返回执行结果
      String name = jedis.get("name");
    } finally {
      if(jedis != null) {
        // 4 关闭连接
        jedis.close();
      }
    }

直连 VS 连接池

image-20200604191606050