redis操作

import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URL;
import java.util.Properties;
import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

@Slf4j
public class JedisUtil {

    private JedisPool jedispool;

    private static volatile JedisUtil jedisUtil;

    private JedisUtil() {
    }

    public static JedisUtil getInstance() {
        if (null == jedisUtil) {
            synchronized (JedisUtil.class) {
                if (null == jedisUtil){
                    jedisUtil = new JedisUtil();
                    jedisUtil.init();
                }
            }
        }
        return jedisUtil;
    }

    public void init() {
        Properties p = new Properties();
        URL url;
        ClassLoader cls = getClass().getClassLoader();
        url = cls.getResource("connect-redis.properties");
        try {
            p.load(url.openStream());
        } catch (FileNotFoundException e) {
            log.error("", e);
        } catch (IOException e) {
            log.error("", e);
        }
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxWaitMillis(Long.parseLong(p.getProperty("redis.maxWaitMillis")));
        config.setMaxTotal(Integer.parseInt(p.getProperty("redis.maxtotal")));
        config.setMinIdle(Integer.parseInt(p.getProperty("redis.minIdle")));
        config.setTestOnBorrow(Boolean.parseBoolean(p.getProperty("redis.testOnBorrow")));
        config.setTestOnReturn(Boolean.parseBoolean(p.getProperty("redis.testOnReturn")));
        config.setTestWhileIdle(Boolean.parseBoolean(p.getProperty("redis.testWhileIdle")));
        config.setTimeBetweenEvictionRunsMillis(Long.parseLong(p.getProperty("redis.timeBetweenEvictionRunsMillis")));
        jedispool = new JedisPool(config, p.getProperty("redis.host"), Integer.parseInt(p.getProperty("redis.port")),
                Integer.parseInt(p.getProperty("redis.timeout")));
    }

    public JedisPool getJedispool() {
        if (jedispool == null) {
            jedisUtil.init();
        }
        return jedispool;
    }

    public Jedis tryGetJedis() {
        try {
            return getJedispool().getResource();
        } catch (Exception e) {
            log.error("", e);
        }
        return null;
    }
}

public static boolean tryGetDistributedLock(Jedis jedis, String lockKey, String requestId, int expireTime) {
        try {
            String result = jedis.set(lockKey, requestId, Constant.SET_IF_NOT_EXIST, Constant.SET_WITH_EXPIRE_TIME,
                    expireTime);
            if (Constant.LOCK_SUCCESS.equals(result)) {
                return true;
            }
        } catch (Exception e) {
            log.error("", e);
            // jedis發現異常返回true
            return true;
        }
        return false;
    }


public static final String LOCK_SUCCESS = "OK";
    public static final String SET_IF_NOT_EXIST = "NX";
    public static final String SET_WITH_EXPIRE_TIME = "PX";
    public static final String DOMAIN_CONF_OP = "DOMAIN_CONF_OP";

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import java.util.UUID;
@Slf4j
public class CommonUtil {
    public synchronized String batchOperation() throws Exception {
        String requestId = UUID.randomUUID().toString() + HostNameUtil.getHostName();
        boolean lockedBySelf = false;
        boolean isOp = false;
        Jedis jedis = JedisUtil.getInstance().tryGetJedis();
        try {
            if (jedis != null) {
                int expireTime = 10 * 60 * 1000;
                if (Utils.tryGetDistributedLock(jedis, Constant.DOMAIN_CONF_OP, requestId, expireTime)) {
                    lockedBySelf = true;
                    isOp = true;
                }
            } else {
                isOp = true;// 如果jedis出問題,正常處理
            }
            if (isOp) {
                // todo 具體事務
            } else {
                return "hasOp";
            }
            return null;
        } catch (Exception e) {
            log.error("", e);
            return "ERROR";
        } finally {
            if (jedis != null) {
                if (lockedBySelf) {
                    jedis.del(Constant.DOMAIN_CONF_OP, requestId);
                }
                JedisUtil.getInstance().getJedispool().returnResource(jedis);
            }
        }
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章