站点工具


侧边栏

抱歉,您没有权限增加页面
服务器技术:java:redisclient


import java.io.IOException;
import java.util.List;
import java.util.UUID;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisSentinelPool;

@Component
public class RedisClient {

    @Autowired
    @Qualifier("jedisSentinelPool")
    private JedisSentinelPool jedisSentinelPool;

    @Value("${redis.key.prefix}")
    private String prefix;

    Logger logger = LoggerFactory.getLogger(RedisClient.class);

    private ObjectMapper objectMapper = new ObjectMapper();

    /
     * 从Redis缓存获取数据
     *
     * @param redisKey
     * @return
     */
    public Object getObjFromRedis(String redisKey) {
        redisKey = prefix + redisKey;
        Jedis jedis = getJedisResource();
        String jsonStr = null;
        try {
            jsonStr = jedis.get(redisKey);
        } finally {
            if (jedis != null) {
                if (null != jedis)
                    jedis.close();
            }
        }

        if (jsonStr != null) {
            try {
                return objectMapper.readValue(jsonStr, Object.class);
            } catch (IOException e) {
                logger.error("反序列化失败", e);
            }

        }

        return null;
    }

    public <T> T getObjFromRedis(String redisKey, Class<T> clazz) {
        redisKey = prefix + redisKey;
        Jedis jedis = getJedisResource();
        String jsonStr = null;
        try {
            jsonStr = jedis.get(redisKey);
        } finally {
            if (null != jedis)
                jedis.close();
        }

        if (jsonStr != null) {
            try {
                return objectMapper.readValue(jsonStr, clazz);
            } catch (IOException e) {
                logger.error("反序列化失败", e);
            }
        }

        return null;
    }

    public Long incr(String redisKey) {

        redisKey = prefix + redisKey;

        Jedis jedis = getJedisResource();
        Long num = null;
        try {
            num = jedis.incr(redisKey);
        } finally {
             归还资源
             jedisPool.returnResource(jedis);
            if (null != jedis)
                jedis.close();
        }

        return num;

    }

    public Long incrBy(String redisKey, int offset) {

        redisKey = prefix + redisKey;

        Jedis jedis = getJedisResource();
        Long num = null;
        try {
            num = jedis.incrBy(redisKey, offset);
        } finally {
             归还资源
            if (null != jedis)
                jedis.close();
        }

        return num;

    }

    public Long decrBy(String redisKey, int offset) {

        redisKey = prefix + redisKey;

        Jedis jedis = getJedisResource();
        Long num = null;
        try {
            num = jedis.decrBy(redisKey, offset);
        } finally {
             归还资源
            if (null != jedis)
                jedis.close();
        }

        return num;

    }

    public Long decr(String redisKey) {

        redisKey = prefix + redisKey;

        Jedis jedis = getJedisResource();
        Long num = 0L;
        try {
            num = jedis.decr(redisKey);
        } finally {
             归还资源
            if(null != jedis)
            jedis.close();
        }

        return num;

    }

    public Jedis getJedisResource() {
        Jedis jedis = null;
        try {
            jedis = jedisSentinelPool.getResource();
            if (jedis != null) {
                return jedis;
            }
        } catch (Exception e) {
            logger.warn("=============Redis Resource Is Not alived====================", e);
            if (jedis != null) {
                 jedisPool.returnBrokenResource(jedis);
                jedis.close();
            }
        }

        return null;
    }

    public String set(String redisKey, String value) {

        redisKey = prefix + redisKey;

        Jedis jedis = getJedisResource();
        String ret = null;
        try {
            ret = jedis.set(redisKey, value);
        } finally {
             归还资源
             jedisPool.returnResource(jedis);
            if (null != jedis)
                jedis.close();
        }

        return ret;

    }

    public String set(String redisKey, String value, int seconds) {

        redisKey = prefix + redisKey;

        Jedis jedis = getJedisResource();
        String ret = null;
        try {
            ret = jedis.setex(redisKey, seconds, value);
        } finally {
             归还资源
             jedisPool.returnResource(jedis);
            if (null != jedis)
                jedis.close();
        }

        return ret;

    }

    public Long delete(String redisKey) {

        redisKey = prefix + redisKey;

        Jedis jedis = getJedisResource();
        Long ret = null;
        try {
            ret = jedis.del(redisKey);
        } finally {
             归还资源
             jedisPool.returnResource(jedis);
            if (null != jedis)
                jedis.close();
        }

        return ret;

    }

    public String set(String redisKey, Long value) {

        return this.set(redisKey, String.valueOf(value));
    }

    public synchronized Long getLong(String redisKey) {
        Long l = null;
        String str = this.get(redisKey);
        if (str != null) {
            l = Long.valueOf(str);
        }
        return l;
    }

    public String get(String redisKey) {

        redisKey = prefix + redisKey;

        Jedis jedis = getJedisResource();
        String str = null;
        try {
            str = jedis.get(redisKey);
        } finally {
             归还资源
             jedisPool.returnResource(jedis);
            if (null != jedis)
                jedis.close();
        }

        return str;

    }

    /
     * 一次获取多个
     *
     * @param redisKey
     * @return
     */
    public List<String> mget(String[] redisKey) {

         redisKey = prefix + redisKey;
        if (redisKey != null) {
            for (int i = 0; i < redisKey.length; i++) {
                redisKey[i] = prefix + redisKey[i];
            }
        }

        Jedis jedis = getJedisResource();
        List<String> str = null;
        try {
            str = jedis.mget(redisKey);
        } finally {

             归还资源
            if (null != jedis)
                jedis.close();
        }

        return str;

    }

    public String saveObjToRedis(String redisKey, Object obj, int seconds) {

        redisKey = prefix + redisKey;

        String value;
        try {
            value = objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("json序列化失败", e);
            return "FAIL";
        }

        Jedis jedis = getJedisResource();
        String code = null;
        try {
            code = jedis.setex(redisKey, seconds, value);
        } finally {
             归还资源
            if (null != jedis)
                jedis.close();
        }

        return code;
    }

    /**
     * 保存数据到Redis
     *
     * @param redisKey @throws
     */
    public String saveObjToRedis(String redisKey, Object obj) {

        redisKey = prefix + redisKey;

        String value;
        try {
            value = objectMapper.writeValueAsString(obj);
        } catch (JsonProcessingException e) {
            logger.error("json序列化失败", e);
            return "FAIL";
        }

        Jedis jedis = getJedisResource();
        String code = null;
        try {
            code = jedis.set(redisKey, value);
        } finally {
             归还资源
            if (null != jedis)
                jedis.close();
        }

        return code;
    }

    public String lock(String lockKey, int seconds) {

        String redisKey = prefix + lockKey;

        String lockedValue = UUID.randomUUID().toString();
        Jedis jedis = getJedisResource();
        try {
            Long result = jedis.setnx(redisKey, lockedValue);

             加锁失败
            if (result <= 0) {

                return lockedValue;
            }
            if (result > 0 && seconds > 0) {
                jedis.expire(redisKey, seconds);

            }
             归还资源
             jedisPool.returnResource(jedis);
        } finally {
            if (null != jedis)
                jedis.close();
        }

        return lockedValue;

    }

    public Long unlock(String lockKey, String lockedValue) {

        String redisKey = prefix + lockKey;

        Jedis jedis = getJedisResource();

        try {
            String target = jedis.get(redisKey);

            if (target != null && target.equals(lockedValue)) {
                return jedis.del(redisKey);
            }
        } finally {
             归还资源
             jedisPool.returnResource(jedis);
            if (null != jedis)
                jedis.close();
        }

        return -1l;
    }

    @Override
    protected void finalize() throws Throwable {

        jedisSentinelPool.destroy();
        super.finalize();

    }
}

服务器技术/java/redisclient.txt · 最后更改: 2020/07/08 18:23 由 chenjinlian