Java基礎知識整理之操做Redis(二)

Java操做Redis之鏈接以及簡單操做

1.下載對應的驅動包

下載 jedis.jarhttps://mvnrepository.com/art...java

2.建立一個鏈接類 RedisStudy.java

2.1 鏈接 Redis

String host = "127.0.0.1";    //主機地址
    int port = 6379;    //端口號
    String pwd = "foobared";    //登陸密碼
    try {
            Jedis jedis = new Jedis(host, port); // 鏈接redis服務器
            String auth = jedis.auth(pwd); // 權限認證
            //鏈接 完成會返回 ok
            System.out.println("connet the redis:"+auth);
        } catch (Exception e) {
            System.out.println("緩存連接錯誤");
        }

2.2 查詢全部 Redis 中的 Key

public void findAllKeys(){
        // jedis.keys("*") 查詢全部的key * 爲通配符
        Set<String> set = jedis.keys("*");
        for (String str : set) {
              System.out.println(str);
        }
    }

2.3 清除全部的 Redis 中的 Key

public void ClearDB() {
        // flushDB 是清除全部的 key 的命令
        String str = jedis.flushDB();
        //若是清理完成,會返回 ok
        System.out.println("flush all Keys:" + str);
    }

3.完整的代碼

import java.util.Set;
import redis.clients.jedis.Jedis;

public class RedisStudy {

    //聲明 redis 對象
    private static Jedis jedis;

    private String host = "127.0.0.1";    //測試地址
    private int port = 6379;    //端口
    private String pwd = "foobared";    //密碼
    
    /**
     * 鏈接redis
     */
    public void getJedis() {
        try {
            jedis = new Jedis(host, port); // 鏈接redis服務器
            String auth = jedis.auth(pwd); // 權限認證
            
            System.out.println("connet the redis:"+auth);
        } catch (Exception e) {
            System.out.println("緩存連接錯誤");
        }
    }
    
    /**
     * 清除全部的緩存
     */
    public void ClearDB() {
        String str = jedis.flushDB();
        System.out.println("flush all Keys:" + str);
    }
    
    /**
     * 找到全部的KEY
     */
    public void findAllKeys(){
        Set<String> set = jedis.keys("*");
        for (String str : set) {
              System.out.println(str);
        }
    }
    
    public static void main(String[] args) {
        //聲明當前類
        RedisStudy rs = new RedisStudy();
        //鏈接
        rs.getJedis();
    }
}

Java基礎知識整理之操做Redis(一)
Java基礎知識整理之操做Redis(三)redis

相關文章
相關標籤/搜索