RedisUtilsコレクションredis共通アクション

2902 ワード

package com.gyc.common; 

import org.springframework.beans.factory.annotation.Autowired;  
import org.springframework.data.redis.core.RedisTemplate;  
import org.springframework.data.redis.core.ValueOperations;  
import org.springframework.stereotype.Component;  
import java.io.Serializable;  
import java.util.Set;  
import java.util.concurrent.TimeUnit;  
  
/** 
 * Created by messigao  
 */  
@SuppressWarnings("unchecked")  
@Component  
public class RedisUtils {  
    @SuppressWarnings("rawtypes")  
    @Autowired  
    private RedisTemplate redisTemplate;  
    /** 
     *        value 
     * 
     * @param keys 
     */  
    public void remove(final String... keys) {  
        for (String key : keys) {  
          remove(key);  
        }  
    }  
    /** 
     *     key 
     * 
     * @param pattern 
     */  
    public void removePattern(final String pattern) {  
        Set keys = redisTemplate.keys(pattern);  
        if (keys.size() > 0)  
            redisTemplate.delete(keys);  
    }  
    /** 
     *      value 
     * 
     * @param key 
     */  
    public void remove(final String key) {  
        if (exists(key)) {  
       redisTemplate.delete(key);  
        }  
    }  
    /** 
     *            value 
     * 
     * @param key 
     * @return 
     */  
    public boolean exists(final String key) {  
        return redisTemplate.hasKey(key);  
    }  
    /** 
     *      
     * 
     * @param key 
     * @return 
     */  
    public Object get(final String key) {  
        Object result = null;  
        ValueOperations operations = redisTemplate.opsForValue();  
        result = operations.get(key);  
        return result;  
    }  
    /** 
     *      
     * 
     * @param key 
     * @param value 
     * @return 
     */  
    public boolean set(final String key, Object value) {  
        boolean result = false;  
        try {  
             ValueOperations operations  = redisTemplate.opsForValue();  
            operations.set(key, value);  
            result = true;  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return result;  
    }  
    /** 
     *      
     * 
     * @param key 
     * @param value 
     * @return 
     */  
    public boolean set(final String key, Object value, Long expireTime) {  
        boolean result = false;  
        try {  
          ValueOperations operations =         redisTemplate.opsForValue();  
            operations.set(key, value);  
            redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);  
            result = true;  
        } catch (Exception e) {  
          e.printStackTrace();  
        }  
        return result;  
    }  
}