Redis简洁使用

一、pom文件添加redis依赖
<!--redis-->
<dependency>
  <groupId>redis.clients</groupId>
  <artifactId>jedis</artifactId>
  <version>2.6.1</version>
</dependency>
<!--apache commons包-->
<dependency>
  <groupId>org.apache.commons</groupId>
  <artifactId>commons-lang3</artifactId>
  <version>3.2.1</version>
</dependency>
二、编写reids资源文件

文件内容:
 
COMMON.REDIS.ISSHARE =false
COMMON.REDIS.POOL.MAXIDLE=5
COMMON.REDIS.POOL.MAXTOTAL=100
COMMON.REDIS.POOL.MINIDLE=2
COMMON.REDIS.POOL.MINWAIT=1
COMMON.REDIS.POOL.TESTONBORROW=true
COMMON.REDIS.POOL.TESTONRETURN=true
COMMON.REDIS.POOL.TIMEOUT=6000
COMMON.REDIS.SINGLE.IP=127.0.0.0:6486 IP地址和端口
COMMON.REDIS.PASSWORD=密码

前面加COMMON是因为程序中前缀为COMMON,加前缀是为了分开发、测试、正式环境得redis服务器不同,前缀传参可以不同(实现扩展)
三、ConfigLoad文件
package Redis;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Properties;
import java.util.regex.Pattern;

/**
 * Created on 2018/4/2.
 */
public class ConfigLoad { public ConfigLoad() {
}

    public static void configLoadForProPerties(String configFilePath) {
        try {
            //加载redis.properties,文件路径为config
            String path = "config";
            //如果插入参数有configFilePath文件路径不为空,就按传入参数路径加载
            if(configFilePath != null && !configFilePath.trim().isEmpty()) {
                path = configFilePath;
            }

            if(!path.trim().startsWith("/") && !Pattern.compile("(^//.|^/|^[a-zA-Z])?:?/.+(/$)?").matcher(path).matches()) {
                path = ConfigLoad.class.getResource("/").getPath() + path;
            }

            refreshFileList(path);
        } catch (Exception var2) {
            var2.printStackTrace();
        }

    }

    private static void refreshFileList(String fileAbsolutePath) {
        try {
            File file = null;
            if(!fileAbsolutePath.trim().startsWith("/") && !Pattern.compile("(^//.|^/|^[a-zA-Z])?:?/.+(/$)?").matcher(fileAbsolutePath).matches()) {
                file = new File(ConfigLoad.class.getResource("/").getPath() + fileAbsolutePath);
            } else {
                file = new File(fileAbsolutePath);
            }

            if(file.exists()) {
                readFile(file);
            }
        } catch (Exception var2) {
            var2.printStackTrace();
        }

    }

    private static void readFile(File file) {
    //如果file是文件路径得话就按路径加载
        if(file.isDirectory()) {
            File[] var1 = file.listFiles();
            int var2 = var1.length;

            for(int var3 = 0; var3 < var2; ++var3) {
                File subFile = var1[var3];
                readFile(subFile);
            }
        } else {
            //非文件路径就在原来得config路径上再加路径properties。形成config/properties路径
            String tempName = file.getName();
            if(tempName.trim().toLowerCase().endsWith("properties")) {
                properties2Map(readConfigFile(file));
            }
        }

    }

    private static Properties readConfigFile(File File) {
        Properties prop = new Properties();
        BufferedInputStream is = null;

        try {
            is = new BufferedInputStream(new FileInputStream(File));
            prop.load(is);
        } catch (Exception var12) {
            var12.printStackTrace();
        } finally {
            try {
                is.close();
            } catch (IOException var11) {
                var11.printStackTrace();
            }

        }

        return prop;
    }

    private static void properties2Map(Properties prop) {
        try {
            ConfigCommon.setProperties(new HashMap(prop));
        } catch (Exception var2) {
            var2.printStackTrace();
        }

    }

    public static void main(String[] args) {
        ConfigCommon.print();
    }
}

四、ConfigCommon文件
package Redis;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

/**
 * Created on 2018/4/2.
 */
public class ConfigCommon {
    private String path;
    private static final Map<String, String> properties = new HashMap();

    public ConfigCommon() {
    }

    static {
        if(properties == null || properties.size() == 0) {
            //加载该文件时,传入redis.properties文件得路径

            //得到资源文件得路径
//            String configFilePath = ConfigCommon.class.getClassLoader().getResource("redis.properties").getPath();
            ConfigLoad.configLoadForProPerties("");
        }

    }

    public String getPath() {
        return this.path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public static void print() {
        Iterator var0 = properties.entrySet().iterator();

        while(var0.hasNext()) {
            Map.Entry<String, String> entry = (Map.Entry)var0.next();
            System.out.println((String)entry.getKey() + ":" + (String)entry.getValue());
        }

    }

    public static void setProperties(Map<String, String> map) {
        properties.putAll(map);
    }

    public static Map<String, String> getProperties() {
        return properties;
    }

    public static String setProperties(String K, String V) {
        return (String)properties.put(K, V);
    }

    public static Boolean getProperties(String K, Boolean defultV) {
        Boolean V = Boolean.valueOf(false);
        if(defultV != null) {
            V = defultV;
        }

        return properties.get(K) == null?V:Boolean.valueOf(((String)properties.get(K)).trim());
    }

    public static String getProperties(String K, String defultV) {
        String V = "";
        if(defultV != null) {
            V = defultV;
        }

        return properties.get(K) == null?V:((String)properties.get(K)).trim();
    }

    public static int getProperties(String K, int defultV) {
        return properties.get(K) == null?defultV:Integer.valueOf(((String)properties.get(K)).trim()).intValue();
    }

    public static String getString(String K, String defultV) {
        String V = "";
        if(defultV != null) {
            V = defultV;
        }

        return properties.get(K) == null?V:((String)properties.get(K)).trim();
    }

    public static Boolean getBoolean(String K, Boolean defultV) {
        Boolean V = Boolean.valueOf(false);
        if(defultV != null) {
            V = defultV;
        }

        return properties.get(K) == null?V:Boolean.valueOf(((String)properties.get(K)).trim());
    }

    public static String get(String K) {
        return (String)properties.get(K);
    }


}

五、RedisClient文件
package Redis;

import org.apache.commons.lang3.SerializationUtils;
import redis.clients.jedis.*;
import redis.clients.util.Pool;

import java.io.Serializable;
import java.util.*;

/**
 * Created on 2018/4/2.
 */
public class RedisClient {
    private Pool<?> redisPool = null;
    private static Jedis listener;

    public RedisClient(String prefix) {
        boolean isRegShared = ConfigCommon.getBoolean(prefix + ".REDIS.ISSHARE", Boolean.valueOf(false)).booleanValue();
        int maxidle = ConfigCommon.getProperties(prefix + ".REDIS.POOL.MAXIDLE", -1);
        int maxTotal = ConfigCommon.getProperties(prefix + ".REDIS.POOL.MAXTOTAL", -1);
        int minIdle = ConfigCommon.getProperties(prefix + ".REDIS.POOL.MINIDLE", -1);
        long maxWait = (long)ConfigCommon.getProperties(prefix + ".REDIS.POOL.MAXWAIT", -1) * 1000L;
        boolean testonrorrow = ConfigCommon.getBoolean(prefix + ".REDIS.POOL.TESTONBORROW", Boolean.valueOf(false)).booleanValue();
        boolean testonreturn = ConfigCommon.getBoolean(prefix + ".REDIS.POOL.TESTONRETURN", Boolean.valueOf(false)).booleanValue();
        int timeout = ConfigCommon.getProperties(prefix + ".REDIS.POOL.TIMEOUT", 5000);
        String password = ConfigCommon.get(prefix + ".REDIS.PASSWORD");
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxWaitMillis(maxWait);
        config.setMinIdle(minIdle);
        config.setMaxIdle(maxidle);
        config.setTestOnBorrow(testonrorrow);
        config.setTestOnReturn(testonreturn);
        if(isRegShared) {
            List<JedisShardInfo> list = new LinkedList();
            String shareKey = prefix + ".REDIS.SHARE";
            Iterator var15 = ConfigCommon.getProperties().entrySet().iterator();

            while(var15.hasNext()) {
                Map.Entry<String, String> entry = (Map.Entry)var15.next();
                String key = (String)entry.getKey();
                if(key != null && key.toString().startsWith(shareKey)) {
                    String ipPort = ((String)entry.getValue()).trim();
                    list.add(new JedisShardInfo(ipPort.split(":")[0].trim(), Integer.valueOf(ipPort.split(":")[1].trim()).intValue()));
                }
            }

            this.redisPool = new ShardedJedisPool(config, list);
        } else {
            String ipPort = ConfigCommon.getString(prefix + ".REDIS.SINGLE.IP", "127.0.0.1:6379").trim();
            this.redisPool = new JedisPool(config, ipPort.split(":")[0].trim(), Integer.valueOf(ipPort.split(":")[1].trim()).intValue(), timeout, password);
        }

    }

    public Pool<?> getPool() {
        return this.redisPool;
    }

    public void set(String key, String vaule) {
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            jedis.set(key, vaule);
        } catch (Exception var9) {
            var9.printStackTrace();
        } finally {
            jedis.close();
        }

    }

    public void set(byte[] key, byte[] vaule) {
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            jedis.set(key, vaule);
        } catch (Exception var9) {
            var9.printStackTrace();
        } finally {
            jedis.close();
        }

    }

    public void setEx(String key, int seconds, String value) {
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            jedis.setex(key, seconds, value);
        } catch (Exception var10) {
            var10.printStackTrace();
        } finally {
            jedis.close();
        }

    }

    public String get(String key) {
        String str = null;
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            str = jedis.get(key);
        } catch (Exception var9) {
            var9.printStackTrace();
        } finally {
            jedis.close();
        }

        return str;
    }

    public String hset(String mkey, String key, String value) {
        String str = null;
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            jedis.hset(mkey, key, value);
        } catch (Exception var11) {
            var11.printStackTrace();
        } finally {
            jedis.close();
        }

        return (String)str;
    }

    public String hget(String mkey, String key) {
        String str = null;
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            str = jedis.hget(mkey, key);
        } catch (Exception var10) {
            var10.printStackTrace();
        } finally {
            jedis.close();
        }

        return str;
    }

    public Map<String, String> hgetall(String mkey) {
        Map<String, String> map = null;
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            map = jedis.hgetAll(mkey);
        } catch (Exception var9) {
            var9.printStackTrace();
        } finally {
            jedis.close();
        }

        return map;
    }

    public void hsetall(String mkey, Map<String, Object> params) {
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            Iterator var5 = params.entrySet().iterator();

            while(var5.hasNext()) {
                Map.Entry<String, Object> entry = (Map.Entry)var5.next();
                jedis.hset(mkey, (String)entry.getKey(), entry.getValue().toString());
            }
        } catch (Exception var10) {
            var10.printStackTrace();
        } finally {
            jedis.close();
        }

    }

    public byte[] get(byte[] key) {
        byte[] str = null;
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            str = jedis.get(key);
        } catch (Exception var9) {
            var9.printStackTrace();
        } finally {
            jedis.close();
        }

        return str;
    }

    public String getAndDel(String key) {
        String str = null;
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            str = jedis.get(key);
            jedis.del(key);
        } catch (Exception var9) {
            var9.printStackTrace();
        } finally {
            jedis.close();
        }

        return str;
    }

    public void del(String key) {
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            jedis.del(key);
        } catch (Exception var8) {
            var8.printStackTrace();
        } finally {
            jedis.close();
        }

    }

    public void del(byte[] bytes) {
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            jedis.del(bytes);
        } catch (Exception var8) {
            var8.printStackTrace();
        } finally {
            jedis.close();
        }

    }

    public void hdel(String mkey, String... keys) {
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            jedis.hdel(mkey, keys);
        } catch (Exception var9) {
            var9.printStackTrace();
        } finally {
            jedis.close();
        }

    }

    public Boolean exists(String key) {
        Boolean re = null;
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            re = jedis.exists(key);
        } catch (Exception var9) {
            var9.printStackTrace();
        } finally {
            jedis.close();
        }

        return re;
    }

    public Set<String> keys(String pattern) {
        Set<String> keys = null;
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            keys = jedis.keys(pattern);
        } catch (Exception var9) {
            var9.printStackTrace();
        } finally {
            jedis.close();
        }

        return keys;
    }

    public boolean expire(String key, int seconds) {
        long re = 0L;
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            re = jedis.expire(key, seconds).longValue();
        } catch (Exception var11) {
            var11.printStackTrace();
        } finally {
            jedis.close();
        }

        return re == 1L;
    }

    public boolean expire(byte[] key, int seconds) {
        long re = 0L;
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            re = jedis.expire(key, seconds).longValue();
        } catch (Exception var11) {
            var11.printStackTrace();
        } finally {
            jedis.close();
        }

        return re > 0L;
    }

    public void setObj(String key, Serializable obj) {
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            jedis.set(key.getBytes(), SerializationUtils.serialize(obj));
        } catch (Exception var9) {
            var9.printStackTrace();
        } finally {
            jedis.close();
        }

    }

    public void zadd(String key, String value, double score) {
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            jedis.zadd(key, score, value);
        } catch (Exception var11) {
            var11.printStackTrace();
        } finally {
            jedis.close();
        }

    }

    public Set<Tuple> rangeByScoreWithScores(String key, double min, double max) {
        Jedis jedis = null;
        JedisPool pool = null;
        Set result = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            result = jedis.zrangeByScoreWithScores(key, min, max);
        } catch (Exception var13) {
            var13.printStackTrace();
        } finally {
            jedis.close();
        }

        return result;
    }

    public Set<String> rangeByScore(String key, double min, double max) {
        Jedis jedis = null;
        JedisPool pool = null;
        Set result = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            result = jedis.zrangeByScore(key, min, max);
        } catch (Exception var13) {
            var13.printStackTrace();
        } finally {
            jedis.close();
        }

        return result;
    }

    public <T> T getObj(String key, Class<T> clazz) {
        Jedis jedis = null;
        JedisPool pool = null;
        byte[] result = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            result = jedis.get(key.getBytes());
        } catch (Exception var10) {
            var10.printStackTrace();
        } finally {
            jedis.close();
        }

        return SerializationUtils.deserialize(result);
    }

    public void del(Set<String> keys) {
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            jedis.del((String[])keys.toArray(new String[0]));
        } catch (Exception var8) {
            var8.printStackTrace();
        } finally {
            jedis.close();
        }

    }

    public void setListener(JedisPubSub pubsub, String pattern) {
        Jedis jedis = null;
        JedisPool pool = null;

        try {
            pool = (JedisPool)this.redisPool;
            if(null == listener) {
                listener = pool.getResource();
            }

            listener.psubscribe(pubsub, new String[]{pattern});
        } catch (Exception var6) {
            var6.printStackTrace();
        }

    }

    public Long getZcount(String key, double min, double max) {
        Jedis jedis = null;
        JedisPool pool = null;
        Long result = null;

        try {
            pool = (JedisPool)this.redisPool;
            jedis = pool.getResource();
            result = jedis.zcount(key, min, max);
        } catch (Exception var13) {
            var13.printStackTrace();
        } finally {
            jedis.close();
        }

        return result;
    }
}

六、RedisUtil

package Redis;

/**
 * Created on 2018/4/2.
 */
public class RedisUtil {
    //COMMON是redis配置文件中得前缀
    public static final RedisClient common = new RedisClient("COMMON");

    public RedisUtil() {
    }
}
七、RedisTest
 
 
package Redis;

/**
 * Created on 2018/4/2.
 */
public class RedisTest {
    public static void main(String[] args) {
        RedisUtil.common.set("redisTest", "天天向上");

        System.out.println("------------------" + RedisUtil.common.get("redisTest"));
    }
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值