redis的使用

1.引入redis依赖

<dependency>
			<groupId>redis-client</groupId>
			<artifactId>redis-client</artifactId>
			<version>0.0.1-SNAPSHOT</version>
		</dependency>

2.创建对应的redisManager类

import java.util.Set;


import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
import redis.clients.jedis.Protocol;

public class RedisManager {

	
	private String host = "127.0.0.1";
	
	private int port = 6379;
	
	// 0 - never expire
	private int expire = 0;
	
	//timeout for jedis try to connect to redis server, not expire time! In milliseconds
	private int timeout = 0;
	
	private String password = "";
	
	private int database = Protocol.DEFAULT_DATABASE;
	
	private static JedisPool jedisPool = null;
	
	public RedisManager(){
		
	}
	
//	public static void main(String[] args) {
//		RedisManager a = new RedisManager();
//		a.setMaster("redis-1");
//		a.setHost("192.168.100.24");
//		a.setPort(26379);
//		a.setDatabase(2);
//		a.init();
//	}
	
	/**
	 * 初始化方法
	 */
	public void init(){
		if(jedisPool == null){  
            if(password != null && !"".equals(password)){  
                jedisPool = new JedisPool(new JedisPoolConfig(), host, port, timeout, password);  
            }else if(timeout != 0){  
                jedisPool = new JedisPool(new JedisPoolConfig(), host, port,timeout);  
            }else{  
                jedisPool = new JedisPool(new JedisPoolConfig(), host, port);  
            }  
              
        }  
	}
	
	/**
	 * get value from redis
	 * @param key
	 * @return
	 */
	public byte[] get(byte[] key){
		byte[] value = null;
		Jedis jedis = jedisPool.getResource();
		try{
			value = jedis.get(key);
		}finally{
			jedisPool.returnResource(jedis);
		}
		return value;
	}
	
	/**
	 * 将字符串值 value 关联到 key 。
	 * 如果 key 已经持有其他值, SET 就覆写旧值,无视类型。
	 * <P>Author : zhangjun </P>.
	 * <P>Date : 2015-1-23 </P>
	 * @param key
	 * @param value
	 * @return 总是返回 OK ,因为 SET 不可能失败。
	 */
	public String set(String key,Object object) {
		String l = null;
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			l = jedis.set(SerializeUtils.serialize(key), SerializeUtils.serialize(object));
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(jedis != null){
				try {
					jedisPool.returnResource(jedis);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return l;
	}
	
	/**
	 * 将字符串值 value 关联到 key 。
	 * <P>Author : zhangjun </P>.
	 * <P>Date : 2015-1-23 </P>
	 * @param key
	 * @param value
	 */
	public Object getObject(String key) {
		Object o = null;
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			byte[] bs = jedis.get(SerializeUtils.serialize(key));
			if(bs != null){
				o = SerializeUtils.deserialize(bs);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(jedis != null){
				try {
					jedisPool.returnResource(jedis);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return o;
	}
	
	
	/**
	 * 将字符串值 value 关联到 key 。
	 * <P>Author : zhangjun </P>.
	 * <P>Date : 2015-1-23 </P>
	 * @param key
	 * @param value
	 */
	public String get(String key) {
		String str = null;
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			str = jedis.get(key);
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(jedis != null){
				try {
					jedisPool.returnResource(jedis);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return str;
	}
	
	/**
	 * 将字符串值 value 关联到 key 。
	 * 如果 key 已经持有其他值, SET 就覆写旧值,无视类型。
	 * <P>Author : zhangjun </P>.
	 * <P>Date : 2015-1-23 </P>
	 * @param key
	 * @param value
	 * @return 总是返回 OK ,因为 SET 不可能失败。
	 */
	public String set(final String key, final String value) {
		String l = null;
		Jedis jedis = null;
		try {
			jedis = jedisPool.getResource();
			l = jedis.set(key, value);
			if(this.expire != 0){
				jedis.expire(key, this.expire);
		 	}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (jedis != null) {
				try {
					jedisPool.returnResource(jedis);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		return l;
	}
	
	/**
	 * set 
	 * @param key
	 * @param value
	 * @return
	 */
	public byte[] set(byte[] key,byte[] value){
		Jedis jedis = jedisPool.getResource();
		try{
			jedis.set(key,value);
			if(this.expire != 0){
				jedis.expire(key, this.expire);
		 	}
		}finally{
			jedisPool.returnResource(jedis);
		}
		return value;
	}
	
	/**
	 * set 
	 * @param key
	 * @param value
	 * @param expire
	 * @return
	 */
	public byte[] set(byte[] key,byte[] value,int expire){
		Jedis jedis = jedisPool.getResource();
		try{
			jedis.set(key,value);
			if(expire != 0){
				jedis.expire(key, expire);
		 	}
		}finally{
			jedisPool.returnResource(jedis);
		}
		return value;
	}
	
	/**
	 * 删除
	 * @param key
	 * @return
	 */
	public Long del(byte[] key){
		Long flag;
		Jedis jedis = jedisPool.getResource();
		try{
			flag = jedis.del(key);
		}finally{
			jedisPool.returnResource(jedis);
		}
		return flag;
	}
	
	/**
	 * 删除
	 * @param key
	 * @return
	 */
	public Long del(String key){
		Long flag;
		Jedis jedis = jedisPool.getResource();
		try{
			flag = jedis.del(key);
		}finally{
			jedisPool.returnResource(jedis);
		}
		return flag;
	}
	
	/**
	 * flush
	 */
	public void flushDB(){
		Jedis jedis = jedisPool.getResource();
		try{
			jedis.flushDB();
		}finally{
			jedisPool.returnResource(jedis);
		}
	}
	
	
	/**
	 * size
	 */
	public Long dbSize(){
		Long dbSize = 0L;
		Jedis jedis = jedisPool.getResource();
		try{
			dbSize = jedis.dbSize();
		}finally{
			jedisPool.returnResource(jedis);
		}
		return dbSize;
	}

	/**
	 * keys
	 * @param regex
	 * @return
	 */
	public Set<byte[]> keys(String pattern){
		Set<byte[]> keys = null;
		Jedis jedis = jedisPool.getResource();
		try{
			keys = jedis.keys(pattern.getBytes());
		}finally{
			jedisPool.returnResource(jedis);
		}
		return keys;
	}
	
	

	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 getExpire() {
		return expire;
	}

	public void setExpire(int expire) {
		this.expire = expire;
	}

	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 getDatabase() {
		return database;
	}

	public void setDatabase(int database) {
		this.database = database;
	}
}

3.用redis使用Cachemanager接口 在Spring中缓存主要有一个缓存接口(Cache)与缓存管理接口(CacheManager)。可以通过扩展这两个接口实现对应的缓存管理。

@SuppressWarnings("rawtypes")
//SuppressWarnings压制警告,即去除警告 
//rawtypes是说传参时也要传递带泛型的参数
public class RedisCacheManager implements CacheManager {

	private static final Logger logger = LoggerFactory.getLogger(RedisCacheManager.class);

	// fast lookup by name map
	private final ConcurrentMap<String, Cache> caches = new ConcurrentHashMap<String, Cache>();

	private RedisManager redisManager;

	/**
	 * The Redis key prefix for caches 
	 */
	private String keyPrefix = "rbac_permissions:";
	
	/**
	 * Returns the Redis session keys
	 * prefix.
	 * @return The prefix
	 */
	public String getKeyPrefix() {
		return keyPrefix;
	}

	/**
	 * Sets the Redis sessions key 
	 * prefix.
	 * @param keyPrefix The prefix
	 */
	public void setKeyPrefix(String keyPrefix) {
		this.keyPrefix = keyPrefix;
	}
	
	@SuppressWarnings("unchecked")
	@Override
	public <K, V> Cache<K, V> getCache(String name) throws CacheException {
		logger.debug("获取名称为: " + name + " 的RedisCache实例");
		
		Cache c = caches.get(name);
		
		if (c == null) {

			// initialize the Redis manager instance
			redisManager.init();
			
			// create a new cache instance
			c = new RedisCache<K, V>(redisManager, keyPrefix);
			
			// add it to the cache collection
			caches.put(name, c);
		}
		return c;
	}

	public RedisManager getRedisManager() {
		return redisManager;
	}

	public void setRedisManager(RedisManager redisManager) {
		this.redisManager = redisManager;
	}
}

4.在配置文件中,初始化,redismanager和redisCacheManage,并将redisCachemanager注入到spring的securitymanager的cacheManager中。

5.其中使用实体类

public class RedisCache<K, V> implements Cache<K, V> {
	
	private Logger logger = LoggerFactory.getLogger(this.getClass());
		
	/**
     * The wrapped Jedis instance.
     */
	private RedisManager cache;
	
	/**
	 * The Redis key prefix for the sessions 
	 */
	private String keyPrefix = "shiro_redis_session:";
	
	/**
	 * Returns the Redis session keys
	 * prefix.
	 * @return The prefix
	 */
	public String getKeyPrefix() {
		return keyPrefix;
	}

	/**
	 * Sets the Redis sessions key 
	 * prefix.
	 * @param keyPrefix The prefix
	 */
	public void setKeyPrefix(String keyPrefix) {
		this.keyPrefix = keyPrefix;
	}
	
	/**
	 * 通过一个JedisManager实例构造RedisCache
	 */
	public RedisCache(RedisManager cache){
		 if (cache == null) {
	         throw new IllegalArgumentException("Cache argument cannot be null.");
	     }
	     this.cache = cache;
	}
	
	/**
	 * Constructs a cache instance with the specified
	 * Redis manager and using a custom key prefix.
	 * @param cache The cache manager instance
	 * @param prefix The Redis key prefix
	 */
	public RedisCache(RedisManager cache, 
				String prefix){
		 
		this( cache );
		
		// set the prefix
		this.keyPrefix = prefix;
	}
	
	/**
	 * 获得byte[]型的key
	 * @param key
	 * @return
	 */
	private byte[] getByteKey(K key){
		if(key instanceof String){
			String preKey = this.keyPrefix + key;
    		return preKey.getBytes();
    	}else{
    		return SerializeUtils.serialize(key);
    	}
	}
 	
	@Override
	public V get(K key) throws CacheException {
		logger.debug("根据key从Redis中获取对象 key [" + key + "]");
		try {
			if (key == null) {
	            return null;
	        }else{
	        	byte[] rawValue = cache.get(getByteKey(key));
	        	@SuppressWarnings("unchecked")
				V value = (V)SerializeUtils.deserialize(rawValue);
	        	return value;
	        }
		} catch (Throwable t) {
			throw new CacheException(t);
		}

	}

	@Override
	public V put(K key, V value) throws CacheException {
		logger.debug("根据key从存储 key [" + key + "]");
		 try {
			 	cache.set(getByteKey(key), SerializeUtils.serialize(value));
	            return value;
	        } catch (Throwable t) {
	            throw new CacheException(t);
	        }
	}

	@Override
	public V remove(K key) throws CacheException {
		logger.debug("从redis中删除 key [" + key + "]");
		try {
            V previous = get(key);
            cache.del(getByteKey(key));
            return previous;
        } catch (Throwable t) {
            throw new CacheException(t);
        }
	}

	@Override
	public void clear() throws CacheException {
		logger.debug("从redis中删除所有元素");
		try {
            cache.flushDB();
        } catch (Throwable t) {
            throw new CacheException(t);
        }
	}

	@Override
	public int size() {
		try {
			Long longSize = new Long(cache.dbSize());
            return longSize.intValue();
        } catch (Throwable t) {
            throw new CacheException(t);
        }
	}

	@SuppressWarnings("unchecked")
	@Override
	public Set<K> keys() {
		try {
            Set<byte[]> keys = cache.keys(this.keyPrefix + "*");
            if (CollectionUtils.isEmpty(keys)) {
            	return Collections.emptySet();
            }else{
            	Set<K> newKeys = new HashSet<K>();
            	for(byte[] key:keys){
            		newKeys.add((K)key);
            	}
            	return newKeys;
            }
        } catch (Throwable t) {
            throw new CacheException(t);
        }
	}

	@Override
	public Collection<V> values() {
		try {
            Set<byte[]> keys = cache.keys(this.keyPrefix + "*");
            if (!CollectionUtils.isEmpty(keys)) {
                List<V> values = new ArrayList<V>(keys.size());
                for (byte[] key : keys) {
                    @SuppressWarnings("unchecked")
					V value = get((K)key);
                    if (value != null) {
                        values.add(value);
                    }
                }
                return Collections.unmodifiableList(values);
            } else {
                return Collections.emptyList();
            }
        } catch (Throwable t) {
            throw new CacheException(t);
        }
	}

}

转载于:https://my.oschina.net/u/3045515/blog/1634599

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值