Redis緩存對象相關

1、想要使用redis先獲得連接池對象,及JedisPool
然後在配置生成連接池對象需要的參數咯
(1)你可以寫一個參數實體類,再寫一個bean注入到spring

@Component
@ConfigurationProperties(prefix="redis")//這個在properties的配置文件裏噢,框架是springboot,表示前綴是redis的,參數名稱得對應。
public class RedisConfig {
    private String host;
    private int port;
    private int timeout;//秒
    private String password;
    private int poolMaxTotal;
    private int poolMaxIdle;
    private int poolMaxWait;//秒
    public String getHost() {
        return host;
    }
    public void setHost(String host) {
        this.host = host;
    }
    public int getPort() {
        return port;
    }
    public void setPort(int port) {
        this.port = port;
    }
    public int getTimeout() {
        return timeout;
    }
    public void setTimeout(int timeout) {
        this.timeout = timeout;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public int getPoolMaxTotal() {
        return poolMaxTotal;
    }
    public void setPoolMaxTotal(int poolMaxTotal) {
        this.poolMaxTotal = poolMaxTotal;
    }
    public int getPoolMaxIdle() {
        return poolMaxIdle;
    }
    public void setPoolMaxIdle(int poolMaxIdle) {
        this.poolMaxIdle = poolMaxIdle;
    }
    public int getPoolMaxWait() {
        return poolMaxWait;
    }
    public void setPoolMaxWait(int poolMaxWait) {
        this.poolMaxWait = poolMaxWait;
    }
}
@Service
public class RedisPoolFactory {

    @Autowired
    RedisConfig redisConfig;

    @Bean
    public JedisPool JedisPoolFactory() {
        JedisPoolConfig poolConfig = new JedisPoolConfig();
        poolConfig.setMaxIdle(redisConfig.getPoolMaxIdle());
        poolConfig.setMaxTotal(redisConfig.getPoolMaxTotal());
        poolConfig.setMaxWaitMillis(redisConfig.getPoolMaxWait() * 1000);
        JedisPool jp = new JedisPool(poolConfig, redisConfig.getHost(), redisConfig.getPort(),
                redisConfig.getTimeout()*1000, redisConfig.getPassword(), 0);
        return jp;
    }

}

(2)可以直接在開啓springmvc配置註解,直接配置
代碼如下

/**
 * 強指定redis的JedisPool接口構造函數,這樣才能在centos成功創建jedispool
 **/ 
public class JedisPoolWriper {
    /** Redis連接池對象 */
    private JedisPool jedisPool;

    public JedisPoolWriper(final JedisPoolConfig poolConfig, final String host,
            final int port) {
        try {
            jedisPool = new JedisPool(poolConfig, host, port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 獲取Redis連接池對象
     * @return
     */
    public JedisPool getJedisPool() {
        return jedisPool;
    }

    /**
     * 注入Redis連接池對象
     * @param jedisPool
     */
    public void setJedisPool(JedisPool jedisPool) {
        this.jedisPool = jedisPool;
    }

}
**
 * Ma.li.ran
 * 2017/11/17 0017 15:51
 * redis配置
 */
@Configuration

public class RedisConfiguration {

  @Value("${redis.hostname}")
  private String hostname;
  @Value("${redis.port}")
  private int port;
  @Value("${redis.pool.maxActive}")
  private int maxTotal;
  @Value("${redis.pool.maxIdle}")
  private int maxIdle;
  @Value("${redis.pool.maxWait}")
  private long maxWaitMillis;
  @Value("${redis.pool.testOnBorrow}")
  private boolean testOnBorrow;

  @Autowired
  private JedisPoolConfig jedisPoolConfig;
  @Autowired
  private JedisPoolWriper jedisPoolWriper;
  @Autowired
  private JedisUtil jedisUtil;



  /**
   * 創建redis連接池的設置
   */
  @Bean(name = "jedisPoolConfig")
  public JedisPoolConfig createJedisConfig() {
    JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
    //控制一個pool可分配多少個jedis實例
    jedisPoolConfig.setMaxTotal(maxTotal);
    /*
      連接池中最多可空閒maxIdle個連接,這裏取值爲20,表示即使沒有數據庫連接依然可以空閒20個隨時等待待命
     */
    jedisPoolConfig.setMaxIdle(maxIdle);
    //最大等待時間,當沒有可用鏈接時,連接池等待的最大歸還時間,超出拋出異常
    jedisPoolConfig.setMaxWaitMillis(maxWaitMillis);
    //在獲取連接時檢查有效性
    jedisPoolConfig.setTestOnBorrow(testOnBorrow);
    return jedisPoolConfig;
  }

  /**
   * 創建redis連接池
   */
  @Bean(name = "jedisPool")
  public JedisPoolWriper createJedisPoolWriper() {
    JedisPoolWriper jedisPoolWriper = new JedisPoolWriper(jedisPoolConfig, hostname, port);
    return jedisPoolWriper;
  }

  /**
   * keys
   * @return
   */
  @Bean(name = "jedisKeys")
  public JedisUtil.Keys createJedisKeys() {
    JedisUtil.Keys jedisKeys = jedisUtil.new Keys();
    return jedisKeys;
  }

  /**
   * Strings
   * @return
   */
  @Bean(name = "jedisStrings")
  public JedisUtil.Strings createJedisStrings() {
    JedisUtil.Strings jedisStrings= jedisUtil.new Strings();
    return jedisStrings;
  }

  /**
   * Hash
   * @return
   */
  @Bean(name = "jedisHash")
  public JedisUtil.Hash createJedisHash() {
    JedisUtil.Hash jedisHash= jedisUtil.new Hash();
    return jedisHash;
  }

  /**
   * Lists
   * @return
   */
  @Bean(name = "jedisLists")
  public JedisUtil.Lists createJedisLists() {
    JedisUtil.Lists jedisLists= jedisUtil.new Lists();
    return jedisLists;
  }

  /**
   * Sets
   * @return
   */
  @Bean(name = "jedisSets")
  public JedisUtil.Sets createJedisSets() {
    JedisUtil.Sets jedisSets= jedisUtil.new Sets();
    return jedisSets;
  }

}

這樣連接池對象就能獲得了,然後就可以用裏面的方法了。

2、
(1)用@Service管理起來直接使用,爲了方便key值管理,定義一個key前綴接口

public interface KeyPrefix {

    public int expireSeconds();//過期時間

    public String getPrefix();//前綴
}

public abstract class BasePrefix implements KeyPrefix{

    private int expireSeconds;

    private String prefix;

    public BasePrefix(String prefix) {//0代表永不過期
        this(0, prefix);
    }

    public BasePrefix( int expireSeconds, String prefix) {
        this.expireSeconds = expireSeconds;
        this.prefix = prefix;
    }

    public int expireSeconds() {//默認0代表永不過期
        return expireSeconds;
    }

    public String getPrefix() {
        String className = getClass().getSimpleName();
        return className+":" + prefix;
    }

}

以後所有key都繼承這個base基類就好了,定義自己的key前綴和過期時間
然後定義一些基礎方法,方便業務使用
這裏json處理用的fastjson

@Service
public class RedisService {

    @Autowired
    JedisPool jedisPool;

    /**
     * 獲取當個對象
     * */
    public <T> T get(KeyPrefix prefix, String key,  Class<T> clazz) {
         Jedis jedis = null;
         try {
             jedis =  jedisPool.getResource();
             //生成真正的key
             String realKey  = prefix.getPrefix() + key;
             String  str = jedis.get(realKey);
             T t =  stringToBean(str, clazz);
             return t;
         }finally {
              returnToPool(jedis);
         }
    }

    /**
     * 設置對象
     * */
    public <T> boolean set(KeyPrefix prefix, String key,  T value) {
         Jedis jedis = null;
         try {
             jedis =  jedisPool.getResource();
             String str = beanToString(value);
             if(str == null || str.length() <= 0) {
                 return false;
             }
            //生成真正的key
             String realKey  = prefix.getPrefix() + key;
             int seconds =  prefix.expireSeconds();
             if(seconds <= 0) {
                 jedis.set(realKey, str);
             }else {
                 jedis.setex(realKey, seconds, str);
             }
             return true;
         }finally {
              returnToPool(jedis);
         }
    }

    /**
     * 判斷key是否存在
     * */
    public <T> boolean exists(KeyPrefix prefix, String key) {
         Jedis jedis = null;
         try {
             jedis =  jedisPool.getResource();
            //生成真正的key
             String realKey  = prefix.getPrefix() + key;
            return  jedis.exists(realKey);
         }finally {
              returnToPool(jedis);
         }
    }

    /**
     * 刪除
     * */
    public boolean delete(KeyPrefix prefix, String key) {
         Jedis jedis = null;
         try {
             jedis =  jedisPool.getResource();
            //生成真正的key
            String realKey  = prefix.getPrefix() + key;
            long ret =  jedis.del(realKey);
            return ret > 0;
         }finally {
              returnToPool(jedis);
         }
    }

    /**
     * 增加值
     * */
    public <T> Long incr(KeyPrefix prefix, String key) {
         Jedis jedis = null;
         try {
             jedis =  jedisPool.getResource();
            //生成真正的key
             String realKey  = prefix.getPrefix() + key;
            return  jedis.incr(realKey);
         }finally {
              returnToPool(jedis);
         }
    }

    /**
     * 減少值
     * */
    public <T> Long decr(KeyPrefix prefix, String key) {
         Jedis jedis = null;
         try {
             jedis =  jedisPool.getResource();
            //生成真正的key
             String realKey  = prefix.getPrefix() + key;
            return  jedis.decr(realKey);
         }finally {
              returnToPool(jedis);
         }
    }

    public boolean delete(KeyPrefix prefix) {
        if(prefix == null) {
            return false;
        }
        List<String> keys = scanKeys(prefix.getPrefix());
        if(keys==null || keys.size() <= 0) {
            return true;
        }
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            jedis.del(keys.toArray(new String[0]));
            return true;
        } catch (final Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            if(jedis != null) {
                jedis.close();
            }
        }
    }

    public List<String> scanKeys(String key) {
        Jedis jedis = null;
        try {
            jedis = jedisPool.getResource();
            List<String> keys = new ArrayList<String>();
            String cursor = "0";
            ScanParams sp = new ScanParams();
            sp.match("*"+key+"*");
            sp.count(100);
            do{
                ScanResult<String> ret = jedis.scan(cursor, sp);
                List<String> result = ret.getResult();
                if(result!=null && result.size() > 0){
                    keys.addAll(result);
                }
                //再處理cursor
                cursor = ret.getStringCursor();
            }while(!cursor.equals("0"));
            return keys;
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }
    }

    public static <T> String beanToString(T value) {
        if(value == null) {
            return null;
        }
        Class<?> clazz = value.getClass();
        if(clazz == int.class || clazz == Integer.class) {
             return ""+value;
        }else if(clazz == String.class) {
             return (String)value;
        }else if(clazz == long.class || clazz == Long.class) {
            return ""+value;
        }else {
            return JSON.toJSONString(value);
        }
    }

    @SuppressWarnings("unchecked")
    public static <T> T stringToBean(String str, Class<T> clazz) {
        if(str == null || str.length() <= 0 || clazz == null) {
             return null;
        }
        if(clazz == int.class || clazz == Integer.class) {
             return (T)Integer.valueOf(str);
        }else if(clazz == String.class) {
             return (T)str;
        }else if(clazz == long.class || clazz == Long.class) {
            return  (T)Long.valueOf(str);
        }else {
            return JSON.toJavaObject(JSON.parseObject(str), clazz);
        }
    }

    private void returnToPool(Jedis jedis) {
         if(jedis != null) {
             jedis.close();
         }
    }

}

使用時直接調用接口方法就好了,注意數據庫修改時及時同步緩存一致
(2)自己封裝個工具類

package com.maqway.wxht.controller.cache;

import java.util.List;
import java.util.Map;
import java.util.Set;
import redis.clients.jedis.BinaryClient.LIST_POSITION;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.SortingParams;
import redis.clients.util.SafeEncoder;

public class JedisUtil {

  /**
   * 緩存生存時間
   */
  private final int expire = 60000;
  /**
   * 操作Key的方法
   */
  public Keys KEYS;
  /**
   * 對存儲結構爲String類型的操作
   */
  public Strings STRINGS;
  /**
   * 對存儲結構爲List類型的操作
   */
  public Lists LISTS;
  /**
   * 對存儲結構爲Set類型的操作
   */
  public Sets SETS;
  /**
   * 對存儲結構爲HashMap類型的操作
   */
  public Hash HASH;

  /**
   * Redis連接池對象
   */
  private JedisPool jedisPool;

  /**
   * 獲取redis連接池
   */
  public JedisPool getJedisPool() {
    return jedisPool;
  }

  /**
   * 設置redis連接池
   */
  public void setJedisPool(JedisPoolWriper jedisPoolWriper) {
    this.jedisPool = jedisPoolWriper.getJedisPool();
  }

  /**
   * 從jedis連接池中獲取獲取jedis對象
   */
  public Jedis getJedis() {
    return jedisPool.getResource();
  }

  /**
   * 設置過期時間
   *
   * @author xiangze
   */
  public void expire(String key, int seconds) {
    if (seconds <= 0) {
      return;
    }
    Jedis jedis = getJedis();
    jedis.expire(key, seconds);
    jedis.close();
  }

  /**
   * 設置默認過期時間
   *
   * @author xiangze
   */
  public void expire(String key) {
    expire(key, expire);
  }

  // *******************************************Keys*******************************************//
  public class Keys {

    public Keys() {
    }

    /**
     * 清空所有key
     */
    public String flushAll() {
      Jedis jedis = getJedis();
      String stata = jedis.flushAll();
      jedis.close();
      return stata;
  }

    /**
     * 更改key
     *
     * @return 狀態碼
     */
    public String rename(String oldkey, String newkey) {
      return rename(SafeEncoder.encode(oldkey), SafeEncoder.encode(newkey));
    }

    /**
     * 更改key,僅當新key不存在時才執行
     *
     * @return 狀態碼
     */
    public long renamenx(String oldkey, String newkey) {
      Jedis jedis = getJedis();
      long status = jedis.renamenx(oldkey, newkey);
      jedis.close();
      return status;
    }

    /**
     * 更改key
     *
     * @return 狀態碼
     */
    public String rename(byte[] oldkey, byte[] newkey) {
      Jedis jedis = getJedis();
      String status = jedis.rename(oldkey, newkey);
      jedis.close();
      return status;
    }

    /**
     * 設置key的過期時間,以秒爲單位
     * *
     */
    public long expired(String key, int seconds) {
      Jedis jedis = getJedis();
      long count = jedis.expire(key, seconds);
      jedis.close();
      return count;
    }

    /**
     * 設置key的過期時間,它是距曆元(即格林威治標準時間 1970 年 1 月 1 日的 00:00:00,格里高利曆)的偏移量。
     *
     * *
     */
    public long expireAt(String key, long timestamp) {
      Jedis jedis = getJedis();
      long count = jedis.expireAt(key, timestamp);
      jedis.close();
      return count;
    }

    /**
     * 查詢key的過期時間
     *
     * @param  key
     * @return 以秒爲單位的時間表示
     */
    public long ttl(String key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      long len = sjedis.ttl(key);
      sjedis.close();
      return len;
    }

    /**
     * 取消對key過期時間的設置
     *
     * @return 影響的記錄數
     */
    public long persist(String key) {
      Jedis jedis = getJedis();
      long count = jedis.persist(key);
      jedis.close();
      return count;
    }

    /**
     * 刪除keys對應的記錄,可以是多個key
     *
     * @param  keys
     * @return 刪除的記錄數
     */
    public long del(String... keys) {
      Jedis jedis = getJedis();
      long count = jedis.del(keys);
      jedis.close();
      return count;
    }

    /**
     * 刪除keys對應的記錄,可以是多個key
     *
     * @param  keys
     * @return 刪除的記錄數
     */
    public long del(byte[]... keys) {
      Jedis jedis = getJedis();
      long count = jedis.del(keys);
      jedis.close();
      return count;
    }

    /**
     * 判斷key是否存在
     *
     * @param  key
     * @return boolean
     */
    public boolean exists(String key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      boolean exis = sjedis.exists(key);
      sjedis.close();
      return exis;
    }

    /**
     * 對List,Set,SortSet進行排序,如果集合數據較大應避免使用這個方法
     *
     * @param  key
     * @return List<String> 集合的全部記錄
     **/
    public List<String> sort(String key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      List<String> list = sjedis.sort(key);
      sjedis.close();
      return list;
    }

    /**
     * 對List,Set,SortSet進行排序或limit
     *
     * @param  key
     * @param  parame 定義排序類型或limit的起止位置.
     * @return List<String> 全部或部分記錄
     **/
    public List<String> sort(String key, SortingParams parame) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      List<String> list = sjedis.sort(key, parame);
      sjedis.close();
      return list;
    }

    /**
     * 返回指定key存儲的類型
     *
     * @param  key
     * @return String string|list|set|zset|hash
     **/
    public String type(String key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      String type = sjedis.type(key);
      sjedis.close();
      return type;
    }

    /**
     * 查找所有匹配給定的模式的鍵
     *
     * @param pattern key的表達式,*表示多個,?表示一個
     */
    public Set<String> keys(String pattern) {
      Jedis jedis = getJedis();
      Set<String> set = jedis.keys(pattern);
      jedis.close();
      return set;
    }
  }

  // *******************************************Strings*******************************************//
  public class Strings {

    public Strings() {
    }

    /**
     * 根據key獲取記錄
     *
     * @param  key
     * @return 值
     */
    public String get(String key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      String value = sjedis.get(key);
      sjedis.close();
      return value;
    }

    /**
     * 根據key獲取記錄
     *
     * @param key
     * @return 值
     */
    public byte[] get(byte[] key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      byte[] value = sjedis.get(key);
      sjedis.close();
      return value;
    }

    /**
     * 添加記錄,如果記錄已存在將覆蓋原有的value
     *
     * @param  key
     * @param  value
     * @return 狀態碼
     */
    public String set(String key, String value) {
      return set(SafeEncoder.encode(key), SafeEncoder.encode(value));
    }

    /**
     * 添加記錄,如果記錄已存在將覆蓋原有的value
     *
     * @param  key
     * @param  value
     * @return 狀態碼
     */
    public String set(String key, byte[] value) {
      return set(SafeEncoder.encode(key), value);
    }

    /**
     * 添加記錄,如果記錄已存在將覆蓋原有的value
     *
     * @param  key
     * @param  value
     * @return 狀態碼
     */
    public String set(byte[] key, byte[] value) {
      Jedis jedis = getJedis();
      String status = jedis.set(key, value);
      jedis.close();
      return status;
    }

    /**
     * 添加有過期時間的記錄
     *
     * @param  key
     * @param  seconds 過期時間,以秒爲單位
     * @param  value
     * @return String 操作狀態
     */
    public String setEx(String key, int seconds, String value) {
      Jedis jedis = getJedis();
      String str = jedis.setex(key, seconds, value);
      jedis.close();
      return str;
    }

    /**
     * 添加有過期時間的記錄
     *
     * @param  key
     * @param  seconds 過期時間,以秒爲單位
     * @param  value
     * @return String 操作狀態
     */
    public String setEx(byte[] key, int seconds, byte[] value) {
      Jedis jedis = getJedis();
      String str = jedis.setex(key, seconds, value);
      jedis.close();
      return str;
    }

    /**
     * 添加一條記錄,僅當給定的key不存在時才插入
     *
     * @param  key
     * @param  value
     * @return long 狀態碼,1插入成功且key不存在,0未插入,key存在
     */
    public long setnx(String key, String value) {
      Jedis jedis = getJedis();
      long str = jedis.setnx(key, value);
      jedis.close();
      return str;
    }

    /**
     * 從指定位置開始插入數據,插入的數據會覆蓋指定位置以後的數據<br/>
     * 例:String str1="123456789";<br/>
     * 對str1操作後setRange(key,4,0000),str1="123400009";
     *
     * @param  key
     * @param  offset
     * @param  value
     * @return long value的長度
     */
    public long setRange(String key, long offset, String value) {
      Jedis jedis = getJedis();
      long len = jedis.setrange(key, offset, value);
      jedis.close();
      return len;
    }

    /**
     * 在指定的key中追加value
     *
     * @param key
     * @param  value
     * @return long 追加後value的長度
     **/
    public long append(String key, String value) {
      Jedis jedis = getJedis();
      long len = jedis.append(key, value);
      jedis.close();
      return len;
    }

    /**
     * 將key對應的value減去指定的值,只有value可以轉爲數字時該方法纔可用
     *
     * @param key
     * @param  number 要減去的值
     * @return long 減指定值後的值
     */
    public long decrBy(String key, long number) {
      Jedis jedis = getJedis();
      long len = jedis.decrBy(key, number);
      jedis.close();
      return len;
    }

    /**
     * <b>可以作爲獲取唯一id的方法</b><br/>
     * 將key對應的value加上指定的值,只有value可以轉爲數字時該方法纔可用
     *
     * @param key
     * @param  number 要減去的值
     * @return long 相加後的值
     */
    public long incrBy(String key, long number) {
      Jedis jedis = getJedis();
      long len = jedis.incrBy(key, number);
      jedis.close();
      return len;
    }

    /**
     * 對指定key對應的value進行截取
     *
     * @param  key
     * @param  startOffset 開始位置(包含)
     * @param endOffset 結束位置(包含)
     * @return String 截取的值
     */
    public String getrange(String key, long startOffset, long endOffset) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      String value = sjedis.getrange(key, startOffset, endOffset);
      sjedis.close();
      return value;
    }

    /**
     * 獲取並設置指定key對應的value<br/>
     * 如果key存在返回之前的value,否則返回null
     *
     * @param  key
     * @param value
     * @return String 原始value或null
     */
    public String getSet(String key, String value) {
      Jedis jedis = getJedis();
      String str = jedis.getSet(key, value);
      jedis.close();
      return str;
    }

    /**
     * 批量獲取記錄,如果指定的key不存在返回List的對應位置將是null
     *
     * @param  keys
     * @return List<String> 值得集合
     */
    public List<String> mget(String... keys) {
      Jedis jedis = getJedis();
      List<String> str = jedis.mget(keys);
      jedis.close();
      return str;
    }

    /**
     * 批量存儲記錄
     *
     * @param keysvalues 例:keysvalues="key1","value1","key2","value2";
     * @return String 狀態碼
     */
    public String mset(String... keysvalues) {
      Jedis jedis = getJedis();
      String str = jedis.mset(keysvalues);
      jedis.close();
      return str;
    }

    /**
     * 獲取key對應的值的長度
     *
     * @param  key
     * @return value值得長度
     */
    public long strlen(String key) {
      Jedis jedis = getJedis();
      long len = jedis.strlen(key);
      jedis.close();
      return len;
    }
  }

  // *******************************************Sets*******************************************//
  public class Sets {

    public Sets() {
    }

    /**
     * 向Set添加一條記錄,如果member已存在返回0,否則返回1
     *
     * @param  key
     * @param  member
     * @return 操作碼, 0或1
     */
    public long sadd(String key, String member) {
      Jedis jedis = getJedis();
      long s = jedis.sadd(key, member);
      jedis.close();
      return s;
    }

    public long sadd(byte[] key, byte[] member) {
      Jedis jedis = getJedis();
      long s = jedis.sadd(key, member);
      jedis.close();
      return s;
    }

    /**
     * 獲取給定key中元素個數
     *
     * @param  key
     * @return 元素個數
     */
    public long scard(String key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      long len = sjedis.scard(key);
      sjedis.close();
      return len;
    }

    /**
     * 返回從第一組和所有的給定集合之間的差異的成員
     *
     * @param  keys
     * @return 差異的成員集合
     */
    public Set<String> sdiff(String... keys) {
      Jedis jedis = getJedis();
      Set<String> set = jedis.sdiff(keys);
      jedis.close();
      return set;
    }

    /**
     * 這個命令等於sdiff,但返回的不是結果集,而是將結果集存儲在新的集合中,如果目標已存在,則覆蓋。
     *
     * @param newkey 新結果集的key
     * @param keys 比較的集合
     * @return 新集合中的記錄數
     **/
    public long sdiffstore(String newkey, String... keys) {
      Jedis jedis = getJedis();
      long s = jedis.sdiffstore(newkey, keys);
      jedis.close();
      return s;
    }

    /**
     * 返回給定集合交集的成員,如果其中一個集合爲不存在或爲空,則返回空Set
     *
     * @param keys
     * @return 交集成員的集合
     **/
    public Set<String> sinter(String... keys) {
      Jedis jedis = getJedis();
      Set<String> set = jedis.sinter(keys);
      jedis.close();
      return set;
    }

    /**
     * 這個命令等於sinter,但返回的不是結果集,而是將結果集存儲在新的集合中,如果目標已存在,則覆蓋。
     *
     * @param newkey 新結果集的key
     * @param  keys 比較的集合
     * @return 新集合中的記錄數
     **/
    public long sinterstore(String newkey, String... keys) {
      Jedis jedis = getJedis();
      long s = jedis.sinterstore(newkey, keys);
      jedis.close();
      return s;
    }

    /**
     * 確定一個給定的值是否存在
     *
     * @param  key
     * @param member 要判斷的值
     * @return 存在返回1,不存在返回0
     **/
    public boolean sismember(String key, String member) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      boolean s = sjedis.sismember(key, member);
      sjedis.close();
      return s;
    }

    /**
     * 返回集合中的所有成員
     *
     * @param  key
     * @return 成員集合
     */
    public Set<String> smembers(String key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      Set<String> set = sjedis.smembers(key);
      sjedis.close();
      return set;
    }

    public Set<byte[]> smembers(byte[] key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      Set<byte[]> set = sjedis.smembers(key);
      sjedis.close();
      return set;
    }

    /**
     * 將成員從源集合移出放入目標集合 <br/>
     * 如果源集合不存在或不包哈指定成員,不進行任何操作,返回0<br/>
     * 否則該成員從源集合上刪除,並添加到目標集合,如果目標集合中成員已存在,則只在源集合進行刪除
     *
     * @param  srckey 源集合
     * @param dstkey 目標集合
     * @param member 源集合中的成員
     * @return 狀態碼,1成功,0失敗
     */
    public long smove(String srckey, String dstkey, String member) {
      Jedis jedis = getJedis();
      long s = jedis.smove(srckey, dstkey, member);
      jedis.close();
      return s;
    }

    /**
     * 從集合中刪除成員
     *
     * @param key
     * @return 被刪除的成員
     */
    public String spop(String key) {
      Jedis jedis = getJedis();
      String s = jedis.spop(key);
      jedis.close();
      return s;
    }

    /**
     * 從集合中刪除指定成員
     *
     * @param  key
     * @param member 要刪除的成員
     * @return 狀態碼,成功返回1,成員不存在返回0
     */
    public long srem(String key, String member) {
      Jedis jedis = getJedis();
      long s = jedis.srem(key, member);
      jedis.close();
      return s;
    }

    /**
     * 合併多個集合並返回合併後的結果,合併後的結果集合並不保存<br/>
     *
     * @param   keys
     * @return 合併後的結果集合
     * @see
     */
    public Set<String> sunion(String... keys) {
      Jedis jedis = getJedis();
      Set<String> set = jedis.sunion(keys);
      jedis.close();
      return set;
    }

    /**
     * 合併多個集合並將合併後的結果集保存在指定的新集合中,如果新集合已經存在則覆蓋
     *
     * @param  newkey 新集合的key
     * @param keys 要合併的集合
     **/
    public long sunionstore(String newkey, String... keys) {
      Jedis jedis = getJedis();
      long s = jedis.sunionstore(newkey, keys);
      jedis.close();
      return s;
    }
  }

  // *******************************************Hash*******************************************//
  public class Hash {

    public Hash() {
    }

    /**
     * 從hash中刪除指定的存儲
     *
     * @param  key
     * @param fieid 存儲的名字
     * @return 狀態碼,1成功,0失敗
     */
    public long hdel(String key, String fieid) {
      Jedis jedis = getJedis();
      long s = jedis.hdel(key, fieid);
      jedis.close();
      return s;
    }

    public long hdel(String key) {
      Jedis jedis = getJedis();
      long s = jedis.del(key);
      jedis.close();
      return s;
    }

    /**
     * 測試hash中指定的存儲是否存在
     *
     * @param key
     * @param  fieid 存儲的名字
     * @return 1存在,0不存在
     */
    public boolean hexists(String key, String fieid) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      boolean s = sjedis.hexists(key, fieid);
      sjedis.close();
      return s;
    }

    /**
     * 返回hash中指定存儲位置的值
     *
     * @param key
     * @param fieid 存儲的名字
     * @return 存儲對應的值
     */
    public String hget(String key, String fieid) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      String s = sjedis.hget(key, fieid);
      sjedis.close();
      return s;
    }

    public byte[] hget(byte[] key, byte[] fieid) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      byte[] s = sjedis.hget(key, fieid);
      sjedis.close();
      return s;
    }

    /**
     * 以Map的形式返回hash中的存儲和值
     *
     * @param  key
     * @return Map<Strinig,String>
     */
    public Map<String, String> hgetAll(String key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      Map<String, String> map = sjedis.hgetAll(key);
      sjedis.close();
      return map;
    }

    /**
     * 添加一個對應關係
     *
     * @param  key
     * @param  fieid
     * @param value
     * @return 狀態碼 1成功,0失敗,fieid已存在將更新,也返回0
     **/
    public long hset(String key, String fieid, String value) {
      Jedis jedis = getJedis();
      long s = jedis.hset(key, fieid, value);
      jedis.close();
      return s;
    }

    public long hset(String key, String fieid, byte[] value) {
      Jedis jedis = getJedis();
      long s = jedis.hset(key.getBytes(), fieid.getBytes(), value);
      jedis.close();
      return s;
    }

    /**
     * 添加對應關係,只有在fieid不存在時才執行
     *
     * @param  key
     * @param fieid
     * @param  value
     * @return 狀態碼 1成功,0失敗fieid已存
     **/
    public long hsetnx(String key, String fieid, String value) {
      Jedis jedis = getJedis();
      long s = jedis.hsetnx(key, fieid, value);
      jedis.close();
      return s;
    }

    /**
     * 獲取hash中value的集合
     *
     * @param  key
     * @return List<String>
     */
    public List<String> hvals(String key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      List<String> list = sjedis.hvals(key);
      sjedis.close();
      return list;
    }

    /**
     * 在指定的存儲位置加上指定的數字,存儲位置的值必須可轉爲數字類型
     *
     * @param key
     * @param  fieid 存儲位置
     * @param  value 要增加的值,可以是負數
     * @return 增加指定數字後,存儲位置的值
     */
    public long hincrby(String key, String fieid, long value) {
      Jedis jedis = getJedis();
      long s = jedis.hincrBy(key, fieid, value);
      jedis.close();
      return s;
    }

    /**
     * 返回指定hash中的所有存儲名字,類似Map中的keySet方法
     *
     * @param key
     * @return Set<String> 存儲名稱的集合
     */
    public Set<String> hkeys(String key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      Set<String> set = sjedis.hkeys(key);
      sjedis.close();
      return set;
    }

    /**
     * 獲取hash中存儲的個數,類似Map中size方法
     *
     * @param  key
     * @return long 存儲的個數
     */
    public long hlen(String key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      long len = sjedis.hlen(key);
      sjedis.close();
      return len;
    }

    /**
     * 根據多個key,獲取對應的value,返回List,如果指定的key不存在,List對應位置爲null
     *
     * @param  key
     * @param  fieids 存儲位置
     * @return List<String>
     */
    public List<String> hmget(String key, String... fieids) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      List<String> list = sjedis.hmget(key, fieids);
      sjedis.close();
      return list;
    }

    public List<byte[]> hmget(byte[] key, byte[]... fieids) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      List<byte[]> list = sjedis.hmget(key, fieids);
      sjedis.close();
      return list;
    }

    /**
     * 添加對應關係,如果對應關係已存在,則覆蓋
     *
     * @param key
     * @param map 對應關係
     * @return 狀態,成功返回OK
     */
    public String hmset(String key, Map<String, String> map) {
      Jedis jedis = getJedis();
      String s = jedis.hmset(key, map);
      jedis.close();
      return s;
    }

    /**
     * 添加對應關係,如果對應關係已存在,則覆蓋
     *
     * @param  key
     * @param  map 對應關係
     * @return 狀態,成功返回OK
     */
    public String hmset(byte[] key, Map<byte[], byte[]> map) {
      Jedis jedis = getJedis();
      String s = jedis.hmset(key, map);
      jedis.close();
      return s;
    }

  }

  // *******************************************Lists*******************************************//
  public class Lists {



    /**
     * List長度
     *
     * @param  key
     * @return 長度
     */
    public long llen(String key) {
      return llen(SafeEncoder.encode(key));
    }

    /**
     * List長度
     *
     * @param key
     * @return 長度
     */
    public long llen(byte[] key) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      long count = sjedis.llen(key);
      sjedis.close();
      return count;
    }

    /**
     * 覆蓋操作,將覆蓋List中指定位置的值
     *
     * @param  key
     * @param  index 位置
     * @param value 值
     * @return 狀態碼
     */
    public String lset(byte[] key, int index, byte[] value) {
      Jedis jedis = getJedis();
      String status = jedis.lset(key, index, value);
      jedis.close();
      return status;
    }

    /**
     * 覆蓋操作,將覆蓋List中指定位置的值
     *
     * @param  index 位置
     * @param  value 值
     * @return 狀態碼
     */
    public String lset(String key, int index, String value) {
      return lset(SafeEncoder.encode(key), index, SafeEncoder.encode(value));
    }

    /**
     * 在value的相對位置插入記錄
     *
     * @param where 前面插入或後面插入
     * @param pivot 相對位置的內容
     * @param  value 插入的內容
     * @return 記錄總數
     */
    public long linsert(String key, LIST_POSITION where, String pivot, String value) {
      return linsert(SafeEncoder.encode(key), where, SafeEncoder.encode(pivot),
          SafeEncoder.encode(value));
    }

    /**
     * 在指定位置插入記錄
     *
     * @param  key
     * @param where 前面插入或後面插入
     * @param pivot 相對位置的內容
     * @param  value 插入的內容
     * @return 記錄總數
     */
    public long linsert(byte[] key, LIST_POSITION where, byte[] pivot, byte[] value) {
      Jedis jedis = getJedis();
      long count = jedis.linsert(key, where, pivot, value);
      jedis.close();
      return count;
    }

    /**
     * 獲取List中指定位置的值
     *
     * @param  key
     * @param  index 位置
     * @return 值
     **/
    public String lindex(String key, int index) {
      return SafeEncoder.encode(lindex(SafeEncoder.encode(key), index));
    }

    /**
     * 獲取List中指定位置的值
     *
     * @param  key
     * @param  index 位置
     * @return 值
     **/
    public byte[] lindex(byte[] key, int index) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      byte[] value = sjedis.lindex(key, index);
      sjedis.close();
      return value;
    }

    /**
     * 將List中的第一條記錄移出List
     *
     * @param  key
     * @return 移出的記錄
     */
    public String lpop(String key) {
      return SafeEncoder.encode(lpop(SafeEncoder.encode(key)));
    }

    /**
     * 將List中的第一條記錄移出List
     *
     * @param key
     * @return 移出的記錄
     */
    public byte[] lpop(byte[] key) {
      Jedis jedis = getJedis();
      byte[] value = jedis.lpop(key);
      jedis.close();
      return value;
    }

    /**
     * 將List中最後第一條記錄移出List
     *
     * @param  key
     * @return 移出的記錄
     */
    public String rpop(String key) {
      Jedis jedis = getJedis();
      String value = jedis.rpop(key);
      jedis.close();
      return value;
    }

    /**
     * 向List尾部追加記錄
     *
     * @param  key
     * @param  value
     * @return 記錄總數
     */
    public long lpush(String key, String value) {
      return lpush(SafeEncoder.encode(key), SafeEncoder.encode(value));
    }

    /**
     * 向List頭部追加記錄
     *
     * @param  key
     * @param value
     * @return 記錄總數
     */
    public long rpush(String key, String value) {
      Jedis jedis = getJedis();
      long count = jedis.rpush(key, value);
      jedis.close();
      return count;
    }

    /**
     * 向List頭部追加記錄
     *
     * @param key
     * @param  value
     * @return 記錄總數
     */
    public long rpush(byte[] key, byte[] value) {
      Jedis jedis = getJedis();
      long count = jedis.rpush(key, value);
      jedis.close();
      return count;
    }

    /**
     * 向List中追加記錄
     *
     * @param key
     * @param  value
     * @return 記錄總數
     */
    public long lpush(byte[] key, byte[] value) {
      Jedis jedis = getJedis();
      long count = jedis.lpush(key, value);
      jedis.close();
      return count;
    }

    /**
     * 獲取指定範圍的記錄,可以做爲分頁使用
     *
     * @param  key
     * @param  start
     * @param  end
     * @return List
     */
    public List<String> lrange(String key, long start, long end) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      List<String> list = sjedis.lrange(key, start, end);
      sjedis.close();
      return list;
    }

    /**
     * 獲取指定範圍的記錄,可以做爲分頁使用
     *
     * @param  key
     * @param  start
     * @param end 如果爲負數,則尾部開始計算
     * @return List
     */
    public List<byte[]> lrange(byte[] key, int start, int end) {
      // ShardedJedis sjedis = getShardedJedis();
      Jedis sjedis = getJedis();
      List<byte[]> list = sjedis.lrange(key, start, end);
      sjedis.close();
      return list;
    }

    /**
     * 刪除List中c條記錄,被刪除的記錄值爲value
     *
     * @param  key
     * @param  c 要刪除的數量,如果爲負數則從List的尾部檢查並刪除符合的記錄
     * @param  value 要匹配的值
     * @return 刪除後的List中的記錄數
     */
    public long lrem(byte[] key, int c, byte[] value) {
      Jedis jedis = getJedis();
      long count = jedis.lrem(key, c, value);
      jedis.close();
      return count;
    }

    /**
     * 刪除List中c條記錄,被刪除的記錄值爲value
     *
     * @param  key
     * @param  c 要刪除的數量,如果爲負數則從List的尾部檢查並刪除符合的記錄
     * @param  value 要匹配的值
     * @return 刪除後的List中的記錄數
     */
    public long lrem(String key, int c, String value) {
      return lrem(SafeEncoder.encode(key), c, SafeEncoder.encode(value));
    }

    /**
     * 算是刪除吧,只保留start與end之間的記錄
     *
     * @param key
     * @param  start 記錄的開始位置(0表示第一條記錄)
     * @param  end 記錄的結束位置(如果爲-1則表示最後一個,-2,-3以此類推)
     * @return 執行狀態碼
     */
    public String ltrim(byte[] key, int start, int end) {
      Jedis jedis = getJedis();
      String str = jedis.ltrim(key, start, end);
      jedis.close();
      return str;
    }

    /**
     * 算是刪除吧,只保留start與end之間的記錄
     *
     * @param key
     * @param  start 記錄的開始位置(0表示第一條記錄)
     * @param  end 記錄的結束位置(如果爲-1則表示最後一個,-2,-3以此類推)
     * @return 執行狀態碼
     */
    public String ltrim(String key, int start, int end) {
      return ltrim(SafeEncoder.encode(key), start, end);
    }
  }

}

這個工具類功能幾乎很全了,舉個栗子

        // 定義redis的key前綴
        String key = PREFIX;
        // 定義接收對象
        List<User> user= null;
        // 定義jackson數據轉換操作類
        ObjectMapper mapper = new ObjectMapper();
        // 拼接出redis的key
            key = key + "_" + user.getId();

        // 判斷key是否存在
        if (!jedisKeys.exists(key)) {
            // 若不存在,則從數據庫裏面取出相應數據
            user= userDao.queryUser(user);
            // 將相關的實體類集合轉換成string,存入redis裏面對應的key中
            String jsonString;
                jsonString = mapper.writeValueAsString(user);

                logger.error(e.getMessage());
            jedisStrings.set(key, jsonString);
        } else {
            // 若存在,則直接從redis裏面取出相應數據
            String jsonString = jedisStrings.get(key);
            // 指定要將string轉換成的集合類型
            JavaType javaType = mapper.getTypeFactory().constructParametricType(String.class, User.class);

                // 將相關key對應的value裏的的string轉換成對象的實體類集合
                user= mapper.readValue(jsonString, javaType);
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章