JedisUtils

package cc.zeelan.framework.utils.redis; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Vector; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import org.springframework.dao.DataAccessException; import org.springframework.data.redis.connection.RedisConnection; import org.springframework.data.redis.core.Cursor; import org.springframework.data.redis.core.HashOperations; import org.springframework.data.redis.core.ListOperations; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ScanOptions; import org.springframework.data.redis.core.SetOperations; import org.springframework.data.redis.core.ValueOperations; import cc.zeelan.framework.utils.reason.R; /** * spring redis客戶端集成 * * @author witts * @project core-utils * @package cc.zeelan.framework.redis * @version 1.0 * @message 林花謝了春紅,太匆匆。無奈朝來寒雨,晚來風 */
public class JedisUtils { private static final Logger logger = LoggerFactory.getLogger(JedisUtils.class); private static JedisUtils instance = null; private static ApplicationContext context = new ClassPathXmlApplicationContext("redis/spring-redis.xml"); public static RedisTemplate<String, Object> template = null; @SuppressWarnings("unchecked") public JedisUtils() { if (template == null) { template = (RedisTemplate<String, Object>) context.getBean(RedisTemplate.class); } } private static synchronized void syncInit() { if (instance == null) { instance = new JedisUtils(); } } static { if (instance == null) { syncInit(); } } /** * 檢查是否鏈接成功 * * @return
     */
    public String ping() { try { return template.execute(new RedisCallback<String>() { public String doInRedis(RedisConnection connection) throws DataAccessException { return connection.ping(); } }); } catch (Exception e) { logger.debug("Redis 拒絕鏈接 (Connection refused)"); } return null; } /** * 查看redis裏有多少數據 */
    public long dbSize() { try { return template.execute(new RedisCallback<Long>() { public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.dbSize(); } }); } catch (Exception e) { logger.debug("Redis dbSize TIME OUT"); } return 0; } /** * 清空redis 全部數據 * * @return
     */
    public String flushDB() { try { return template.execute(new RedisCallback<String>() { public String doInRedis(RedisConnection connection) throws DataAccessException { connection.flushDb(); return "sussess"; } }); } catch (Exception e) { logger.debug("redis(清空數據倉異常)"); } return "fail"; } /** * 根據key獲取過時時間 */
    public long getTimeKey(String key) { try { return template.getExpire(key); } catch (Exception e) { logger.debug("redis(getTimeKey exception)"); } return 0; } /** * 獲取key有效時間 */
    public long getTimeKey(String key, int type) { // stringRedisTemplate.getExpire("test",TimeUnit.SECONDS)//根據key獲取過時時間並換算成指定單位
        long result = 0; try { switch (type) { case 0:// 納秒生效
                result = template.getExpire(key, TimeUnit.NANOSECONDS); break; case 1:// 微妙生效
                result = template.getExpire(key, TimeUnit.MICROSECONDS); break; case 2:// 毫秒生效
                result = template.getExpire(key, TimeUnit.MILLISECONDS); break; case 3:// 秒生效
                result = template.getExpire(key, TimeUnit.SECONDS); break; case 4:// 分鐘生效
                result = template.getExpire(key, TimeUnit.MINUTES); break; case 5:// 小時生效
                result = template.getExpire(key, TimeUnit.HOURS); break; case 6:// 天生效
                result = template.getExpire(key, TimeUnit.DAYS); break; default:// 默認秒生效
                result = template.getExpire(key, TimeUnit.SECONDS); break; } } catch (Exception e) { logger.debug("redis(getTimeKey exception)"); } return result; } /** * 經過key刪除 * * @param key */
    public long deleteByKey(String... keys) { try { return template.execute(new RedisCallback<Long>() { public Long doInRedis(RedisConnection connection) throws DataAccessException { long result = 0; for (int i = 0; i < keys.length; i++) { result = connection.del(keys[i].getBytes()); } return result; } }); } catch (Exception e) { logger.debug("redis(deleteByKey exception)"); } return 0; } /** * 檢查key是否已經存在 * * @param key * @return
     */
    public boolean exists(String key) { return template.execute(new RedisCallback<Boolean>() { public Boolean doInRedis(RedisConnection connection) throws DataAccessException { return connection.exists(key.getBytes()); } }); } /** * 設置key */
    public boolean setKey(String key, Object value) { try { ValueOperations<String, Object> operation = null; operation = template.opsForValue(); operation.set(key, value); return true; } catch (Exception e) { e.printStackTrace(); } return false; } /** * Redis中有個INCR和INCRBY命令, 均可以實現值遞增的原子性操做, 方便了解決了高併發時的衝突問題 * * @param key * @param size * @return
     */
    public long increment(byte[] key, int size) { try { return template.execute(new RedisCallback<Long>() { public Long doInRedis(RedisConnection connection) throws DataAccessException { return connection.incrBy(key, size); } }); } catch (Exception e) { logger.debug("Redis 拒絕鏈接 (Connection refused)"); } return 0; } /** * 設置key的過時時間 */
    public boolean expire(String key, long timeout, int type) { boolean result = false; switch (type) { case 0:// 納秒失效
            result = template.expire(key, timeout, TimeUnit.NANOSECONDS); break; case 1:// 微妙失效
            result = template.expire(key, timeout, TimeUnit.MICROSECONDS); break; case 2:// 毫秒失效
            result = template.expire(key, timeout, TimeUnit.MILLISECONDS); break; case 3:// 秒失效
            result = template.expire(key, timeout, TimeUnit.SECONDS); break; case 4:// 分鐘失效
            result = template.expire(key, timeout, TimeUnit.MINUTES); break; case 5:// 小時失效
            result = template.expire(key, timeout, TimeUnit.HOURS); break; case 6:// 天失效
            result = template.expire(key, timeout, TimeUnit.DAYS); break; default:// 默認秒失效
            result = template.expire(key, timeout, TimeUnit.SECONDS); break; } return result; } /** * 設置數據有效時間 * * @param key * @param value * @param second * 時間參數 * @param type * 0t納秒/1t微秒/2t毫秒/3t秒/4t分鐘/5t小時/6t天生效 */
    public void setTimeKey(String key, Object value, long second, int type) { ValueOperations<String, Object> operation = null; operation = template.opsForValue(); switch (type) { case 0:// 納秒生效
 operation.set(key, value, second, TimeUnit.NANOSECONDS); template.expire(key, second, TimeUnit.NANOSECONDS); break; case 1:// 微妙生效
 operation.set(key, value, second, TimeUnit.MICROSECONDS); template.expire(key, second, TimeUnit.MICROSECONDS); break; case 2:// 毫秒生效
 operation.set(key, value, second, TimeUnit.MILLISECONDS); template.expire(key, second, TimeUnit.MILLISECONDS); break; case 3:// 秒生效
 operation.set(key, value, second, TimeUnit.SECONDS); template.expire(key, second, TimeUnit.SECONDS); break; case 4:// 分鐘生效
 operation.set(key, value, second, TimeUnit.MINUTES); template.expire(key, second, TimeUnit.MINUTES); break; case 5:// 小時生效
 operation.set(key, value, second, TimeUnit.HOURS); template.expire(key, second, TimeUnit.HOURS); break; case 6:// 天生效
 operation.set(key, value, second, TimeUnit.DAYS); template.expire(key, second, TimeUnit.DAYS); break; default:// 默認秒生效
 operation.set(key, value, second, TimeUnit.SECONDS); template.expire(key, second, TimeUnit.SECONDS); break; } } /** * 獲取key * * @param key * @return
     */
    public Object getKey(String key) { ValueOperations<String, Object> operation = null; operation = template.opsForValue(); return operation.get(key); } /** * 設置hash集合 map爲hashMap<String,Object>(); */
    public void setHashOperations(String key, Map<String, Object> value) { HashOperations<String, Object, Object> operation = null; operation = template.opsForHash(); operation.putAll(key, value); operation = null; } /** * 獲取hash集合 * * @param key * @return
     */
    public Map<Object, Object> getHashOperations(String key) { HashOperations<String, Object, Object> operation = null; operation = template.opsForHash(); return operation.entries(key); } /** * 批量把一個集合插入到列表中 * * @param key * @param list */
    public void setLeftArray(String key, List<Object> value) { ListOperations<String, Object> operation = null; operation = template.opsForList(); operation.leftPushAll(key, value); } /** * 從存儲在鍵中的列表中刪除等於值的元素的第一個計數事件。 計數參數如下列方式影響操做: count> 0:刪除等於從頭至尾移動的值的元素。 count * <0:刪除等於從尾到頭移動的值的元素。 count = 0:刪除等於value的全部元素。 * * @param key * @param count * @param value */
    public long removeListKey(String key, int count, Object value) { ListOperations<String, Object> operation = null; operation = template.opsForList(); return operation.remove(key, count, value); } /** * 獲取集合長度 */
    public long getSize(String key) { ListOperations<String, Object> opsForList = null; opsForList = template.opsForList(); return opsForList.size(key); } /** * 根據下表獲取列表中的值,下標是從0開始的 * * @param key * @param start * @param end * @return
     */
    public List<Object> getIndex(String key, long start, long end) { ListOperations<String, Object> operation = null; operation = template.opsForList(); List<Object> array = null; array = operation.range(key, start, end); return array; } /** * 根據下表獲取列表中的值,下標是從0開始的 * * @param key * @param start * @param end * @return
     */
    public Object getIndex(String key, long index) { ListOperations<String, Object> operation = null; operation = template.opsForList(); Object object = null; object = operation.index(key, index); return object; } /** * hash刪除 * * @return
     */
    public long delete() { HashOperations<String, Object, Object> operation = null; operation = template.opsForHash(); return operation.delete("redisHash", "name"); } /** * 檢測hash key是否存在 * * @param key * @param value * @return
     */
    public boolean hashKey(String key, String value) { HashOperations<String, Object, Object> operation = null; operation = template.opsForHash(); return operation.hasKey(key, value); } /** * 經過給定的delta增長散列hashKey的值(整型) * * @return
     */
    public long increment(String key, String hashKey, int number) { HashOperations<String, Object, Object> operation = null; operation = template.opsForHash(); return operation.increment(key, hashKey, number); } /** * 經過給定的delta增長散列hashKey的值(浮點數) * * @param key * @param hashKey * @param delta * @return
     */
    public double increment(String key, String hashKey, double delta) { HashOperations<String, Object, Object> operation = null; operation = template.opsForHash(); return operation.increment(key, hashKey, delta); } /** * 獲取key所對應的散列表的key * * @param key * @return
     */
    public Set<Object> keys(String key) { HashOperations<String, Object, Object> operation = null; operation = template.opsForHash(); return operation.keys(key); } /** * 獲取key所對應的散列表的大小個數 * * @param key * @return
     */
    public long size(String key) { HashOperations<String, Object, Object> operation = null; operation = template.opsForHash(); return operation.size(key); } /** * 設置散列hashKey的值 * * @param key * @param hashKey * @param value */
    public void put(String key, String hashKey, String value) { HashOperations<String, Object, Object> operation = null; operation = template.opsForHash(); operation.put(key, hashKey, value); } /** * 移除集合中一個或多個成員 * * @param key * @param values * @return
     */
    public long remove(String key, Object... values) { SetOperations<String, Object> operation = null; operation = template.opsForSet(); return operation.remove(key, values); } /** * 判斷 member 元素是不是集合 key 的成員 * * @param key * @param object * @return
     */
    public boolean isMember(String key, Object object) { SetOperations<String, Object> operation = null; operation = template.opsForSet(); return operation.isMember(key, object); } /** * 返回集合中的全部成員 * * @param key * @return
     */
    public Set<Object> members(String key) { SetOperations<String, Object> operation = null; operation = template.opsForSet(); return operation.members(key); } /** * 隨機獲取key無序集合中的一個元素 * * @param key * @return
     */
    public Object randomMember(String key) { SetOperations<String, Object> operation = null; operation = template.opsForSet(); return operation.randomMember(key); } /** * 獲取多個key無序集合中的元素(去重),count表示個數 * * @param key * @param count * @return
     */
    public Set<Object> distinctRandomMembers(String key, long count) { SetOperations<String, Object> operation = null; operation = template.opsForSet(); return operation.distinctRandomMembers(key, count); } /** * 獲取多個key無序集合中的元素,count表示個數 * * @param key * @param count * @return
     */
    public List<Object> randomMembers(String key, long count) { SetOperations<String, Object> operation = null; operation = template.opsForSet(); return operation.randomMembers(key, count); } /** * 遍歷zset * * @param key * @param options * @return
     */ Vector<Object> scan(String key, ScanOptions options) { Vector<Object> array = null; array = new Vector<Object>(); SetOperations<String, Object> operation = null; operation = template.opsForSet(); Cursor<Object> cursor = null; cursor = operation.scan(key, ScanOptions.NONE); while (cursor.hasNext()) { array.add(cursor.next()); } return array; } /** * redis性能讀寫測試 4000併發 1次操做 * * @param args */
    public synchronized static void main(String[] args) { JedisUtils jedis = new JedisUtils(); System.out.println(jedis.getKey("123")); long threadCount = 4000;// 併發
        long excute = 10;// 執行次數
        ExecutorService threadPool = Executors.newCachedThreadPool(); jedis.flushDB(); long startTime = System.currentTimeMillis(); for (int i = 0; i < threadCount; i++) { threadPool.execute(new Runnable() { // 非線程安全 
 @Override public void run() { for (int j = 0; j < excute; j++) { R.debug(jedis.setKey(R.getNano(), R.getNano())); } } }); } R.debug("excute method time is " + (System.currentTimeMillis() - startTime) / 1000); threadPool.shutdown(); } } 
相關文章
相關標籤/搜索