使用jedis操作redis

4 篇文章 0 订阅

1、引入jar

<redis.clients.version>2.9.0</redis.clients.version>
<!--redis缓存相关依赖-->
        <dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-redis</artifactId>
            <version>1.8.0.RC1</version>
        </dependency>
        <!-- redis客户端jar -->
        <dependency>
            <groupId>redis.clients</groupId>
            <artifactId>jedis</artifactId>
            <version>${redis.clients.version}</version>
        </dependency>
2、配置redis.properties
#访问地址
redis.host=127.0.0.1
#访问端口
redis.port=6379
#注意,如果没有password,此处不设置值,但这一项要保留,默认foobared
redis.password=foobared
#客户端超时时间单位是毫秒 默认是2000
redis.timeout=10000

#最大空闲数
redis.maxIdle=300
#连接池的最大数据库连接数。设为0表示无限制,如果是jedis 2.4以后用redis.maxTotal
redis.maxActive=300
#控制一个pool可分配多少个jedis实例,用来替换上面的redis.maxActive,如果是jedis 2.4以后用该属性
redis.maxTotal=300
#当池内没有返回对象时,最大等待时间
redis.maxWait=10000
#当调用borrow Object方法时,是否进行有效性检查 ,如果为true,则得到的jedis实例均是可用的
redis.testOnBorrow=false
redis.testOnReturn=false
#在空闲时检查有效性, 默认false
redis.testWhileIdle=true
#最大建立连接等待时间。如果超过此时间将接到异常。设为-1表示无限制。
redis.maxWaitMillis=1000
#连接的最小空闲时间 默认1800000毫秒(30分钟)
redis.minEvictableIdleTimeMillis=300000
#每次释放连接的最大数目,默认3
redis.numTestsPerEvictionRun=1024
#逐出扫描的时间间隔(毫秒) 如果为负数,则不运行逐出线程, 默认-1
redis.timeBetweenEvictionRunsMillis=30000
#连接耗尽是否阻塞,false代表抛异常,true代表阻塞直到超时,默认为true
redis.blockWhenExhausted=false
3、配置redis-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="poolConfig" class="redis.clients.jedis.JedisPoolConfig">
        <property name="maxIdle" value="${redis.maxIdle}"/>
        <property name="maxTotal" value="${redis.maxTotal}"/>
        <property name="maxWaitMillis" value="${redis.maxWait}"/>
        <property name="testOnBorrow" value="${redis.testOnBorrow}"/>
        <property name="testOnReturn" value="${redis.testOnReturn}"/>
        <property name="testWhileIdle" value="${redis.testWhileIdle}"/>
        <property name="timeBetweenEvictionRunsMillis" value="${redis.timeBetweenEvictionRunsMillis}"/>
        <property name="minEvictableIdleTimeMillis" value="${redis.minEvictableIdleTimeMillis}"/>
        <!--每次逐出检查时 逐出的最大数目 如果为负数就是 : 1/abs(n), 默认3-->
        <property name="numTestsPerEvictionRun" value="${redis.numTestsPerEvictionRun}"/>
        <!--连接耗尽是否阻塞,false代表抛异常,true代表阻塞直到超时,默认为true -->
        <property name="blockWhenExhausted" value="${redis.blockWhenExhausted}"/>
    </bean>

    <bean id="jedisPool" class="redis.clients.jedis.JedisPool">
        <constructor-arg name="poolConfig" ref="poolConfig" />
        <constructor-arg name="host" value="${redis.host}" />
        <constructor-arg name="port" value="${redis.port}" type="int" />
        <constructor-arg name="timeout" value="${redis.maxWait}" type="int" />
        <constructor-arg name="password" value="${redis.password}" />
        <constructor-arg name="database" value="0" type="int" />
    </bean>

    <!--自定义redis工具类,在需要缓存的地方注入此类  -->
    <bean id="redisService" class="com.hikvision.common.cache.RedisService">
        <property name="jedisPool" ref="jedisPool" />
    </bean>
</beans>
4、工具类, RedisService.java
package com.hikvision.common.cache;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hikvision.common.util.LogUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * redis缓存服务service
 *
 * @author wanjiadong
 * @description
 * @date Create in 16:35 2018/5/10
 */
public class RedisService {

    private JedisPool jedisPool;

    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

    /**
     * 获取Jedis实例
     *
     * @return
     */
    public synchronized Jedis getJedis() {
        try {
            if (jedisPool != null) {
                Jedis resource = jedisPool.getResource();
                LogUtil.debug(RedisService.class, resource
                        + ",activeNum:"+ jedisPool.getNumActive()
                        + ",idleNum:" + jedisPool.getNumIdle()
                        + ",waiterNum:" + jedisPool.getNumWaiters());
                return resource;
            } else {
                return null;
            }
        } catch (Exception e) {
            LogUtil.exception(RedisService.class, "Redis缓存获取Jedis实例 出错!", e);
            return null;
        }
    }

    /**
     * 释放jedis资源
     * 每次连接必须使用
     *
     * @param jedis
     */
    public void returnResource(final Jedis jedis) {
        if (jedis != null) {
            //jedis-2.9以上的版本已经使用了jedis.close()
            jedis.close();
//            jedisPool.returnResource(jedis);
//            jedis.quit();
        }
    }

    //=============================common============================

    /**
     * 指定缓存失效时间
     * @param key 键
     * @param time 时间(秒)
     * @return
     */
    public boolean expire(String key,long time){
        boolean result = false;
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (null != jedis && time > 0) {
                jedis.expire(key, (int) time);
            }
        } catch (Exception e) {
            LogUtil.exception(RedisService.class, "redis键过期设置出错--键值" + key, e);
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    /**
     * 根据key 获取过期时间
     * @param key 键 不能为null
     * @return 时间(秒) 返回0代表为永久有效
     */
    public long getExpire(String key){
        Long time = null;
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (jedis != null) {
                time = jedis.ttl(key);
            }
        } catch (Exception e) {
            LogUtil.exception(RedisService.class, "获取" + key + "的过期时间出错!", e);
        } finally {
            returnResource(jedis);
        }
        if(null == time) {
            return -2;
        }
        return time;
    }

    /**
     * 判断key是否存在
     * @param key 键
     * @return true 存在 false不存在
     */
    public boolean hasKey(String key){
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (jedis != null) {
                return jedis.exists(key);
            }
        } catch (Exception e) {
            LogUtil.exception(RedisService.class, "获取" + key + "的过期时间出错!", e);
        } finally {
            returnResource(jedis);
        }
        return false;
    }

    /**
     * 删除缓存
     * @param key 可以传一个值 或多个
     */
    @SuppressWarnings("unchecked")
    public void del(String ... key){
        if(null == key) {
            return;
        }
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if(null == jedis) {
                return;
            }
            jedis.del(key);
        } catch (Exception e) {
            LogUtil.exception(RedisService.class, "删除" + key + "出错!", e);
        } finally {
            returnResource(jedis);
        }
    }

    //============================String=============================
    /**
     * 普通缓存获取
     * @param key 键
     * @return 值
     */
    public Object get(String key){
        Jedis jedis = null;
        Object obj = null;
        try {
            jedis = jedisPool.getResource();
            String str = jedis.get(key);
            obj = JSONObject.parse(str);
        } catch (Exception e) {
            LogUtil.exception(RedisService.class, "获取" + key + "出错!", e);
        } finally {
            returnResource(jedis);
        }
        return obj;
    }

    /**
     * 普通缓存放入
     * @param key 键
     * @param value 值
     * @return true成功 false失败
     */
    public boolean set(String key,Object value) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (jedis != null) {
                jedis.set(key, JSONObject.toJSONString(value));
            }
            return true;
        } catch (Exception e) {
            LogUtil.exception(RedisService.class, "Redis缓存设置" + key + "-" + value + "出错!", e);
            return false;
        } finally {
            returnResource(jedis);
        }
    }

    /**
     * 普通缓存放入并设置时间
     * @param key 键
     * @param value 值
     * @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
     * @return true成功 false 失败
     */
    public boolean set(String key,Object value,long time){
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (jedis != null) {
                jedis.set(key, JSONObject.toJSONString(value));
                jedis.expire(key, (int) time);
            }
            return true;
        } catch (Exception e) {
            LogUtil.exception(RedisService.class, "Redis缓存设置" + key + "-" + value + "出错!", e);
            return false;
        } finally {
            returnResource(jedis);
        }
    }

    //============================set=============================
    /**
     * 根据key获取Set中的所有值
     * @param key 键
     * @return
     */
    public Set<Object> sGet(String key){
        Jedis jedis = null;
        Set<Object> set = null;
        try {
            jedis = jedisPool.getResource();
            Set<String> strSet = jedis.smembers(key);
            if (strSet !=null && !strSet.isEmpty()) {
                set = new HashSet<Object>();
                for (String str : strSet) {
                    Object obj = JSONObject.parse(str);
                    set.add(obj);
                }
            }
        } catch (Exception e) {
            LogUtil.exception(RedisService.class, "获取" + key + "出错!", e);
        } finally {
            returnResource(jedis);
        }
        return set;
    }

    /**
     * 将set数据放入缓存
     * @param key 键
     * @param time 时间(秒)
     * @param values 值 可以是多个
     * @return 成功个数
     */
    public long sSetAndTime(String key,long time,Object...values) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            if (values != null && values.length>0) {
                String[] strarrays = new String[values.length];
                for (int i = 0; i < values.length; i++) {
                    strarrays[i] = JSONObject.toJSONString(values[i]);
                }
                Long count = jedis.sadd(key, strarrays);
                if(time>0) expire(key, time);
                return count;
            }
        } catch (Exception e) {
            return 0;
        } finally {
            returnResource(jedis);
        }
        return 0;
    }

    //================================zSet================================

    /**
     * 将数据放入set缓存
     * @param key 键
     * @param value 值
     * @param score 排序分数
     */
    public <T> boolean zSet(String key, T value ,double score) {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            if (jedis != null) {
                jedis.zadd(key, score, JSONObject.toJSONString(value));
            }
            return true;
        } catch (Exception e) {
            LogUtil.exception(RedisService.class, "Redis缓存设置" + key + "-" + value + "出错!", e);
            return false;
        } finally {
            returnResource(jedis);
        }
    }
    /**
     *
    * 返回键k的从start-end之间的数据。(从大到小排序从0开始)
    * @param
    * @return
    * @auther yaotenghui
    * @date 2018/5/17 15:22
    */
    public <T> Set<T> reverseRange(String key, long start, long end, Class<T> resultType){
        Jedis jedis = null;
        Set<T> set = null;
        try {
            jedis = jedisPool.getResource();
            Set<String> strSet = jedis.zrevrange(key,start,end);
            if (strSet !=null && !strSet.isEmpty()) {
                set = new HashSet<T>();
                for (String str : strSet) {
                    set.add(JSON.toJavaObject(JSON.parseObject(str), resultType));
                }
            }
        } catch (Exception e) {
            LogUtil.exception(RedisService.class, "获取" + key + "出错!", e);
        } finally {
            returnResource(jedis);
        }
        return set;
    }

    /**
     *
     * 返回键k的从start-end之间的数据。(从大到小排序从0开始)
     * @param
     * @return
     * @auther wanjiadong
     * @date 2018/6/23 15:22
     */
    public <T> List<T> reverseRangeToList(String key, long start, long end, Class<T> resultType){
        Jedis jedis = null;
        List<T> list = null;
        try {
            jedis = jedisPool.getResource();
            Set<String> strSet = jedis.zrevrange(key,start,end);
            if (strSet !=null && !strSet.isEmpty()) {
                list = new ArrayList<T>(strSet.size());
                for (String str : strSet) {
                    list.add(JSON.toJavaObject(JSON.parseObject(str), resultType));
                }
            }
        } catch (Exception e) {
            LogUtil.exception(RedisService.class, "获取" + key + "出错!", e);
        } finally {
            returnResource(jedis);
        }
        return list;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

41摄氏度男

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

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

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

打赏作者

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

抵扣说明:

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

余额充值