1、Jedis

1、如何使用

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>2.9.0</version>
</dependency>
@Test
public void testJedis() {
    // 1.连接 redis, 默认就是 localhost:6379
    Jedis jedis = new Jedis("127.0.0.1", 6379);
    // 2.操作 redis
    jedis.set("name", "zzw");
    String name = jedis.get("name");
    System.out.println(name);
    // 3.关闭连接
    jedis.close();
}

2、读写 Redis 数据

@Test
public void testList() {
    // 1.连接 redis
    Jedis jedis = new Jedis("127.0.0.1", 6379);
    // 2.操作 redis
    jedis.lpush("list1", "a", "b", "c");
    jedis.rpush("list1", "x", "y", "z");
    List<String> list1 = jedis.lrange("list1", 0, -1);
    list1.forEach(System.out::println);
    // 3.关闭连接
    jedis.close();
}
@Test
public void testHash() {
    // 1.连接 redis
    Jedis jedis = new Jedis("127.0.0.1", 6379);
    // 2.操作 redis
    jedis.hset("hash1", "name", "zhangsan");
    jedis.hset("hash1", "age", "18");
    Map<String, String> map = jedis.hgetAll("hash1");
    map.forEach((key, value) -> System.out.println(key + ": " + value));
    // 3.关闭连接
    jedis.close();
}

3、Jedis 简易工具类开发

# redis.properties
redis.host=127.0.0.1
redis.port=6379
redis.maxTotal=30
redis.maxIdle=10
import java.util.ResourceBundle; // 资源包

public class JedisUtil {

    private static final JedisPool jp; // 连接池
    private static final String host;
    private static final int port;
    private static final int maxTotal;
    private static final int maxIdle;

    static {
        ResourceBundle rb = ResourceBundle.getBundle("redis"); // 资源包
        host = rb.getString("redis.host");
        port = Integer.parseInt(rb.getString("redis.port"));
        maxTotal = Integer.parseInt(rb.getString("redis.maxTotal"));
        maxIdle = Integer.parseInt(rb.getString("redis.maxIdle"));

        JedisPoolConfig config = new JedisPoolConfig(); // 连接池配置
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);

        jp = new JedisPool(config, host, port);
    }

    public static Jedis getJedis() {
        return jp.getResource();
    }
}
posted @ 2023-10-26 23:38  lidongdongdong~  阅读(10)  评论(0)    收藏  举报