6.java连接Redis

Jedis 介绍

Redis 不仅是使用命令来操作,现在基本上主流的语言 (java、C、C#、C++、php、Node.js、Go 等) 都有客户端支持。
在官方网站里列一些 Java 的客户端,有 Jedis、Redisson、Jredis、JDBC-Redis、等;其中官方推荐使用 Jedis和 Redisson。在企业中用的最多的就是 Jedis,下面我们就重点学习下 Jedis。
Jedis 同样也是托管在 github 上,地址:https://github.com/xetorthio/jedis

java 入门程序

依赖:

    <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-pool2 -->
    <dependency>
      <groupId>org.apache.commons</groupId>
      <artifactId>commons-pool2</artifactId>
      <version>2.3</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
    <dependency>
      <groupId>redis.clients</groupId>
      <artifactId>jedis</artifactId>
      <version>2.7.0</version>
    </dependency>

代码:

public class Demo1 {
    /**
     * 单实例连接 redis 数据库
     */
    @Test
    public void first(){
        Jedis jedis = new Jedis("192.168.157.133", 6379);
        jedis.set("addr","北京");
        System.out.println(jedis.get("addr"));}
}

连接池

    /**
     * 连接池
     */
    @Test
    public void second(){
//        1. 设置连接池的配置对象
        JedisPoolConfig config = new JedisPoolConfig();
//        2. 设置池中最大连接数 [可选]
        config.setMaxTotal(50);
//        3. 设置空闲时间池中的连接数 [可选]
        config.setMaxIdle(10);
//        4. 设置连接池对象
        JedisPool pool = new JedisPool(config, "192.168.157.133", 6379);
//        5. 从池中获取连接对象
        Jedis jedis = pool.getResource();
        System.out.println(jedis.get("addr"));
//        6. 连接归还池中
    }

定义连接池工具类

package utils;

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

public class JedisUtils {
// 1. 定义一个连接池对象
private static final JedisPool POOL;

</span><span style="color: rgba(0, 128, 0, 1)">/**</span><span style="color: rgba(0, 128, 0, 1)">
 *  静态代码块初始化连接池对象:
 *     静态代码特点: 随着类的加载而执行,而且只执行一次,它仅能初始化类变量,即static修饰的数据成员。
 * </span><span style="color: rgba(0, 128, 0, 1)">*/</span>
<span style="color: rgba(0, 0, 255, 1)">static</span><span style="color: rgba(0, 0, 0, 1)"> {

// 1. 设置连接池的配置对象
JedisPoolConfig config = new JedisPoolConfig();
// 2. 设置池中最大连接数 [可选]
config.setMaxTotal(50);
// 3. 设置空闲时间池中的连接数 [可选]
config.setMaxIdle(10);
// 4. 设置连接池对象
POOL = new JedisPool(config, "192.168.157.133", 6379);
}

</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, 255, 1)">public</span> <span style="color: rgba(0, 0, 255, 1)">static</span><span style="color: rgba(0, 0, 0, 1)"> Jedis getJedis() {
    </span><span style="color: rgba(0, 0, 255, 1)">return</span><span style="color: rgba(0, 0, 0, 1)"> POOL.getResource();
}

}