jedis 調用redis工具類

redis(jedis)工具類實例:集羣模式和單機模式java

在寫redis工具類以前,咱們首先須要知道如何讀取redis配置文件redis

一、集羣模式工具類apache

package com.wonddream.utils;工具

import java.util.HashSet;測試

import java.util.Set;ui

import redis.clients.jedis.HostAndPort;.net

import redis.clients.jedis.JedisCluster;對象

import org.apache.commons.logging.Log;ip

import org.apache.commons.logging.LogFactory;字符串

public class JedisClusterUtil {

    private static final Log logger = LogFactory.getLog(JedisClusterUtil.class);

    private static Set<HostAndPort> jedisClusterNodes = new HashSet<HostAndPort>();

    private static JedisCluster jedisCluster = null;

    /**

     * 初始化jedisCluster對象

     */

    static {

        try {

            jedisCluster = reloadJedisCluster();

        } catch (Exception e) {

            logger.error(e.getMessage(), e);

        }

    }

    /**

     * 集羣模式

     * 獲取JedisCluster對象

     * @return

     * @throws Exception

     */

    public static JedisCluster getJedisCluster() throws Exception {

        if (jedisCluster == null) {

            synchronized (JedisClusterUtil.class) {

                jedisCluster = reloadJedisCluster();

            }

        }

        return jedisCluster;

    }

    /**

     * 集羣模式

     * 獲取JedisCluster方法

     * @return

     * @throws Exception

     */

    public static JedisCluster reloadJedisCluster() throws Exception {

        logger.info("初始化實體");

        JedisCluster cluster;

        String redisAddrCfg =     

        PropertiesUtil.getString("redis.address","config/redisConfig");

        logger.info("******redis集羣配置:"+redisAddrCfg);

        if (StringUtil.isEmpty(redisAddrCfg) || redisAddrCfg.split(",").length == 0) {

            throw new Exception("System.properties中REDIS_ADDR_CFG屬性爲空");

        }

        String[] addrs = redisAddrCfg.split(",");

        for (String addr : addrs) {

            String[] ipAndPort = addr.split(":");

            if (ipAndPort == null || ipAndPort.length != 2) {

                throw new Exception("System.properties中REDIS_ADDR_CFG屬性配置錯誤");

            }

            jedisClusterNodes.add(new HostAndPort(ipAndPort[0],

                  Integer.parseInt(ipAndPort[1])));

        }

        cluster = new JedisCluster(jedisClusterNodes, 2000, 6);

        return cluster;

    }

    /*

     * 測試

     */

public static void main(String[] args) throws Exception {

}

}

二、單機模式工具類

package com.wonddream.utils;

import redis.clients.jedis.Jedis;

import org.apache.commons.logging.Log;

import org.apache.commons.logging.LogFactory;

public class JedisUtil {

    private static final Log logger = LogFactory.getLog(JedisUtil.class);

    private static Jedis jedis = null;

    /**

     * 初始化jedis對象

     */

    static {

      try {

             jedis = reloadJedis();

         } catch (Exception e) {

             logger.error(e.getMessage(), e);

         }

    }     

    /**

     * 單機模式

     * 獲取Jedis對象

     * @return

     * @throws Exception

     */

    public static Jedis getJedis() throws Exception {

        if (jedis == null) {

            synchronized (JedisUtil.class) {

                jedis = reloadJedis();

            }

        }

        return jedis;

    }

    /**

     * 單機模式

     * 獲取Jedis方法

     * @return

     * @throws Exception

     */

    public static Jedis reloadJedis() throws Exception {

        logger.info("初始化實體");

        Jedis jedis;

        String redisAddrCfg = PropertiesUtil.getString("redis.address","config/redisConfig");

        logger.info("******redis單機配置:"+redisAddrCfg);

        if (StringUtil.isEmpty(redisAddrCfg) || redisAddrCfg.split(",").length == 0) {

            throw new Exception("System.properties中REDIS_ADDR_CFG屬性爲空");

        }

        String[] ipAndPort = redisAddrCfg.split(":");

        if (ipAndPort == null || (ipAndPort.length != 2 && ipAndPort.length != 3)) {

            throw new Exception("System.properties中REDIS_ADDR_CFG屬性配置錯誤");

        }

        jedis = new Jedis(ipAndPort[0], Integer.parseInt(ipAndPort[1]), 2000, 30);

        //若是使用這redis設置有密碼,則須要再次設置外匯返傭http://www.fx61.com/受權。個人redis配置格式:ip:port:password

        //使用者能夠根據本身的狀況自行調整

        if(ipAndPort.length == 3) {

         jedis.auth(ipAndPort[2]);

        }        

        return jedis;

    }

    /*

     * 測試

     */

public static void main(String[] args) throws Exception {

getJedis().setex("name", 2, "wangpenghui");

System.out.println(getJedis().get("name"));

Thread.sleep(3000);

System.out.println(getJedis().get("name"));

}

}

import org.slf4j.Logger;

import org.slf4j.LoggerFactory;

import redis.clients.jedis.Jedis;

public class JedisUtil {

    private static final Logger log = LoggerFactory.getLogger(DemoTest.class);

    

    /////////////////////////////////////////////////key操做

    /**

     * 刪除指定的key

     * @param key

     * @return

     */

    public static long del(String key){

        Jedis jedis =null;

        long res = -1;

        try {

            jedis = JedisPoolUtil.getJedis();

            res = jedis.del(key);

        } catch (Exception e) {

            e.printStackTrace();

            log.error("strSet {} error:{}",key ,e);

        } finally {

            JedisPoolUtil.release(jedis);

        }

        return  res;

    }

    /**

     * 字符串設置key-value-expire

     * @param key

     * @param value

     * @param expire 過時時間,值爲-1時永不過時

     * @return 成功返回OK

     */

    public static  String strSet(String key ,String value,int expire){

        Jedis jedis =null;

        String res = null;

        try {

            jedis = JedisPoolUtil.getJedis();

            res = jedis.set(key, value);

            if(expire != -1){

                jedis.expire(key ,expire);

            }

        } catch (Exception e) {

            e.printStackTrace();

            log.error("strSet {} error:{}",key ,e);

        } finally {

            JedisPoolUtil.release(jedis);

        }

        return  res;

    }

    ///////////////////////////////////////////string操做

    /**

     * 字符串設置key-value

     * @param key

     * @param value

     * @return 成功返回OK

     */

    public static  String strSet(String key ,String value){

        return strSet(key,value,-1);

    }

    /**

     * 根據key獲取字符串的值

     * @param key

     * @return

     */

    public static String strGet(String key){

        Jedis jedis =null;

        String res = null;

        try {

            jedis = JedisPoolUtil.getJedis();

            res = jedis.get(key);

        } catch (Exception e) {

            e.printStackTrace();

            log.error("strSet {} error:{}",key ,e);

        } finally {

            JedisPoolUtil.release(jedis);

        }

        return  res;

    }

    public static String strMset(String... keyValues){

        String res = null;

        Jedis jedis = null;

        try {

            jedis = JedisPoolUtil.getJedis();

            res = jedis.mset(keyValues);

        } catch (Exception e) {

            e.printStackTrace();

            log.error("strMset {} error:{}",keyValues ,e);

        } finally {

            JedisPoolUtil.release(jedis);

        }

        return  res;

    }

    public static List<String> strMget(String... keys){

        List<String> res = null;

        Jedis jedis = null;

        try {

            jedis = JedisPoolUtil.getJedis();

            res = jedis.mget(keys);

        } catch (Exception e) {

            e.printStackTrace();

            log.error("strMget {} error:{}",keys ,e);

        } finally {

            JedisPoolUtil.release(jedis);

        }

        return res;

    }

    /////////////////////////////////////////////////////////list操做

     /**

     * 從右邊開始往List中添加數據

     * @param key

     * @param values

     * @return 返回值爲添加到List中元素的個數

     */

    public static long listRpush(String key , String ... values){

        long res = -1;

        Jedis jedis = null;

        try {

            jedis = JedisPoolUtil.getJedis();

            res = jedis.rpush(key, values);

        } catch (Exception e) {

            e.printStackTrace();

            log.error("listRpush(): {} {},error:{}",key ,values,e);

        } finally {

            JedisPoolUtil.release(jedis);

        }

        return res;

    }

    /**

     * 返回key中從start到end之間的元素

     * @param key

     * @param start

     * @param end

     * @return

     */

    public static List<String> listLrange(String key,int start ,int end){

        List<String> res = null;

        Jedis jedis = null;

        try {

            jedis = JedisPoolUtil.getJedis();

            res = jedis.lrange(key,start,end);

        } catch (Exception e) {

            e.printStackTrace();

            log.error("listRpush(): {} {} {},error:{}",key ,start,end,e);

        } finally {

            JedisPoolUtil.release(jedis);

        }

        return res;

    }

    /////////////////hash操做

    public static long mapHset(String key, String field, String value) {

        long res = -1;

        Jedis jedis = null;

        try {

            jedis = JedisPoolUtil.getJedis();

            res = jedis.hset(key, field, value);

        } catch (Exception e) {

            e.printStackTrace();

            log.info("mapHset() {} {} {} , errors {}",key,field,value,e);

        } finally {

            JedisPoolUtil.release(jedis);

        }

        return res;

    }

    public static String mapHget(String key, String field) {

        String res = null;

        Jedis jedis = null;

        try {

            jedis = JedisPoolUtil.getJedis();

            res = jedis.hget(key, field);

        } catch (Exception e) {

            e.printStackTrace();

            log.info("mapHget() {} {} , errors {}",key,field,e);

        } finally {

            JedisPoolUtil.release(jedis);

        }

        return res;

    }

    public static String mapHmset(String key, Map<String, String> map) {

        String res = null;

        Jedis jedis = null;

        try {

            jedis = JedisPoolUtil.getJedis();

            res = jedis.hmset(key, map);

        } catch (Exception e) {

            e.printStackTrace();

            log.info("mapHmset() {} {} , errors {}",key,map,e);

        } finally {

            JedisPoolUtil.release(jedis);

        }

        return res;

    }

    public static List<String> mapHmget(String key, String... fields) {

        List<String> res = null;

        Jedis jedis = null;

        try {

            jedis = JedisPoolUtil.getJedis();

            res = jedis.hmget(key, fields);

        } catch (Exception e) {

            e.printStackTrace();

            log.info("mapHmget() {} {} , errors {}",key,fields,e);

        } finally {

            JedisPoolUtil.release(jedis);

        }

        return res;

    }

//......

}

工具類測試代碼

public class JedisUtilTest {

//////////////////////////////key 操做

    @Test

    public void del(){

        long res = JedisUtil.del("list");

        System.out.println(res);

    }

    //////////////////////////////string 操做

    @Test

    public void strSet1() {

        String res = JedisUtil.strSet("k2", "v2",60);

        System.out.println(res);

    }

    @Test

    public void strSet2() {

        String res = JedisUtil.strSet("k3", "v3");

        System.out.println(res);

    }

    @Test

    public void strGet() {

        String k1 = JedisUtil.strGet("k1");

        System.out.println(k1);

    }

    @Test

    public void strMset(){

        String res = JedisUtil.strMset("k1", "v1", "k2", "v2");

        System.out.println(res);

    }

    @Test

    public void strMget(){

        List<String> res = JedisUtil.strMget("k1", "k2");

        System.out.println(res);

    }

    //////////////////////////////list 操做

    @Test

    public void listRpush(){

        long res = JedisUtil.listRpush("list", "aa", "cc", "dd", "bb", "aa");

        System.out.println(res);

    }

    @Test

    public void listLrange(){

        List<String> res = JedisUtil.listLrange("list", 0, -1);

        for (String item : res) {

            System.out.println(item);

        }

    }

    /////////////////hash操做

     @Test

    public void mapHset(){

        long res = JedisUtil.mapHset("map", "name", "zhangsan");

        System.out.println(res);

    }

    @Test

    public void mapHget(){

        String res = JedisUtil.mapHget("map", "name");

        System.out.println(res);

    }

    @Test

    public void mapHmset(){

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

        map.put("name","zhangsan");

        map.put("age","18");

        map.put("birth","1999-09-21");

        String res = JedisUtil.mapHmset("map",map);

        System.out.println(res);

    }

    @Test

    public void mapHmget(){

        List<String> res = JedisUtil.mapHmget("map", "name","age","birth");

        System.out.println(res);

    }

//......

}

相關文章
相關標籤/搜索