1. 程式人生 > >使用jedis連線呼叫redis,方式一:java code

使用jedis連線呼叫redis,方式一:java code

一、redis.properties檔案

# Redis settings
redis.host=ip
redis.port=6379
redis.pass=password
#客戶端超時時間單位是毫秒 預設是2000
redis.timeout=10000
redis.dbIndex=1
redis.dbIndex2=2
redis.CachingTime=900

#最大空閒數
redis.maxIdle=300
#最小空閒數
redis.minIdle=1
#連線池的最大資料庫連線數。設為0表示無限制,如果是jedis 2.4以後用redis.maxTotal
#redis.maxActive=600
#控制一個pool可分配多少個jedis例項,用來替換上面的redis.maxActive,如果是jedis 2.4以後用該屬性
redis.maxTotal=1000 #最大建立連線等待時間。如果超過此時間將接到異常。設為-1表示無限制。 redis.maxWaitMillis=3000 #連線的最小空閒時間 預設1800000毫秒(30分鐘) redis.minEvictableIdleTimeMillis=300000 #每次釋放連線的最大數目,預設3 redis.numTestsPerEvictionRun=1024 #逐出掃描的時間間隔(毫秒) 如果為負數,則不執行逐出執行緒, 預設-1 redis.timeBetweenEvictionRunsMillis=30000 #是否在從池中取出連線前進行檢驗,如果檢驗失敗,則從池中去除連線並嘗試取出另一個 redis.testOnBorrow=true
#返回性校驗 redis.testOnReturn=true #在空閒時檢查有效性, 預設false redis.testWhileIdle=true

二、java讀取redis.properties

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class RedisServerEnvironment
{
private static Properties redisMap = null; private static Logger logger = LoggerFactory.getLogger(RedisServerEnvironment.class); static { Properties properties = new Properties(); InputStream input = null; ClassLoader classLoader = RedisServerEnvironment.class.getClassLoader(); InputStream mapInput = null; try { mapInput = new FileInputStream(classLoader.getResource("properties/redis.properties").getFile()); redisMap = new Properties(); redisMap.load(mapInput); mapInput.close(); } catch (IOException e) { logger.error("No redis Map file!", e); } } public static Properties getWeatherMap() { return redisMap; } //static method for accessing context properties public static String getPropertyString(String name) { return ((String)redisMap.get(name)).trim(); } //static method for accessing context properties public static Integer getPropertyInteger(String name) { return Integer.valueOf(((String)redisMap.get(name)).trim()); } }

三、RedisUtil工具類

package com.bmw.boss.share.util.jedis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import redis.clients.jedis.*;
import redis.clients.jedis.params.geo.GeoRadiusParam;

import java.util.List;

/**
 * Created by qxr4383 on 2018/4/4.
 */
public class RedisUtilByCode {
    private static final Logger LOGGER = LoggerFactory.getLogger(RedisUtilByCode.class);

    private static JedisPool jedisPool = null;

    /**
     * 初始化Redis連線池
     */
    static {
        try {
            final String host =  RedisServerEnvironment.getPropertyString("redis.host");
            final Integer port = RedisServerEnvironment.getPropertyInteger("redis.port");
            final String auth = RedisServerEnvironment.getPropertyString("redis.pass");
            final Integer timeout = RedisServerEnvironment.getPropertyInteger("redis.timeout");
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(RedisServerEnvironment.getPropertyInteger("redis.maxTotal"));
            config.setMaxIdle( RedisServerEnvironment.getPropertyInteger("redis.maxIdle"));
            config.setMaxWaitMillis( RedisServerEnvironment.getPropertyInteger("redis.maxWaitMillis"));
            config.setTestOnBorrow(true);
            jedisPool = new JedisPool(config, host, port, timeout, auth, RedisServerEnvironment.getPropertyInteger("redis.dbIndex"));
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("RedisUtilByCode 初始化Redis連線池異常 : " + e);
        }
    }

    /**
     * Redis setNX 儲存字串 增加鎖資料
     * <p>
     * 返回0 -> key已存在,無法覆蓋值
     * 返回1 -> 插入成功
     * seconds   快取時間
     * @param key
     * @param value
     * @param seconds
     * @return
     */
    public static Long setNXData(String key, String value, Integer seconds) {
        Long ret = 0l;
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            ret = jedis.setnx(key, value);
            if (ret == 1 && seconds != null) {
                jedis.expire(key, seconds);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("RedisUtilByCode setNXData() : " + e);
        } finally {
            jedis.close();
        }
        return ret;
    }

    /**
     * Redis儲存字串
     *
     * @param key
     * @param value
     * @param seconds
     */
    public static void setData(String key, String value, Integer seconds) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.set(key, value);
            if (seconds != null) {
                jedis.expire(key, seconds);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("RedisUtilByCode setData() : " + e);
        } finally {
            jedis.close();
        }
    }

    /**
     * 獲取字串
     *
     * @param key
     * @return
     */
    public static String getData(String key) {
        Jedis jedis = null;
        String ret = "";
        try {
            jedis = jedisPool.getResource();
            ret = jedis.get(key);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("RedisUtilByCode getData() : " + e);
        } finally {
            jedis.close();
        }
        return ret;
    }

    /**
     * 刪除資料
     *
     * @param key
     */
    public static Long delData(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.del(key);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("RedisUtilByCode delData() : " + e);
        } finally {
            jedis.close();
        }
        return 0L;
    }

    /**
     * add list
     *
     * @param key
     * @param value
     * @param seconds
     */
    public static void addList(String key, String value, Integer seconds) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.rpush(key, value);
            if (seconds != null) {
                jedis.expire(key, seconds);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("RedisUtilByCode addList() : " + e);
        } finally {
            jedis.close();
        }
    }

    /**
     * 獲取list的長度
     *
     * @param key
     * @return
     */
    public static Long listLength(String key) {
        Jedis jedis = null;
        Long llen = 0l;
        try {
            jedis = jedisPool.getResource();
            llen = jedis.llen(key);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("RedisUtilByCode addList() : " + e);
        } finally {
            jedis.close();
        }
        return llen;
    }




    // add -> Set
    public static void addSet(String key, String value, Integer seconds) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.sadd(key, value);
            if (seconds != null) {
                jedis.expire(key, seconds);
            }
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("RedisUtilByCode addSet() : " + e);
        } finally {
            jedis.close();
        }
    }

    // get -> Set
//    public static Set<String> getSet(String key) {
//        Jedis jedis = null;
//        Set<String> set = Sets.newConcurrentHashSet();
//        try {
//            jedis = jedisPool.getResource();
//            set = jedis.smembers(key);
//        } catch (Exception e) {
//            e.printStackTrace();
//            LOGGER.error("RedisUtilByCode getSet() : " + e);
//        } finally {
//            jedis.close();
//        }
//        return set;
//    }

    // remove -> Set
    public static Long removeSet(String key, String members) {
        Jedis jedis = null;
        Long l = 0L;
        try {
            jedis = jedisPool.getResource();
            l = jedis.srem(key, members);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error("RedisUtilByCode getSet() : " + e);
        } finally {
            jedis.close();
        }
        return l;
    }


    // ----------------------------- GEO -----------------------------

    /**
     * add單個座標
     *
     * @param key
     * @param longitude 經度
     * @param latitude  緯度
     * @param member    唯一標識
     */
    public static Long geoadd(String key, double longitude, double latitude, String member) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.geoadd(key, longitude, latitude, member);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return 0L;
    }

    /**
     * GEO 查詢
     *
     * @param key
     * @param longitude 經度
     * @param latitude  緯度
     * @param radius    半徑
     * @param unit      單位
     * @param sort      ASC|DESC:預設null結果是未排序的,傳入ASC為從近到遠排序,傳入DESC為從遠到近排序
     * @param count     傳入COUNT引數,可以返回指定數量的結果 null 不限制
     * @param withdist  傳入WITHDIST引數,則返回結果會帶上匹配位置與給定地理位置的距離
     *                  傳入WITHHASH引數,則返回結果會帶上匹配位置的hash值
     *                  傳入WITHCOORD引數,則返回結果會帶上匹配位置的經緯度
     * @return
     */
    public static List<GeoRadiusResponse> georadius(String key, double longitude, double latitude, double radius, GeoUnit unit,
                                                    String sort, Integer count, boolean withdist) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            GeoRadiusParam param = GeoRadiusParam.geoRadiusParam();
            param.withCoord();
            if (count != null) {
                param.count(count);
            }
            if (withdist) {
                param.withDist();
            }
//            if (Constants.ASC.equals(sort)) {
//                param.sortAscending();
//            } else if (Constants.DESC.equals(sort)) {
//                param.sortDescending();
//            }
            return jedis.georadius(key, longitude, latitude, radius, unit, param);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return null;
    }

    /**
     * 查詢
     *
     * @param key
     * @param members
     * @return
     */
    public static List<GeoCoordinate> geopos(String key, String... members) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.geopos(key, members);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return null;
    }

    /**
     * 刪除一個或者多個座標
     * <p>
     * zrem(key, member...member) :刪除名稱為key的zset中的元素member
     */
    public static Long zrem(String key, String... members) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            return jedis.zrem(key, members);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            jedis.close();
        }
        return 0L;
    }
}