All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.github.yoojia.next.RedisProxy Maven / Gradle / Ivy

package com.github.yoojia.next;

import com.github.yoojia.next.supports.Config;
import com.github.yoojia.next.supports.Context;
import com.github.yoojia.next.supports.NextPlugin;
import com.github.yoojia.next.utils.SystemTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

/**
 * @author YOOJIA.CHEN ([email protected])
 */
public class RedisProxy implements NextPlugin {

    private static final Logger LOGGER = LoggerFactory.getLogger(RedisProxy.class);

    private static JedisPool CONNECTIONS;

    private static final ThreadLocal THREAD_CACHED = new ThreadLocal();

    @Override
    public void init(Context context, Config config) {
        LOGGER.debug("Init...");
        if (config == null){
            throw new IllegalArgumentException("Redis plugin require config!");
        }
        final long start = System.nanoTime();
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(config.getValue("max_idle", 10));
        final String host = config.getValue("host", "127.0.0.1");
        final String password = config.getValue("password", null);
        final int port = config.getValue("port", 6379);
        final int timeout = config.getValue("timeout", 10 * 1000);
        CONNECTIONS = new JedisPool(poolConfig, host, port, timeout, password);
        SystemTime.log(start, "RedisProxy.init()");
    }

    @Override
    public void onStartup(Context context) {}

    @Override
    public void onShutdown(Context context) {
        CONNECTIONS.destroy();
    }

    @Override
    public int getPriority() {
        return 0;
    }

    /**
     * 请求获取一个Jedis链接
     */
    public static Jedis apply(){
        final long start = System.nanoTime();
        try{
            final Jedis cached = THREAD_CACHED.get();
            if(cached != null) {
                return cached;
            }else{
                final Jedis create = CONNECTIONS.getResource();
                THREAD_CACHED.set(create);
                return create;
            }
        }finally {
            SystemTime.log(start, "RedisProsy.apply()");
        }
    }

    /**
     * 关闭一个Jedis链接
     */
    public static void release(Jedis resource){
        final Jedis cached = THREAD_CACHED.get();
        if(cached != null && cached == resource){
            THREAD_CACHED.set(null);
        }
        CONNECTIONS.returnResourceObject(resource);
    }
}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy