Jedis 操作redis简易说明

参考地址: https://tech.antfin.com/docs/2/98726

1: maven引入jar

        <!-- Jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>2.9.0</version>
        </dependency>
        
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-pool2</artifactId>
            <version>2.8.0</version>
        </dependency>

2:测试代码

package com.gwzx.gwzxyw.utils;

import org.apache.commons.pool2.impl.GenericObjectPoolConfig;

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

/**
 * 操作redis简易工具类
 * @author
 *
 */
public class JedisUtil {
    
    private static JedisPool jedispool = null;
    
    public static void main(String[] args) {
        try {
            //连接池通用的一些设置
            GenericObjectPoolConfig poolconf = new GenericObjectPoolConfig();
            //设置连接池的属性
            //设置连接池最多创建50个jedis连接
            poolconf.setMaxTotal(60);
            //设置池中最多保留10个空闲的jedis连接
            poolconf.setMaxIdle(10);
            //设置池中最小保留5个空闲的jedis连接
            poolconf.setMinIdle(5);
            // 当资源池连接用尽后,调用者的最大等待时间(单位为毫秒)。默认值为-1,表示永不超时
            poolconf.setMaxWaitMillis(1000L * 2);
            //当连接用完时,是否阻塞客户端直到超时。false代表连接耗尽,直接给客户端抛异常
            poolconf.setBlockWhenExhausted(true);
            //从池中借一个连接时,先测试一下连接是否正常
            poolconf.setTestOnBorrow(true);
            //return 一个jedis实例给pool时,是否检查连接可用性(ping())
            //poolconf.setTestOnReturn(true);
            
            // 空闲检测
            // 如果为true,表示用一个专门的线程对空闲的连接进行有效性的检测扫描,如果有效性检测失败,即表示无效连接,会从资源池中移除。
            poolconf.setTestWhileIdle(true);
            // 表示一个Jedis连接至少停留在空闲状态的最短时间,然后才能被空闲连接扫描线程进行有效性检测,默认值为60000毫秒,即60秒。
            poolconf.setMinEvictableIdleTimeMillis(1000L * 60);
            // 表示两次空闲连接扫描的活动之间,要睡眠的毫秒数,默认为30000毫秒,也就是30秒钟。
            poolconf.setTimeBetweenEvictionRunsMillis(1000L * 30);
            // 表示空闲检测线程每次最多扫描的Jedis连接数,默认值为-1,表示扫描全部的空闲连接。
            poolconf.setNumTestsPerEvictionRun(-1);
            
            // public JedisPool(final GenericObjectPoolConfig poolConfig, final String host, int port, int timeout, final String password, final int database) 
            jedispool = new JedisPool(poolconf, "127.0.0.1", 6379, 2000, null, 0);

            //从池中获取一个连接
            Jedis jedis = jedispool.getResource();
            //使用
            System.out.println(jedis.ping());    //PONG
            String t = jedis.setex("receipt:aa", 30, "老郭laoguo..");
            System.out.println("t:" + t); //OK
            
            String value = jedis.get("receipt:aa");
            System.out.println("value:" + value);
            //将连接放回连接池
            jedis.close();
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("启动失败");
        }
    }

    
}