Java基础知识整理之操作Redis(二)

发布时间:2019-11-17 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Java基础知识整理之操作Redis(二)脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

Java操作redis之连接以及简单操作

1.下载对应的驱动包

下载 jedis.jarhttps://mvnrepository.com/art...

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(三)

脚本宝典总结

以上是脚本宝典为你收集整理的Java基础知识整理之操作Redis(二)全部内容,希望文章能够帮你解决Java基础知识整理之操作Redis(二)所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。