Advanced Redis application advanced course one-stop Redis solution

download: One-stop Redis solution for advanced Redis application courses

This course takes a practical project as the main line, integrates various problem scenarios of Redis, and transforms the project from time to time to learn by asking. After completing this lesson, you will be able to quickly stop troubleshooting and repair when faced with Redis-related problems, and you will become perfect in both practical work and job interviews.

The right people
are interested in Redis, but back-end engineers who don’t know how to deeply separate from the project
understand the daily operations of Redis, but the back-end engineers
who don’t understand the underlying principles of Redis have no thoughts about Redis problems and don’t know how to deal with back-end engineers
. Store request
back-end web development foundation

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public final class RedisClient {

private static String ADDR = "127.0.0.1";   //Redis效劳器IP 
private static int PORT = 6379;   //Redis的端口号 
private static String AUTH = null;//"admin";//访问密码
private static int MAX_ACTIVE = 1024;//可用衔接实例的最大数目,默许值为8;假如赋值为-1,则表示不限制;假如pool曾经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
private static int MAX_IDLE = 200; //控制一个pool最多有几个状态为idle(闲暇的)的jedis实例,默许值也是8。
private static int MAX_WAIT = 10000;//等候可用衔接的最大时间,单位毫秒,默许值为-1,表示永不超时。假如超越等候时间,则直接抛出JedisConnectionException;
private static int TIMEOUT = 10000;
private static boolean TEST_ON_BORROW = true;//在borrow一个jedis实例时,能否提早停止validate操作;假如为true,则得到的jedis实例均是可用的;
private static JedisPool jedisPool = null;

/**
 * 初始化Redis衔接池
 */
static {
    try {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxActive(MAX_ACTIVE);
        config.setMaxIdle(MAX_IDLE);
        config.setMaxWait(MAX_WAIT);
        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 resource = jedisPool.getResource();
            return resource;
        }
        return null;
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

private static Jedis jedis = getJedis();

/**
 * 释放jedis资源
 * @param jedis
 */
public static void returnResource(final Jedis jedis) {
    if (jedis != null) {
        jedisPool.returnResource(jedis);
    }
}

/***
 * 清空一切db
 */
public static void flushAll(){
    jedis.flushAll();
    RedisClient.returnResource(jedis);
}

Guess you like

Origin blog.51cto.com/15079112/2585893