在Java中使用Redis

 

java 使用 jedis 操作 redis。

名字很好记,redis 的 r 换成 j,j 即 java。

 

redis-server 要做到:

  • bind 绑定机器的实际 ip
  • 防火墙开放对应端口

 

 


 

 

Jedis 的使用

1、添加 jedis 依赖

需要 2 个 jar 包:jedis.jar、commons-pool2.jar。

jedis 使用 apache 的线程池,所以需要添加 commons-pool2.jar。

 

使用 maven,添加 jedis 时会自动包含 commons-pool2。

github 上只有源码,如果要下载 jar 包,可以到 Maven Repository 下载。

 

 

2、使用示例

        Jedis jedis=new Jedis("192.168.1.9",6379);
        // jedis.auth("abcd");  //如果需要密码
        //jedis.select(0);  //选择数据库,下标指定,默认使用 db0
    <span style="color: rgba(0, 0, 255, 1)">if</span> (jedis.ping().equals("PONG")){  <span style="color: rgba(0, 128, 0, 1)">//链路通畅</span>
        jedis.set("name","chy"<span style="color: rgba(0, 0, 0, 1)">);
        System.out.println(jedis.get(</span>"name"<span style="color: rgba(0, 0, 0, 1)">));
    }
    </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">{
        System.out.println(</span>"无法连接redis服务器"<span style="color: rgba(0, 0, 0, 1)">);
    }

    jedis.close();
    </span></pre>

 

 

        Jedis jedis=new Jedis("192.168.1.9",6379);
    </span><span style="color: rgba(0, 0, 255, 1)">if</span> (jedis.ping().equals("PONG")){  <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">连接成功</span>
        jedis.zadd("users", 1223, "zhangsan"<span style="color: rgba(0, 0, 0, 1)">);
        jedis.zadd(</span>"users", 2568, "lisi"<span style="color: rgba(0, 0, 0, 1)">);
        jedis.zadd(</span>"users", 1379, "wangwu"<span style="color: rgba(0, 0, 0, 1)">);

        </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">迭代</span>
        Set&lt;Tuple&gt; users = jedis.zrangeWithScores("users", 0, -1<span style="color: rgba(0, 0, 0, 1)">);  //[0,-1]
        </span><span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> (Tuple user:users){
            String name </span>= user.getElement(); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取元素值</span>
            <span style="color: rgba(0, 0, 255, 1)">double</span> score = user.getScore(); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取分数</span>
            System.out.println(name+"的积分是:"+<span style="color: rgba(0, 0, 0, 1)">score);
        }
    }
    </span><span style="color: rgba(0, 0, 255, 1)">else</span><span style="color: rgba(0, 0, 0, 1)">{
        System.out.println(</span>"无法连接redis服务器"<span style="color: rgba(0, 0, 0, 1)">);
    }

    jedis.close();</span></pre>

 

 

 


 

 

 

Jedis 类的常用方法

1、构造方法

  • Jedis(String  host, int port)    // 指定 redis 服务器主机地址、端口号,host 可以是 ip 或者域名。参数均可选,缺省时默认为 127.0.0.1、6379
  • Jedis(String  host,int port, int timeout, boolean  ssl)  // 连接超时时间、是否使用安全连接。参数都可选。

 

 

2、连接

  • auth(String password)   // 验证密码
  • ping()    // 是否能 ping 通,能 ping 通则返回 String 类型的 PONG。
  • connect()   // 连接 redis-server。这个很少用,因为进行读写操作时会检测是否已连接,没连接会自动连接
  • close()   // 关闭连接并释放资源
  • shutdown()   // 关闭 redis-server

 

 

3、redis-server 的配置项

  • configGet(String param)  // 获取 redis-server 配置的某个参数值
  • configSet(String param, String value)  // 设置 redis-server 的一个配置项
  • configRewrite()    // 同步到配置文件中,永久有效。若不同步,则重启 redis-server 失效。

 

 

4、数据库

  • select(index  db)    // 选择要使用的数据库,默认使用 db0
  • flushDB()    // 清空当前数据库
  • flushAll()   // 清空所有数据库
  • save()   // 同步到硬盘
  • bgsave()   // 后台同步

 

 

 

5、key

  • set(String key,String value)    // 如果 key 已存在,会覆盖
  • setnx(String  key, String value)    //key 不存在时才设置,若 key 已存在,则不进行任何操作
  • mset(String key1,String value2,String  key2, String value2, .....)    // 同时设置多个键值对
  • msetnx(String key1,String value2,String  key2, String value2, .....)    //key 不存在时才设置

 

  • expire(String key, int seconds)   // 设置过期时间
  • setex(String key,int seconds, String value)   // 设置键值对、并指定过期时间,默认永不过期

 

  • get(String key)    // 返回 String 类型的 value
  • mget(String key1,String key2, .....)   // 同时获取多个 value,返回值是 List<String>

 

  • exists(String key)   // 检测某个 key 是否存在
  • rename(String oldKey,String newKey)    // 重命名 key
  • type(String key)    // 获取 value 的类型,string、hash、list、set、sorted set。
  • del(String key1, String key2, ....)    // 删除一个或多个键值对

 

  • incr(String key)    // 值自增,+1,返回操作后的值,long 型
  • incrBy(String  key, long increment)   // 指定 int 型增量,返回 long
  • incrByFloat(String key,double increment)    // 指定 double 型增量,返回 double。方法名中的 float 表示浮点数,并不限于单精度

 

  • decr(String key)   // 值自减
  • decrBy(String key,long  decrement)  // 原值减去 decrement,decrement 要指定为正数

没有 decrByFloat()方法,可以用 incrByFloat(),增量指定为负数即可。

 

 

 

6、hash

  • hset(String key, String field, String value)    // 设置单个字段
  • hsetnx(String key,  String field,  String value)  
  • hset(String   key, Map<String ,String>  map)  // 把 map 中的字段都添加进来

 

  • hget(String key , String field)
  • hmget(String key,  String field1, String field2,  ....)    // 获取多个字段的值,返回 List<String>
  • hgetAll(String  key)    // 获取所有的字段,返回 Map<String , String >

 

  • hexists(String key, String  field)   // 某个字段是否存在
  • hdel(String  key, String  field)    // 删除某个字段

 

  • hlen(String key)   // 返回该 hash 表中字段数,返回值是 Long 型
  • hkeys(String key)   // 获取所有的字段名,返回值是 Set<String>
  • hvals(String  key)   // 获取所有的字段值,返回值是 List<String>

 

  • hincrBy(String  key, String  field, long  increment)   // 返回操作后的数值,long 型
  • hincrByFloat(String key, String field , double  increment)   //double

没有 hdecrXxx() 方法,将上面的增量写成负数即可。

  

 

 

7、list

  • lpush(String  key, String element1, String  element2, .....)     // 在列表头插入一个或多个元素
  • lpushx(String key, String element1, String element2 ,.....)    //key 存在才插入,若 key 不存在,不进行任何操作
  • lpop(String key)   // 弹出列表的第一个元素。弹出是指删除并返回。

 

  • rpush(String key, String element1, String element2, ....)   // 在列表尾插入一个或多个元素
  • rpushx(String key, String element1, String element2, ....) 
  • rpop(String key)   // 弹出列表的最后一个元素

 

  • lindex(String key, long index)   // 返回指定位置上的元素
  • linsert(String key,ListPosition  position,,String element1, String element2)   // 在 element1 的前面 | 后面插入 element2。第二个参数是枚举类型,可用的值:ListPosition.BEFORE,ListPosition.AFTER

 

  • llen(String key)    // 元素个数,long
  • lrange(String key, long  startIndex, long  endIndex)   // 返回 [startIndex, endIndex] 上的所有元素,List<String>

 

  • lset(String key, long index, String element)   // 修改该位置上的值,index 上要已有元素。
  • lrem(String key, long count, String element)   // 从列表中移除 count 个值是 value 的元素,count 为正表示从前往后搜索,为负表示从后往前搜索
  • ltrim(String key, long startIndex, long  endIndex)   // 修剪列表,只保留 [startIndex, endIndex] 上的元素,其余删除。返回 String 类型的操作结果,“OK”表示操作成功。

 

 

 

8、set

  • sadd(String key, String element1, String element2, ....)   // 添加一个或多个元素
  • srem(String key, String element1, String element2, ...)    // 移除一个或多个元素

 

  • smembers(String key)   // 返回集合中所有的元素,Set<String>
  • scard(String  key)   // 返回集合中的元素个数,long
  • sismember(String key, String element)   // 检测集合中是否包含某个元素,boolean

 

  • spop(String key)   // 随机弹出一个元素,String
  • spop(String key, long count)   // 随机弹出 count 个元素,Set<String>

 

  • srandmember(String key)   // 随机返回一个元素。与 spop()的区别是,srandmember() 不会移除该元素
  • srandmember(Sring key, long count)

 

  • sdiff(String key1, String key2, ....)   // 求差集,返回 Set<String>
  • sdiffstore(String  destKey, String key1, String key2)   // 把差集中的元素存储到 destKey 集合中,返回差集中的元素个数,long

相同用法的还有:

  • sinter   交集
  • sunion   并集

 

set 是无序的,没有与索引相关的方法。

 

 

 

9、sorted  set

  • zadd(String key, doubel  score, String element)   
  • zadd(String key, Map<String, Double>  map)
  • zrem(String key, String element1, String element2,  ....)   // 移除一个或多个元素

 

  • zcard(String key)   // 元素个数,long
  • zcount(String key, double  minScore, double  maxScore)   // 返回 [minScore, maxScore] 区间上的元素个数。元素默认按 score 升序排列
  • zcount(String key, String startElement, String  endElement)   // 返回 [startElement, endElement] 上的元素个数

 

  • zrank(String key, String element)   // 返回该元素所在位置 | 排名,下标。默认按 score 升序排列
  • zrevrank(String key, String element)   // 按 score 降序排列

 

  • zincrby(String key, double increment, String element)    // 返回操作后的元素值,double。没有 zdecrby() 方法,将增量设置为负数即可

 

  • zinter(String destKey, String...keys)    // 交集,结果存储到 destKey 集合中
  • zunion(String destKey,String...keys)   // 并集

 

  • zrangeByXxx()  系列方法      // 返回该某个区间上的所有元素,Set<String>。默认按 score 升序排列
  • zrevrangeXxx()  系列方法   // 返回某个区间上的所有元素,Set<String>。按 score 降序排列,rev 即 reverse,反序
  • zremrangeByXxx()  系列方法   // 删除某个区间上的所有元素

 

list 返回多个元素时用的是 List,set、sorted set 返回多个元素时用的是 Set,hash 返回多个值时用的是 Map、List、Set。

 

  


 

 

JedisPool 的使用

自动创建一些 Jedis 对象,放在 JedisPool 中,要用时取出来直接用即可,用完放回池中,减少创建 Jedis 对象的时间开销。

  JedisPool jedisPool = new JedisPool("192.168.1.9",6379);  //host、port 均可选,缺省时使用默认值
  Jedis jedis = jedisPool.getResource();

 

 

可以对 JedisPool 进行配置:

        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(15);
        jedisPoolConfig.setMaxIdle(10);
        jedisPoolConfig.setMinIdle(5);
        jedisPoolConfig.setMaxWaitMillis(180);//若一个 Jedis 对象闲置多少秒,就销毁

        JedisPool jedisPool= new JedisPool(jedisPoolConfig, "192.168.1.9", 6379);
        Jedis jedis = jedisPool.getResource();

 

 

JedisPool jedisPool= new JedisPool(jedisPoolConfig, "192.168.1.9", 6379, 30, "abcd", true);

配置、host、port、超时时间、密码、是否使用 ssl,参数均可选。

超时时间是指多少秒内连不上 redis-server 就返回失败。

如果要使用 ssl,需要在 Linux 上安装 ssl 证书。

 

 


 

 

 

连接 redis 集群

        // 集群节点
        Set<HostAndPort> nodes = new HashSet();
        nodes.add(new HostAndPort("192.168.1.7", 6379)); //host、port
        nodes.add(new HostAndPort("192.168.1.7", 6380));
        nodes.add(new HostAndPort("192.168.1.7", 6381));
        nodes.add(new HostAndPort("192.168.1.7", 6382));
        nodes.add(new HostAndPort("192.168.1.7", 6383));
        nodes.add(new HostAndPort("192.168.1.7", 6384));

//获取 JedisCluster 对象 JedisCluster jedisCluster = new JedisCluster(nodes);
jedisCluster.set(
"level", "master"); String level = jedisCluster.get("level"); System.out.println("your level is :"+level);
    jedisCluster.zadd(</span>"users", 1223, "zhangsan"<span style="color: rgba(0, 0, 0, 1)">);
    jedisCluster.zadd(</span>"users", 2568, "lisi"<span style="color: rgba(0, 0, 0, 1)">);
    jedisCluster.zadd(</span>"users", 1379, "wangwu"<span style="color: rgba(0, 0, 0, 1)">);

    Set</span>&lt;Tuple&gt; users = jedisCluster.zrangeWithScores("users", 0, -1); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">[0,-1]</span>
    <span style="color: rgba(0, 0, 255, 1)">for</span><span style="color: rgba(0, 0, 0, 1)"> (Tuple user:users){
        String name </span>= user.getElement(); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取元素值</span>
        <span style="color: rgba(0, 0, 255, 1)">double</span> score = user.getScore(); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取分数</span>
        System.out.println(name+"的积分是:"+<span style="color: rgba(0, 0, 0, 1)">score);
    }    <br><br></span></pre>

 

JedisCluster 类的方法和 Jedis 类的方法基本一样,不再一一说明。