Jedis connection pool (the actual items available)

POM dependence

<properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <slf4j.version>1.7.25</slf4j.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>3.8.1</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>${slf4j.version}</version>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/redis.clients/jedis -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>3.2.0</version>
        </dependency>
    </dependencies>

RedisPool

package utils;

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

public  class RedisPool {
     // reason declared as static: to ensure jedis tomcat connection pool when you start loading up
     // jedis connection pool 
    Private  static JedisPool the pool;
     Private  static Integer = maxTotal Integer.parseInt (PropertiesUtil.getProperty ( "redis.pool .maxTotal "," 20 is " ));
     Private  static Integer = the Integer.parseInt maxIdle (PropertiesUtil.getProperty (" redis.pool.maxIdle "," 10 " ));
     Private  static Integer = the Integer.parseInt minIdle (PropertiesUtil.getProperty ( "redis.pool.minIdle", "2" ));
     Private  static Integer maxWaitMillis = Integer.parseInt(PropertiesUtil.getProperty("redis.pool.maxWaitMillis", "2"));
    private static Boolean testOnBorrow = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.pool.testOnBorrow", "true"));
    private static Boolean testOnReturn = Boolean.parseBoolean(PropertiesUtil.getProperty("redis.pool.testOnReturn", "true"));
    private static Integer timeBetweenEvictionRunsMillis = Integer.parseInt(PropertiesUtil.getProperty("redis.pool.timeBetweenEvictionRunsMillis", "2"));
    private static Boolean testWhileIdle =Boolean.parseBoolean(PropertiesUtil.getProperty("redis.pool.testWhileIdle", "true"));
     Private  static Integer = the Integer.parseInt numTestsPerEvictionRun (PropertiesUtil.getProperty ( "redis.pool.numTestsPerEvictionRun", "2" ));
     Private  static String redisIp = PropertiesUtil.getProperty ( "redis.ip" );
     Private  static Integer redisPort Integer.parseInt = (PropertiesUtil.getProperty ( "redis.port" ));
     // initialize the connection pool, it will only be called once 
    Private  static  void initPool () {
        JedisPoolConfig config = new JedisPoolConfig();

        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMinIdle(minIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        config.setTestOnBorrow(testOnBorrow);
        config.setTestOnReturn (testOnReturn);
        config.setTimeBetweenEvictionRunsMillis (timeBetweenEvictionRunsMillis);
        config.setTestWhileIdle(testWhileIdle);
        config.setNumTestsPerEvictionRun (numTestsPerEvictionRun);

        // when the connection pool is exhausted, and whether obstruction, false throws an exception, true blocked until the timeout, timeout exception is thrown, the default is to true 
        config.setBlockWhenExhausted ( to true );

        // this timeout is 2S 
        the pool = new new JedisPool (config, redisIp, redisPort, 1000 * 2 );

    }

    static {
        initPool();
    }

    // pick from a connection pool instance 
    public  static Jedis getJedis () {
         return pool.getResource ();
    }

    // normal connection pool instance back jedis 
    public  static  void returnResource (Jedis jedis) {
        pool.close();
    }

    // The broken connection pool instance back jedis 
    public  static  void returnBrokenResource (Jedis jedis) {
        pool.close();
    }

}

RedisPoolUtil

package utils;



import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;

public class RedisPoolUtil {
    
    private static Logger log = LoggerFactory.getLogger(RedisPoolUtil.class);

    // reset period
     // parameter only key and expiration date, because only you can set the validity period according to key 
    public  static Long The expire (String key, int exTime) {
        Jedis jedis = null;
        Long result = null;
        try {
            jedis = RedisPool.getJedis ();
             // set period 
            Result = jedis.expire (Key, exTime);
        } catch (Exception e) {
            log.error("setex key:{} error", key, e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }

    // exTime unit is s, set the session valid time
     // When the user first logs in, there is need to set a deadline, there is redis session in
     // subsequent request if the user login again, you only need to call expire, you can reset the valid 
    public  static String SETEX (String Key, String value, int exTime) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = RedisPool.getJedis();
            result = jedis.setex(key, exTime, value);
        } catch (Exception e) {
            log.error("setex key:{} value:{} error", key, value, e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }

    public static String set(String key, String value) {
        Jedis Jedis = null ;
         // results returned jedis 
        String Result = null ;
         the try {
            jedis = RedisPool.getJedis();
            //设置key-value
            result = jedis.set(key, value);
        } catch (Exception e) {
            log.error("set key:{} value:{} error", key, value, e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }

    public static String get(String key) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = RedisPool.getJedis ();
             // Get value according to the value of Key 
            Result = jedis.get (Key);
        } catch (Exception e) {
            log.error("set key:{} error", key, e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }

    public static Long del(String key) {
        Jedis jedis = null;
        Long result = null;
        try {
            jedis = RedisPool.getJedis ();
             // The delete key-value key 
            Result = jedis.del (key);
        } catch (Exception e) {
            log.error("set key:{} error", key, e);
            RedisPool.returnBrokenResource(jedis);
            return result;
        }
        RedisPool.returnResource(jedis);
        return result;
    }
}

redis profile

# The maximum number of active objects     
redis.pool.maxTotal=1000
# The maximum number of objects to maintain state idel      
redis.pool.maxIdle=100
# Idel state can maintain the minimum number of objects   
redis.pool.minIdle=50
# When the pool does not return the object, the maximum waiting time    
redis.pool.maxWaitMillis=10000
# When calling borrow Object methods, whether a validity check    
redis.pool.testOnBorrow=true
# When you call return Object methods, whether a validity check    
redis.pool.testOnReturn = to true 
# "spare link" thread detection, the detection cycle milliseconds. If negative, it said they did not run the "detection thread." The default is -1 .  
redis.pool.timeBetweenEvictionRunsMillis = 30000
# Output when "Link" objects to the caller, if it detects idle time-out;  
redis.pool.testWhileIdle=true
# For "free links" check thread, the number of link resources per test. The default is 3.  
redis.pool.numTestsPerEvictionRun=50
#redis server IP
redis.ip=127.0.0.1
#redis server Port
redis.port = 6379
i

Log profile

logback.xml file

<?xml version="1.0" encoding="UTF-8" ?>

<configuration scan="true" scanPeriod="3 seconds">
    <! - set the log output to the console ->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%X{userId}] [%X{requestId}] %logger - %msg%n</pattern>
        </encoder>
    </appender>

    <! - set the log output to a file ->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <File>logFile.log</File>
        <rollingPolicy  class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <FileNamePattern>logFile.%d{yyyy-MM-dd_HH-mm}.log.zip</FileNamePattern>
        </rollingPolicy>

        <layout class="ch.qos.logback.classic.PatternLayout">
            <Pattern>%d{HH:mm:ss,SSS} [%thread] %-5level %logger{32} - %msg%n</Pattern>
        </layout>
    </appender>

    <root>
        <level value="DEBUG"/>
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="FILE"/>
    </root>


</configuration>

Guess you like

Origin www.cnblogs.com/dgwblog/p/12302029.html
Recommended