redis 在实际项目中的使用-运用篇(java-jedis)(三)

工程(环境window10,gradle-6.8.3版本,编辑器IntelliJ IDEA 2019.3.4,jedis的版本是3.8.0)

        上两节我们对于redis做了简单的讲解,接下来就jedis库的使用直接实现操作代码,为了兼顾redis集群和非集群实现,首先实现通用接口,然后具体实现子类分别完成。

使用到插件:

        lombok ,请自行安装

在build.gralde文件中引入依赖库:

implementation 'com.alibaba:fastjson:1.2.78'
implementation group: 'org.apache.commons', name: 'commons-lang3', version: '3.12.0'
implementation group: 'redis.clients', name: 'jedis', version: '3.8.0'

 依赖库地址

        https://mvnrepository.com/

1、通用接口类

import java.util.List;
import java.util.Map;
import java.util.Set;


public interface IJedisController {

    public  void Init(String data);



    /**
     * 添加sorted set
     *
     * @param key
     * @param value
     * @param score
     */
    public void zadd(String key, String value, double score);

    /**
     * 返回指定位置的集合元素,0为第一个元素,-1为最后一个元素
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<String> zrange(String key, int start, int end);

    /**
     * 获取给定区间的元素,原始按照权重由高到低排序
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<String> zrevrange(String key, int start, int end);

    /**
     * 添加对应关系,如果对应关系已存在,则覆盖
     *
     * @param key
     * @param map 对应关系
     * @return 状态,成功返回OK
     */
    public String hmset(String key, Map<String, String> map);

    /**
     * 向List头部追加记录
     *
     * @param key
     * @param value
     * @return 记录总数
     */
    public long rpush(String key, String value);





    /**
     * 删除
     *
     * @param key
     * @return
     */
    public long del(String key);

    /**
     * 从集合中删除成员
     * @param key
     * @param value
     * @return 返回1成功
     * */
    public long zrem(String key, String... value);

    public void saveValueByKey(int dbIndex, byte[] key, byte[] value, long expireTime) throws Exception;

    public byte[] getValueByKey(int dbIndex, byte[] key) throws Exception;

    public void deleteByKey(int dbIndex, byte[] key) throws Exception;

    /**
     * 获取总数量
     * @param key
     * @return
     */
    public long zcard(String key);

    /**
     * 是否存在KEY
     * @param key
     * @return
     */
    public boolean exists(String key);

    /**
     * 重命名KEY
     * @param oldKey
     * @param newKey
     * @return
     */
    public String rename(String oldKey, String newKey);

    /**
     * 设置失效时间
     * @param key
     * @param seconds
     */
    public void expire(String key, long seconds);
    /**
     * 删除失效时间
     * @param key
     */
    /**
     * 删除失效时间
     * @param key
     */
    public void persist(String key);

    /**
     * 添加一个键值对,如果键存在不在添加,如果不存在,添加完成以后设置键的有效期
     * @param key
     * @param value
     * @param timeOut
     */
    public void setnxWithTimeOut(String key,String value,long timeOut);

    /**
     * 返回指定key序列值
     * @param key
     * @return
     */
    public long incr(String key);

    /**
     * 获取当前时间
     * @return 秒
     */
    public long currentTimeSecond();


    /**
     * 设置数据
     * @param key
     * @param value
     * @return
     */

    public String set(final String key, final String value);


    public  String get(final  String key);

    public  Map<String, String> hgetAll(String key);

    public  void close();

}

 

2、非集群配置类

        在改该类中用了lombok插件和lang3、Json库,lombok插件可以非常方便打印日志信息,只需在类的声明处加上@slf4j注解即可,lang3库是对于异常日志时,能够将日志信息排版输出到日志文件中,这两个可以去掉,lambok插件的安装这里就不做阐述

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.exception.ExceptionUtils;;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.exceptions.JedisDataException;

import java.util.List;
import java.util.Map;
import java.util.Set;


@Slf4j
public class JedisOneController implements IJedisController {


    JedisPool mRedisPool;
    JedisPoolConfig mConfig;
    JSONObject mJson = null;

    public void Init(String  data)
    {
        try
        {

            
            mJson = JSONObject.parseObject(data);
            if (mJson == null)
                return;

            mConfig = new JedisPoolConfig();
            //控制一个pool可分配多少个jedis实例,通过pool.getResource()来获取;
            //如果赋值为-1,则表示不限制;如果pool已经分配了maxActive个jedis实例,则此时pool的状态为exhausted(耗尽)。
            mConfig.setMaxTotal(mJson.getInteger("maxTotal"));
            //控制一个pool最多有多少个状态为idle(空闲的)的jedis实例。
            mConfig.setMaxIdle(mJson.getInteger("maxIdle"));
            //表示当borrow(引入)一个jedis实例时,最大的等待时间,如果超过等待时间,则直接抛出JedisConnectionException;
            mConfig.setMaxWaitMillis(mJson.getInteger("maxWaitMillis"));
            //在borrow一个jedis实例时,是否提前进行validate操作;如果为true,则得到的jedis实例均是可用的;
            mConfig.setTestOnBorrow(mJson.getBoolean("testOnBorrow"));

            mRedisPool = new JedisPool(mConfig, mJson.getString("host")
                    , mJson.getInteger("port")
                    , mJson.getInteger("timeout")
                    , mJson.getString("pass"));


        }
        catch (Exception e)
        {
            e.printStackTrace();
        }



    }

    /**
     * 回收jedis(放到finally中)
     *
     * @param jedis
     */
    private void returnJedis(Jedis jedis) {
        if (null != jedis) {
            jedis.close();
        }
    }

    /**
     * 添加sorted set
     *
     * @param key
     * @param value
     * @param score
     */
    public void zadd(String key, String value, double score) {
        Jedis jedis = getJedis();
        try {
            jedis.zadd(key, score, value);
        }catch (JedisDataException e)
        {
            log.error(ExceptionUtils.getStackTrace(e));
        }
        returnJedis(jedis);
    }

    /**
     * 返回指定位置的集合元素,0为第一个元素,-1为最后一个元素
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<String> zrange(String key, int start, int end) {
        Jedis jedis = getJedis();
        Set<String> set = jedis.zrange(key, start, end);
        returnJedis(jedis);
        return set;
    }

    /**
     * 获取给定区间的元素,原始按照权重由高到低排序
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<String> zrevrange(String key, int start, int end) {
        Jedis jedis = getJedis();
        Set<String> set = jedis.zrevrange(key, start, end);
        returnJedis(jedis);
        return set;
    }

    /**
     * 添加对应关系,如果对应关系已存在,则覆盖
     *
     * @param key
     * @param map 对应关系
     * @return 状态,成功返回OK
     */
    public String hmset(String key, Map<String, String> map) {
        Jedis jedis = getJedis();
        String s = jedis.hmset(key, map);
        returnJedis(jedis);
        return s;
    }

    @Override
    public Map<String, String> hgetAll(String key) {
        Jedis jedis = getJedis();
        Map<String,String> map= jedis.hgetAll(key);
        returnJedis(jedis);
        return map;
    }

    /**
     * 向List头部追加记录
     *
     * @param key
     * @param value
     * @return 记录总数
     */
    public long rpush(String key, String value) {
        Jedis jedis = getJedis();
        long count = jedis.rpush(key, value);
        returnJedis(jedis);
        return count;
    }

    /**
     * 向List头部追加记录
     *
     * @param key
     * @param value
     * @return 记录总数
     */
    private long rpush(byte[] key, byte[] value) {
        Jedis jedis = getJedis();
        long count = jedis.rpush(key, value);
        returnJedis(jedis);
        return count;
    }

    /**
     * 删除
     *
     * @param key
     * @return
     */
    public long del(String key) {
        Jedis jedis = getJedis();
        long s = jedis.del(key);
        returnJedis(jedis);
        return s;
    }

    /**
     * 从集合中删除成员
     * @param key
     * @param value
     * @return 返回1成功
     * */
    public long zrem(String key, String... value) {
        Jedis jedis = getJedis();
        long s = jedis.zrem(key, value);
        returnJedis(jedis);
        return s;
    }

    public void saveValueByKey(int dbIndex, byte[] key, byte[] value, long expireTime)
            throws Exception {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            jedis.set(key, value);
            if (expireTime > 0)
                jedis.expire(key, expireTime);
        } catch (Exception e) {
            throw e;
        } finally {
            returnResource(jedis);
        }
    }

    public byte[] getValueByKey(int dbIndex, byte[] key) throws Exception {
        Jedis jedis = null;
        byte[] result = null;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            result = jedis.get(key);
        } catch (Exception e) {
            throw e;
        } finally {
            returnResource(jedis);
        }
        return result;
    }

    public void deleteByKey(int dbIndex, byte[] key) throws Exception {
        Jedis jedis = null;
        try {
            jedis = getJedis();
            jedis.select(dbIndex);
            jedis.del(key);
        } catch (Exception e) {
            throw e;
        } finally {
            returnResource(jedis);
        }
    }

    public void returnResource(Jedis jedis/*, boolean isBroken*/) {
        if (jedis == null)
            return;
        //if (isBroken)
        //jedisPool.returnBrokenResource(jedis);
        jedis.close();
        //else
        //jedisPool.returnResource(jedis);
        //jedis.close();
    }

    /**
     * 获取总数量
     * @param key
     * @return
     */
    public long zcard(String key) {
        Jedis jedis = getJedis();
        long count = jedis.zcard(key);
        returnJedis(jedis);
        return count;
    }

    /**
     * 是否存在KEY
     * @param key
     * @return
     */
    @Override
    public boolean exists(String key) {
        Jedis jedis = getJedis();
        try {
            boolean exists = jedis.exists(key);
            return exists;
        }catch (JedisDataException e)
        {
            log.error(ExceptionUtils.getStackTrace(e));

        }
        finally {
            returnJedis(jedis);
        }
        return false;
    }

    /**
     * 重命名KEY
     * @param oldKey
     * @param newKey
     * @return
     */
    @Override
    public String rename(String oldKey, String newKey) {
        Jedis jedis = getJedis();
        try {
            String result = jedis.rename(oldKey, newKey);
            return result;
        }catch (JedisDataException e)
        {
            log.error(ExceptionUtils.getStackTrace(e));
        }finally {
            returnJedis(jedis);
        }
        return "";
    }

    @Override
    public String get(String key) {
        Jedis jedis = getJedis();
        String result = jedis.get(key);
        returnJedis(jedis);
        return result;
    }

    /**
     * 设置失效时间
     * @param key
     * @param seconds
     */
    public void expire(String key, long seconds) {
        Jedis jedis = getJedis();
        jedis.expire(key, seconds);
        returnJedis(jedis);
    }

    /**
     * 删除失效时间
     * @param key
     */
    public void persist(String key) {
        Jedis jedis = getJedis();
        jedis.persist(key);
        returnJedis(jedis);
    }

    /**
     * 添加一个键值对,如果键存在不在添加,如果不存在,添加完成以后设置键的有效期
     * @param key
     * @param value
     * @param timeOut
     */
    public void setnxWithTimeOut(String key,String value,long timeOut){
        Jedis jedis = getJedis();
        if(0!=jedis.setnx(key, value)){
            jedis.expire(key, timeOut);
        }
        returnJedis(jedis);
    }

    /**
     * 返回指定key序列值
     * @param key
     * @return
     */
    public long incr(String key){
        Jedis jedis = getJedis();
        long l = jedis.incr(key);
        returnJedis(jedis);
        return l;
    }

    /**
     * 获取当前时间
     * @return 秒
     */
    @SuppressWarnings("unchecked")
    public long currentTimeSecond(){
        Long l = 0l;
        Jedis jedis = getJedis();
        Object obj = jedis.eval("return redis.call('TIME')",0);
        if(obj != null){
            List<String> list = (List<String>)obj;
            l = Long.valueOf(list.get(0));
        }
        returnJedis(jedis);
        return l;
    }
    private Jedis getJedis() {
        return mRedisPool.getResource();
    }


    @Override
    public String set(String key, String value) {
        Jedis jedis = getJedis();

        String result = jedis.set(key, value);
        returnJedis(jedis);
        return result;

    }

    @Override
    public void close() {

        mRedisPool.close();

    }
}

 

3、redis集群实现类

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.JedisCluster;
import redis.clients.jedis.JedisPoolConfig;

import java.util.*;


public class JedisClusterController implements   IJedisController {


    JedisCluster mJedisCluster;

    JSONObject mJson;

    /**
     * 初始化redis集群信息,data json格式
     */

    public  void Init(String data )
    {
        try {
            if (data == null)
                return;

            mJson = JSONObject.parseObject(data);
            Set<HostAndPort> hostPortSet = new HashSet<>();
            JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
            // 最大空闲连接数, 默认8个
            jedisPoolConfig.setMaxIdle(mJson.getInteger("maxIdle"));
            // 最大连接数, 默认8个
            jedisPoolConfig.setMaxTotal(mJson.getInteger("maxTotal"));
            //最小空闲连接数, 默认0
            jedisPoolConfig.setMinIdle(mJson.getInteger("minIdle",0));
            // 获取连接时的最大等待毫秒数(如果设置为阻塞时BlockWhenExhausted),如果超时就抛异常, 小于零:阻塞不确定的时间,  默认-1
            jedisPoolConfig.setMaxWaitMillis(mJson.getInteger( "maxWaitMillis")); // 设置2秒
            //对拿到的connection进行validateObject校验
            jedisPoolConfig.setTestOnBorrow(mJson.getBoolean(mJson, "testOnBorrow"));

            String[] defaultIp = new String[0];
            String[] ipArray = mJson.getJSONArray( "ip");

            Set<HostAndPort> hostset = new HashSet<>();

            for (int i = 0; i < ipArray.length; i++) {
                String[] host = ipArray[i].split(":");
                try {
                    if (host.length != 2) {

                        throw new RuntimeException("Error occure when Init JedisCluster=" + String.format("%d", i));
                    }
                    HostAndPort ip = new HostAndPort(host[0], Integer.parseInt(host[1]));
                    hostset.add(ip);
                } catch (Exception e) {
                    return;
                }
            }
            mJedisCluster = new JedisCluster(hostset, jedisPoolConfig);
        }
        catch (Exception e)
        {
            e.printStackTrace();
            return;

        }

    }

    private  Boolean ContainIp(Set<HostAndPort> hostset,HostAndPort ip)
    {
        Iterator<HostAndPort> itr = hostset.iterator();
        while(itr.hasNext())
        {
            HostAndPort h = itr.next();
            if(h.equals(ip))
                return true;
        }
        return false;
    }

    /**
     * 获得键对应的值
     * @param key
     * @return
     */
    public byte[] get(byte[] key){

        return mJedisCluster.get(key);
    };

    /**
     * 获得键对应的值
     * @param key
     * @return
     */
    public String get(String key){

        return mJedisCluster.get(key);
    };

    /**
     * 设置键值
     * @param key
     * @param value
     * @return
     */
    public String set(byte[] key, byte[] value){

        return mJedisCluster.set(key, value);
    }


    /**
     * 设置键值
     * @param key
     * @param value
     * @return
     */
    public String set(String key, String value){

        return mJedisCluster.set(key, value);
    }

    /**
     * 是否存在KEY
     * @param key
     * @return
     */
    public boolean exists(String key)
    {

        return mJedisCluster.exists(key);
    }

    /**
     * 添加sorted set
     *
     * @param key
     * @param value
     * @param score
     */
    public void zadd(String key, String value, double score)
    {
        mJedisCluster.zadd(key, score, value);
    }

    /**
     * 返回指定位置的集合元素,0为第一个元素,-1为最后一个元素
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<String> zrange(String key, int start, int end)
    {
        Set<String> strings = mJedisCluster.zrange(key, start, end);
        return strings;
    }

    /**
     * 获取给定区间的元素,原始按照权重由高到低排序
     * @param key
     * @param start
     * @param end
     * @return
     */
    public Set<String> zrevrange(String key, int start, int end)
    {
        Set<String> strings= mJedisCluster.zrevrange(key, start, end);
        return strings;
    }

    /**
     * 添加对应关系,如果对应关系已存在,则覆盖
     *
     * @param key
     * @param map 对应关系
     * @return 状态,成功返回OK
     */
    public String hmset(String key, Map<String, String> map)
    {
        String s = mJedisCluster.hmset(key, map);
        return s;
    }

    /**
     * 向List头部追加记录
     *
     * @param key
     * @param value
     * @return 记录总数
     */
    public long rpush(String key, String value)
    {
        long count = mJedisCluster.rpush(key, value);
        return count;
    }

    /**
     * 向List头部追加记录
     *
     * @param key
     * @param value
     * @return 记录总数
     */
    public long rpush(byte[] key, byte[] value)
    {
        long count = mJedisCluster.rpush(key, value);
        return count;
    }

    /**
     * 删除
     *
     * @param key
     * @return
     */
    public long del(String key)
    {
        long s = mJedisCluster.del(key);
        return s;
    }

    /**
     * 从集合中删除成员
     * @param key
     * @param value
     * @return 返回1成功
     * */
    public long zrem(String key, String... value)
    {
        long s = mJedisCluster.zrem(key, value);
        return s;
    }

    public void saveValueByKey(int dbIndex, byte[] key, byte[] value, long expireTime)throws Exception
    {
        try {
            mJedisCluster.set(key, value);
            if (expireTime > 0)
                mJedisCluster.expire(key, (int)expireTime);
        } catch (Exception e) {
            throw e;
        }
    }

    public byte[] getValueByKey(int dbIndex,byte[] key) throws Exception
    {
        byte[] result = null;
        try {
            result = mJedisCluster.get(key);
        } catch (Exception e) {
            throw e;
        }
        return result;
    }

    public void deleteByKey(int dbIndex, byte[] key) throws Exception
    {
        try {
            mJedisCluster.del(key);
        } catch (Exception e) {
            throw e;
        }
    }


    /**
     * 获取总数量
     * @param key
     * @return
     */
    public long zcard(String key)
    {
        long count = mJedisCluster.zcard(key);
        return count;
    }


    /**
     * 重命名KEY
     * @param oldKey
     * @param newKey
     * @return
     */
    public String rename(String oldKey, String newKey)
    {
        String result = mJedisCluster.rename(oldKey, newKey);
        return result;
    }

    /**
     * 设置失效时间
     * @param key
     * @param seconds
     */
    public void expire(String key, long seconds)
    {
        mJedisCluster.expire(key, seconds);
    }

    /**
     * 删除失效时间
     * @param key
     */
    public void persist(String key)
    {
        mJedisCluster.persist(key);
    }

    /**
     * 添加一个键值对,如果键存在不在添加,如果不存在,添加完成以后设置键的有效期
     * @param key
     * @param value
     * @param timeOut
     */
    public void setnxWithTimeOut(String key,String value,long timeOut){
        if(0!=mJedisCluster.setnx(key, value)){
            mJedisCluster.expire(key, timeOut);

        }
    }

    @Override
    public long incr(String key) {

        long l = mJedisCluster.incr(key);
        return l;

    }

    /**
     * 返回指定key序列值
     * @param key
     * @return
     */


    @Override
    public Map<String, String> hgetAll(String key) {
        return mJedisCluster.hgetAll(key);
    }

    /**
     * 获取当前时间
     * @return 秒
     */
    @SuppressWarnings("unchecked")
    public long currentTimeSecond()
    {
        Long l = 0l;
        Object obj = mJedisCluster.eval("return redis.call('TIME')",0);

        if(obj==null)
            return l;

        try {

            List<String> list = (List<String>) obj;
            l = Long.valueOf(list.get(0));
        }catch ( ClassCastException e )
        {
            e.printStackTrace();
        }
        return 0l;
    }

    @Override
    public void close() {
        if(mJedisCluster!=null)
            mJedisCluster.close();
    }

    public static void main(String[] args) {

        IJedisController controller = new JedisClusterController();

        JSONObject json = new JSONObject();
        JSONArray jsonArray = new JSONArray();
        jsonArray.add("192.168.1.35:6379");
//             jsonArray.add("192.168.1.35:6380");
//             jsonArray.add("192.168.1.35:6381");
//             jsonArray.add("192.168.1.35:6382");
//             jsonArray.add("192.168.1.35:6383");
//             jsonArray.add("192.168.1.35:6384");
        json.put("ip",jsonArray);
        controller.Init(json.toString());


        controller.set("test","hahah");
        if(controller.exists("test"))
        {
            System.err.println(controller.get("test"));
        }


        Map<String,String> map = new HashMap<>();


        map.put("1","1");
        map.put("2","2");
        controller.hmset("testMap",map);

        Map<String,String> map1 = controller.hgetAll("testMap");


        System.err.println(map1);

    }
}

对于此,jedis在Java项目中的实现就基本完成。

注意:

        不同的jedis版本的API接口会有少量的差异化,这也是我为什么会把编辑环境和运用环境的版本信息同步给大家的原因

未完待续。

        下一节内容是对于springboot项目中引入redis的代码实现

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值