Redis】Java中使用Jedis操作Redis(Maven导入包)、创建Redis连接池

如果我们使用 Java 操作 Redis, 需要确保已经安装了 redis 服务及 Java redis 驱动。

Maven 项目可以直接在 pom.xml 中加入 jedis 包驱动:

        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>

Jedis 中操作 String,List,Set,Map,以及集合排序

package cn.hncu;

import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.Jedis;

import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**

  • Created with IntelliJ IDEA.

  • Explain:Java 操作 Redis 测试
    */
    public class TestRedis {

    private Jedis jedis;

    @Before
    public void setJedis() {
    //连接 redis 服务器 (在这里是连接本地的)
    jedis = new Jedis("127.0.0.1", 6379);
    //权限认证
    jedis.auth("chenhaoxiang");
    System.out.println(
    "连接服务成功");
    }

    /**

    • Redis 操作字符串
      */
      @Test
      public void testString() {
      //添加数据
      jedis.set("name", "chx"); //key 为 name 放入 value 值为 chx
      System.out.println("拼接前:" + jedis.get("name"));//读取 key 为 name 的值

      //向 key 为 name 的值后面加上数据 --- 拼接
      jedis.append("name", "is my name;");
      System.out.println(
      "拼接后:" + jedis.get("name"));

      //删除某个键值对
      jedis.del("name");
      System.out.println(
      "删除后:" + jedis.get("name"));

      //s 设置多个键值对
      jedis.mset("name", "chenhaoxiang", "age", "20", "email", "chxpostbox@outlook.com");
      jedis.incr(
      "age");//用于将键的整数值递增 1。如果键不存在,则在执行操作之前将其设置为 0。 如果键包含错误类型的值或包含无法表示为整数的字符串,则会返回错误。此操作限于 64 位有符号整数。
      System.out.println(jedis.get("name") + "" + jedis.get("age") +" "+ jedis.get("email"));
      }

    @Test
    public void testMap() {
    //添加数据
    Map<String, String> map = new HashMap<String, String>();
    map.put(
    "name", "chx");
    map.put(
    "age", "100");
    map.put(
    "email", "***@outlook.com");
    jedis.hmset(
    "user", map);
    //取出 user 中的 name,结果是一个泛型的 List
    //第一个参数是存入 redis 中 map 对象的 key,后面跟的是放入 map 中的对象的 key,后面的 key 是可变参数
    List<String> list = jedis.hmget("user", "name", "age", "email");
    System.out.println(list);

     </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">删除map中的某个键值</span>
     jedis.hdel("user", "age"<span style="color: rgba(0, 0, 0, 1)">);
     System.out.println(</span>"age:" + jedis.hmget("user", "age")); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">因为删除了,所以返回的是null</span>
     System.out.println("user的键中存放的值的个数:" + jedis.hlen("user")); <span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">返回key为user的键中存放的值的个数2</span>
     System.out.println("是否存在key为user的记录:" + jedis.exists("user"));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">是否存在key为user的记录 返回true</span>
     System.out.println("user对象中的所有key:" + jedis.hkeys("user"));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">返回user对象中的所有key</span>
     System.out.println("user对象中的所有value:" + jedis.hvals("user"));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">返回map对象中的所有value
    
     </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">拿到key,再通过迭代器得到值</span>
     Iterator&lt;String&gt; iterator = jedis.hkeys("user"<span style="color: rgba(0, 0, 0, 1)">).iterator();
     </span><span style="color: rgba(0, 0, 255, 1)">while</span><span style="color: rgba(0, 0, 0, 1)"> (iterator.hasNext()) {
         String key </span>=<span style="color: rgba(0, 0, 0, 1)"> iterator.next();
         System.out.println(key </span>+ ":" + jedis.hmget("user"<span style="color: rgba(0, 0, 0, 1)">, key));
     }
     jedis.del(</span>"user"<span style="color: rgba(0, 0, 0, 1)">);
     System.out.println(</span>"删除后是否存在key为user的记录:" + jedis.exists("user"));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">是否存在key为user的记录</span>
    
}
</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 * jedis操作List
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
@Test
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> testList(){
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">移除javaFramwork所所有内容</span>
    jedis.del("javaFramwork"<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>
    jedis.lpush("javaFramework","spring"<span style="color: rgba(0, 0, 0, 1)">);
    jedis.lpush(</span>"javaFramework","springMVC"<span style="color: rgba(0, 0, 0, 1)">);
    jedis.lpush(</span>"javaFramework","mybatis"<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)">取出所有数据,jedis.lrange是按范围取出
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">第一个是key,第二个是起始位置,第三个是结束位置</span>
    System.out.println("长度:"+jedis.llen("javaFramework"<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)">jedis.llen获取长度,-1表示取得所有</span>
    System.out.println("javaFramework:"+jedis.lrange("javaFramework",0,-1<span style="color: rgba(0, 0, 0, 1)">));

    jedis.del(</span>"javaFramework"<span style="color: rgba(0, 0, 0, 1)">);
    System.out.println(</span>"删除后长度:"+jedis.llen("javaFramework"<span style="color: rgba(0, 0, 0, 1)">));
    System.out.println(jedis.lrange(</span>"javaFramework",0,-1<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)">
 * jedis操作Set
 </span><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
@Test
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> testSet(){
    </span><span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">添加</span>
    jedis.sadd("user","chenhaoxiang"<span style="color: rgba(0, 0, 0, 1)">);
    jedis.sadd(</span>"user","hu"<span style="color: rgba(0, 0, 0, 1)">);
    jedis.sadd(</span>"user","chen"<span style="color: rgba(0, 0, 0, 1)">);
    jedis.sadd(</span>"user","xiyu"<span style="color: rgba(0, 0, 0, 1)">);
    jedis.sadd(</span>"user","chx"<span style="color: rgba(0, 0, 0, 1)">);
    jedis.sadd(</span>"user","are"<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)">移除user集合中的元素are</span>
    jedis.srem("user","are"<span style="color: rgba(0, 0, 0, 1)">);
    System.out.println(</span>"user中的value:"+jedis.smembers("user"));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">获取所有加入user的value</span>
    System.out.println("chx是否是user中的元素:"+jedis.sismember("user","chx"));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">判断chx是否是user集合中的元素</span>
    System.out.println("集合中的一个随机元素:"+jedis.srandmember("user"));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">返回集合中的一个随机元素</span>
    System.out.println("user中元素的个数:"+jedis.scard("user"<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><span style="color: rgba(0, 128, 0, 1)">*/</span><span style="color: rgba(0, 0, 0, 1)">
@Test
</span><span style="color: rgba(0, 0, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">void</span><span style="color: rgba(0, 0, 0, 1)"> test(){
    jedis.del(</span>"number");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">先删除数据,再进行测试</span>
    jedis.rpush("number","4");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">将一个或多个值插入到列表的尾部(最右边)</span>
    jedis.rpush("number","5"<span style="color: rgba(0, 0, 0, 1)">);
    jedis.rpush(</span>"number","3"<span style="color: rgba(0, 0, 0, 1)">);

    jedis.lpush(</span>"number","9");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">将一个或多个值插入到列表头部</span>
    jedis.lpush("number","1"<span style="color: rgba(0, 0, 0, 1)">);
    jedis.lpush(</span>"number","2"<span style="color: rgba(0, 0, 0, 1)">);
    System.out.println(jedis.lrange(</span>"number",0,jedis.llen("number"<span style="color: rgba(0, 0, 0, 1)">)));
    System.out.println(</span>"排序:"+jedis.sort("number"<span style="color: rgba(0, 0, 0, 1)">));
    System.out.println(jedis.lrange(</span>"number",0,-1));<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">不改变原来的排序</span>
    jedis.del("number");<span style="color: rgba(0, 128, 0, 1)">//</span><span style="color: rgba(0, 128, 0, 1)">测试完删除数据</span>

}

}

Redis 连接池

package cn.hncu;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**

  • Created with IntelliJ IDEA.

  • Explain:Redis 连接池
    */
    public final class RedisPool {
    //Redis 服务器 IP
    private static String ADDR = "127.0.0.1";
    //Redis 的端口号
    private static Integer PORT = 6379;
    //访问密码
    private static String AUTH = "chenhaoxiang";

    //可用连接实例的最大数目,默认为 8;
    //如果赋值为 -1,则表示不限制,如果 pool 已经分配了 maxActive 个 jedis 实例,则此时 pool 的状态为 exhausted(耗尽)
    private static Integer MAX_TOTAL = 1024;
    //控制一个 pool 最多有多少个状态为 idle(空闲) 的 jedis 实例,默认值是 8
    private static Integer MAX_IDLE = 200;
    //等待可用连接的最大时间,单位是毫秒,默认值为 -1,表示永不超时。
    //如果超过等待时间,则直接抛出 JedisConnectionException
    private static Integer MAX_WAIT_MILLIS = 10000;
    private static Integer TIMEOUT = 10000;
    //在 borrow(用) 一个 jedis 实例时,是否提前进行 validate(验证) 操作;
    //如果为 true,则得到的 jedis 实例均是可用的
    private static Boolean TEST_ON_BORROW = true;
    private static JedisPool jedisPool = null;

    /**

    • 静态块,初始化 Redis 连接池
      /
      static {
      try {
      JedisPoolConfig config
      = new JedisPoolConfig();
      /
      注意:
      在高版本的 jedis jar 包,比如本版本 2.9.0,JedisPoolConfig 没有 setMaxActive 和 setMaxWait 属性了
      这是因为高版本中官方废弃了此方法,用以下两个属性替换。
      maxActive ==> maxTotal
      maxWait==> maxWaitMillis
      */
      config.setMaxTotal(MAX_TOTAL);
      config.setMaxIdle(MAX_IDLE);
      config.setMaxWaitMillis(MAX_WAIT_MILLIS);
      config.setTestOnBorrow(TEST_ON_BORROW);
      jedisPool
      = new JedisPool(config,ADDR,PORT,TIMEOUT,AUTH);
      }
      catch (Exception e) {
      e.printStackTrace();
      }

    }

    /**

    • 获取 Jedis 实例
    • @return
      */
      public synchronized static Jedis getJedis(){
      try {
      if(jedisPool != null){
      Jedis jedis
      = jedisPool.getResource();
      return jedis;
      }
      else{
      return null;
      }
      }
      catch (Exception e) {
      e.printStackTrace();
      return null;
      }
      }

    public static void returnResource(final Jedis jedis){
    //方法参数被声明为 final,表示它是只读的。
    if(jedis!=null){
    jedisPool.returnResource(jedis);
    //jedis.close()取代 jedisPool.returnResource(jedis) 方法将 3.0 版本开始
    //jedis.close();
    }
    }
    }

RedisJava 测试连接池

package cn.hncu;

import redis.clients.jedis.Jedis;

/**

  • Created with IntelliJ IDEA.

  • Explain: 测试 RedisPool
    */
    public class RedisJava {

    public static void main(String[] args) {
    RedisPool.getJedis().set(
    "name","陈浩翔");
    System.out.println(RedisPool.getJedis().get(
    "name"));
    }

}