redis工具类java

 依赖包:

<dependency>
    <groupId>redis.clients</groupId>
    <artifactId>jedis</artifactId>
    <version>3.2.0</version>
</dependency>

 工具类:

package com.xxx.xxx;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import redis.clients.jedis.*;

import javax.annotation.PostConstruct;
import java.math.BigInteger;
import java.util.*;

/**
 * 操作Redis的类
 *
 */
@Slf4j
@Component
public class RedisUtil {

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

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

    @Value("${redis.port}")
    private Integer port;

    @Value("${redis.maxInst}")
    private Integer maxInst;

    @Value("${redis.maxIdle}")
    private Integer maxIdle;

    @Value("${redis.maxWait}")
    private Integer maxWait;

    @Value("${redis.timeout}")
    private Integer timeout;

    private static JedisPool jedisPool;
    private JedisPoolConfig conf = new JedisPoolConfig();

    private RedisUtil() {
    }

    @PostConstruct
    private void init() {
        conf.setMaxTotal(maxInst);
        conf.setMaxIdle(maxIdle);
        conf.setMaxWaitMillis(maxWait);
        conf.setTestOnBorrow(true);
        createJedisPool();
    }

    private void createJedisPool() {
        try {
            if (jedisPool == null || (jedisPool != null && jedisPool.isClosed())) {
                if(StringUtils.isEmpty(password)){
                    jedisPool = new JedisPool(conf, host, port, timeout);
                }else{
                    jedisPool = new JedisPool(conf, host, port, timeout, password);
                }
            }
        } catch (Exception e) {
            log.error("can not create JedisPool.", e);
        }
    }

    /**
     * 获取Jedis连接
     *
     * @return
     */
    public static Jedis getConnection() {
        Jedis jedis = null;
        if (jedisPool != null && !jedisPool.isClosed()) {
            try {
                jedis = jedisPool.getResource();
            } catch (Exception e) {
                close(jedis);
                log.error("can not get jedis from JedisPool.", e);
            }
        } else {
            log.error("JedisPool is closed!");
            throw new RuntimeException("JedisPool is closed!");
        }
        return jedis;
    }

    /**
     * 关闭Jedis连接
     *
     * @param jedis
     */
    public static void close(Jedis jedis) {
        if (jedis != null) {
            try {
                jedis.close();
            } catch (Exception e) {
                log.error("can not return jedis to JedisPool.", e);
            }
        }
    }


    /**
     * 从Redis上获取数据
     *
     * <pre>
     * &#64;param key
     * &#64;return
     * Modifications:
     * Modifier wangdefeng; 2017年4月21日; Create new Method getStringFromRedis
     * </pre>
     */
    public static String getStringFromRedis(String key) {
        Jedis jedis = null;
        String result = null;
        try {
            jedis = RedisUtil.getConnection();
            result = jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            if (jedis != null) {
                RedisUtil.close(jedis);
            }
        }
        return result;
    }

    /**
     * 向redis存数据
     *
     * <pre>
     * &#64;param key
     * &#64;param value
     * Modifications:
     * Modifier wangdefeng; 2017年4月21日; Create new Method putStringToRedis
     * </pre>
     */
    public static void putStringToRedis(String key, String value) {
        Jedis jedis = null;
        try {
            jedis = RedisUtil.getConnection();
            jedis.set(key, value);
            //jedis.expire(key, getExpireSecond());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            if (null != jedis) {
                RedisUtil.close(jedis);
            }
        }
    }

    public static void putStreamToRedis(String key, Map<String, String> data) {
        Jedis jedis = null;
        try {
            jedis = RedisUtil.getConnection();
            jedis.del(key);
//            jedis.xdel(key,StreamEntryID.LAST_ENTRY);
//            jedis.xrange(key, "-", "+", jedis.xlen(key).intValue());
            jedis.xadd(key, StreamEntryID.NEW_ENTRY, data);
            //jedis.expire(key, getExpireSecond());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            if (null != jedis) {
                RedisUtil.close(jedis);
            }
        }
    }

    public static List<StreamEntry> getStreamFromRedis(String key,String startStreamEntryID,String endStreamEntryID) {
        Jedis jedis = null;
        List<StreamEntry> list = new ArrayList<>();
        try {
            jedis = RedisUtil.getConnection();
            list = jedis.xrange(key, new StreamEntryID(startStreamEntryID), new StreamEntryID(endStreamEntryID), Math.toIntExact(jedis.xlen(key)));
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            if (null != jedis) {
                RedisUtil.close(jedis);
            }
        }
        return list;
    }

    /**
     * 根据redis的key和map中的key获取value
     * @param key
     * @param field
     * @return
     */
    public List<String> getMapValueByKeyFromRedis(String key,String field){
        Jedis jedis = null;
        List<String> result = null;
        try {
            jedis = RedisUtil.getConnection();
            result = jedis.hmget(key,field);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            if (jedis != null) {
                RedisUtil.close(jedis);
            }
        }
        return result;
    }
    /**
     * 获取map中所有的key
     * @param key
     * @return
     */
    public Set<String> getMapKeyFromRedis(String key){
        Jedis jedis = null;
        Set<String> result = null;
        try {
            jedis = RedisUtil.getConnection();
            result = jedis.hkeys(key);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            if (jedis != null) {
                RedisUtil.close(jedis);
            }
        }
        return result;
    }

    /**
     * 将map缓存到redis中
     * @param key
     * @param map
     */
    public  void putMapToRedis(String key,Map map){
        Jedis jedis = null;
        try {
            jedis = RedisUtil.getConnection();
            jedis.hmset(key, map);
            //jedis.expire(key, getExpireSecond());
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            if (null != jedis) {
                RedisUtil.close(jedis);
            }
        }
    }
    /**
     * 获取到当天24点剩余时间,单位(s)
     *
     * <pre>
     * &#64;return
     * Modifications:
     * Modifier wangdefeng; 2017年4月21日; Create new Method getExpireSecond
     * </pre>
     */
    private static int getExpireSecond() {
        Date date = new Date();
        Calendar cal = Calendar.getInstance();
        cal.setTime(date);
        cal.set(Calendar.HOUR, 0);
        cal.set(Calendar.MINUTE, 0);
        cal.set(Calendar.SECOND, 0);
        cal.set(Calendar.MILLISECOND, 0);
        cal.add(Calendar.DATE, 1);
        Date nextDate = cal.getTime();
        return (int) (nextDate.getTime() - date.getTime()) / 1000;
    }

    /**
     * 删除redis数据
     * @param key
     * @return
     */
    public static void delFromRedis(String key) {
        Jedis jedis = null;
        try {
            jedis = RedisUtil.getConnection();
            jedis.del(key);
        } catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage(), e);
        } finally {
            if (jedis != null) {
                RedisUtil.close(jedis);
            }
        }
    }

    public static void main(String[] args) {
        System.out.println(new BigInteger(String.valueOf(14)).shiftRight(24).toString());
        RedisUtil redisUtil = new RedisUtil();
//        redisUtil.putStringToRedis("keykey","12");
//        Map<String, String> dataMap = new HashMap<>();
//        dataMap.put("123", "value123");
//        dataMap.put("factoryKey", "测试");
//        redisUtil.putStreamToRedis("keykey",dataMap);

        String s = redisUtil.getStringFromRedis("Config:Instance:417484016137011200:417484016141306426");
        System.out.println(s);

    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

凌晨两点钟同学

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值