Jedis快速入门

2024-01-07 18:12:51

1.Jedis使用的基本步骤:

1.1 引入依赖
<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.7.0</version>
</dependency>
1.2 创建Jedis对象,建立连接
void setUp() {
    jedis = new Jedis("255.255.255.255", 6379);
    jedis.auth("123456");
    jedis.select(0);
}
1.3 使用Jedis,方法名与Redis命令一致
@Test
public void demo1() {
    String result = jedis.set("name", "虎哥");
    System.out.println("result=" + result);
    String name = jedis.get("name");
    System.out.println("name=" + name);
}

@Test
public void demo2() {
    jedis.hset("user:1", "name", "Jack");
    jedis.hset("user:1", "age", "21");

    Map<String, String> map = jedis.hgetAll("user:1");

    System.out.println(map);

}
1.4 释放资源
void tearDown() {
    if (jedis != null) {
        jedis.close();
    }
}
1.5 完整代码
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import redis.clients.jedis.Jedis;

import java.util.Map;

public class JedisTest {

    private Jedis jedis;

    @BeforeEach
    void setUp() {
        jedis = new Jedis("255.255.255.255", 6379);
        jedis.auth("123456");
        jedis.select(0);
    }

    @AfterEach
    void tearDown() {
        if (jedis != null) {
            jedis.close();
        }
    }

    @Test
    public void demo1() {
        String result = jedis.set("name", "虎哥");
        System.out.println("result=" + result);
        String name = jedis.get("name");
        System.out.println("name=" + name);
    }

    @Test
    public void demo2() {
        jedis.hset("user:1", "name", "Jack");
        jedis.hset("user:1", "age", "21");

        Map<String, String> map = jedis.hgetAll("user:1");

        System.out.println(map);

    }
}
1.6 可视化工具查看

在这里插入图片描述

工具下载地址:https://github.com/lework/RedisDesktopManager-Windows/releases

2.Jedis的连接池

2.1 代码
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class JedisConnectionFactory {
    private static final JedisPool jedisPool;

    static {
        //配置连接池
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        //最大连接
        poolConfig.setMaxTotal(8);
        //最大空闲连接
        poolConfig.setMaxIdle(8);
        //最小空闲连接
        poolConfig.setMinIdle(8);
        //设置最长等待时间,单位ms
        poolConfig.setMaxWaitMillis(1000);
        //创建连接池对象
        jedisPool = new JedisPool(poolConfig, "255.255.255.255", 6379, 1000, "123456");
    }

    //获取Jedis对象
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }
}
2.2 获取连接修改如下
void setUp() {
    //直接获取连接
    //jedis = new Jedis("255.255.255.255", 6379);
    //jedis.auth("123456");
    //连接池获取连接
    jedis = JedisConnectionFactory.getJedis();
    jedis.select(0);
}

文章来源:https://blog.csdn.net/qq_42236791/article/details/135427557
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。