java redis 配置使用

1.RedisKit

package com.seryo.util;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Random;
import java.util.Set;
import java.util.SortedSet;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

import org.redisson.Redisson;
import org.redisson.api.RBucket;
import org.redisson.api.RCountDownLatch;
import org.redisson.api.RKeys;
import org.redisson.api.RList;
import org.redisson.api.RTopic;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

/**
 * redis 操作辅助工具 
* * @category redis 操作辅助工具 * @className RedisKit * @package com.xy.redis * @description */ public class RedisKit { private static interface Helper { RedisKit INSTANCE = new RedisKit(); } private RedissonClient client; private RedisKit() { } private static ReentrantLock lock = new ReentrantLock(); /** * 连接redis 服务 * * @category 连接redis 服务 */ private void connect() { if (client == null || client.isShutdown() || client.isShuttingDown()) { lock.lock(); try { if (client == null || client.isShutdown() || client.isShuttingDown()) { Config cfg = Config.fromJSON(RedisKit.class.getClassLoader().getResourceAsStream("redis.json")); client = Redisson.create(cfg); } } catch (Exception e) { throw new RuntimeException(e); } finally { lock.unlock(); } } } /** * 断开连接
* 断开连接后,如果需要重新使用,只能重新获取实例了 * * @category 断开连接 */ public void disconnect() { if (client != null) { client.shutdown(); client = null; } } /** * set 不设置过期时间 * * @category set * @param key * @param value * @return */ private RBucket _set(String key, T value) { RBucket bucket = client.getBucket(key); bucket.set(value); return bucket; } /** * 获取缓存bucket * * @category 获取缓存bucket * @author prz * @date 2017年7月28日 * @param key * @return * @return RBucket */ private RBucket _getBucket(String key) { return client.getBucket(key); } /** * 使缓存timeout毫秒后过期 * * @category 使缓存timeout毫秒后过期 * @author prz * @date 2017年7月28日 * @param bucket * @param timeout */ private boolean _expire(RBucket bucket, long timeout) { return bucket.expire(timeout, TimeUnit.MILLISECONDS); } /** * 使缓存timeout毫秒后过期 * * @category 使缓存timeout毫秒后过期 * @author prz * @date 2017年7月28日 * @param key * @param timeout */ private boolean _expire(String key, long timeout) { return _expire(_getBucket(key), timeout); } /** * 使缓存在expireAt时间点过期 * * @category 使缓存在expireAt时间点过期 * @param bucket * @param expireAt */ private boolean _expireAt(RBucket bucket, long expireAt) { return bucket.expireAt(expireAt); } /** * 使缓存在expireAt时间点过期 * * @category 使缓存在expireAt时间点过期 * @param key * @param expireAt */ private boolean _expireAt(String key, long expireAt) { return _expireAt(_getBucket(key), expireAt); } /** * set
* 不设置过期时间 * * @category set * @param key * @param value */ public void set(String key, T value) { _set(key, value); } /** * cache set
* x毫秒后过期 * * @category cache set * @param key * 键 * @param value * 值 * @param timeout * x毫秒后过期 */ public void set(String key, T value, long timeout) { RBucket bucket = _set(key, value); _expire(bucket, timeout); } /** * cache set 在某个时间点后过期 * * @category cache set * @param key * 键 * @param value * 值 * @param expireAt * 时间节点(long表示) */ public void setExpAt(String key, T value, long expireAt) { RBucket bucket = _set(key, value); _expireAt(bucket, expireAt); } /** * 判断是否存在某个key * * @category 判断是否存在某个key * @param key * @return boolean */ public boolean exists(String key) { return client.getBucket(key).isExists(); } /** * get
* 支持所有数据处理 * * @category get * @param key * @return T */ public T get(String key) { return this._getBucket(key).get(); } /** * delete
* 支持所有数据类似处理 * * @category delete * @param key * @return boolean */ public boolean del(String key) { return _getBucket(key).delete(); } /** * 使缓存timeout后超期 * * @category 使缓存timeout后超期 * @param key * @param timeout * @return */ public boolean expire(String key, long timeout) { return _expire(key, timeout); } /** * 使缓存expireAt时刻超期 * * @category 使缓存expireAt时刻超期 * @param key * @param expireAt * @return boolean */ public boolean expireAt(String key, long expireAt) { return _expireAt(key, expireAt); } /** * 清空过期时间,即持久化 * * @category 清空过期时间,即持久化 * @param key * @return boolean */ public boolean persist(String key) { return _getBucket(key).clearExpire(); } /** * 存储字符串 * * @category 存储字符串 * @param key * @param value */ public void str(String key, String value) { set(key, value); } /** * 获取字符串 * * @category 获取字符串 * @param key * @return */ public String str(String key) { return (String) get(key); } /** * 获取list * * @category 获取list * @param key * @return */ public List list(String key) { return client.getList(key); } /** * 保存list * * @category 保存list * @param key * @param list * @return */ public boolean list(String key, List list) { client.getList(key).delete(); return client.getList(key).addAll(list); } /** * 获取list元素 * * @category 获取list元素 * @param key * @param index * @return */ public Object lget(String key, int index) { return list(key).get(index); } /** * 向指定list里面添加数据 * * @category 向指定list里面添加数据 * @param key * @param obj */ public void ladd(String key, Object obj) { client.getList(key).add(obj); } /** * 向指定list里面添加数据 * * @category 向指定list里面添加数据 * @param key * @param list */ public void ladd(String key, List list) { client.getList(key).addAll(list); } /** * 向指定list里面的指定位置添加数据 * * @category 向指定list里面的指定位置添加数据 * @param index * @param key * @param obj */ public void ladd(int index, String key, Object obj) { client.getList(key).add(index, obj); } /** * 获取set * * @category 获取set * @param key * @return */ public Set sset(String key) { return client.getSet(key); } /** * 往set中添加元素 * * @category 往set中添加元素 * @param key * @param value */ public void sadd(String key, Object value) { client.getSet(key).add(value); } /** * 往set中添加元素 * * @category 往set中添加元素 * @param key * @param set */ public void sadd(String key, Set set) { client.getSet(key).addAll(set); } /** * 获取sorted set * * @category 获取sorted set * @param key */ public SortedSet zset(String key) { return client.getSortedSet(key); } /** * 取排序集合第一个 * * @category 取排序集合第一个 * @param key * @return */ public T zsetFirst(String key) { return this.zset(key).first(); } /** * 取排序集合最后一个 * * @category 取排序集合最后一个 * @param key * @return */ public T zsetLast(String key) { return this.zset(key).last(); } /** * 排序集合添加一个 * * @category 排序集合添加一个 * @param key * @param value */ public void zsetAdd(String key, T value) { zset(key).add(value); } /** * 获取所有的key * * @category 获取所有的key * @return */ public List keys() { RKeys rKeys = client.getKeys(); Iterator iterator = rKeys.getKeys().iterator(); List keys = new ArrayList(); while (iterator.hasNext()) { keys.add(iterator.next()); } return keys; } /** * 获取消息的Topic * @param redisson * @param objectName * @return */ public RTopic getRTopic(String objectName){ RTopic rTopic=client.getTopic(objectName); return rTopic; } /** * 获取记数锁 * @param redisson * @param objectName * @return */ public RCountDownLatch getRCountDownLatch(String objectName){ RCountDownLatch rCountDownLatch=client.getCountDownLatch(objectName); return rCountDownLatch; } /** * 使用ip地址和端口创建Redisson * @param ip * @param port * @return */ public Redisson getRedisson(String ip,String port){ Config config=new Config(); config.useSingleServer().setAddress(ip+":"+port); Redisson redisson=(Redisson) Redisson.create(config); System.out.println("成功连接Redis Server"+"\t"+"连接"+ip+":"+port+"服务器"); return redisson; } // ------------ 静态方法 ------------ /** * 获取实例 * * @category 获取实例 * @return */ public static RedisKit getInstance() { Helper.INSTANCE.connect(); return Helper.INSTANCE; } public static void main(String[] args) { RedisKit kit = getInstance(); Random rd = new Random(System.currentTimeMillis()); new Thread(()->{ for(int i = 1;i<100;i++) { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } kit.ladd("list","201807261005-" + i); } }).start(); new Thread(()->{ for(int i = 1;i<100;i++) { try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } RList list = (RList)kit.list("list"); System.out.println("初始化的list: " + list); if(list.size() > 0) { String key = list.remove(rd.nextInt(list.size())); boolean exists = kit.exists(key); System.out.println( "key: " + key + "已过期,移除"); } //list.clear(); //kit.list("list",new ArrayList<>()); System.out.println("处理后的list : " + list); System.out.println("\n"); } }).start(); new Timer().schedule(new TimerTask() { @Override public void run() { } }, 500); } }

2.Cache

package com.seryo.cache;

import java.util.List;

import com.seryo.vo.LogObject;

/**
 * 缓存接口
 * 
 * @category 缓存接口
 * @version 1.0
 */
public interface Cache {

	public static final String CACHE_FLAG = "Cache";

	/**
	 * 设置缓存
	 * 
	 * @category 设置缓存
	 * @param key
	 * @param value
	 * @param timeout
	 *            ms
	 */
	public  void set(String key, T value, long timeout);

	/**
	 * 设置缓存
	 * 
	 * @category 设置缓存
	 * @param key
	 * @param value
	 * @param expireAt
	 *            ms
	 */
	public  void setExpireAt(String key, T value, long expireAt);

	/**
	 * 获取缓存
	 * 
	 * @category 获取缓存
	 * @param key
	 * @return Object 缓存对象
	 */
	public  T get(String key);

	/**
	 * 使某个缓存过期
	 * 
	 * @category 使某个缓存过期
	 * @param key
	 * @param timeout
	 * @return T 缓存对象
	 */
	public boolean expire(String key, long timeout);

	/**
	 * 使得某个缓存在某个时刻过期
	 * 
	 * @category 使得某个缓存在某个时刻过期
	 * @param key
	 * @param expireAt
	 */
	public boolean expireAt(String key, long expireAt);

	/**
	 * 判断某个缓存是否存在
	 * 
	 * @category 判断某个缓存是否存在
	 * @param key
	 * @return boolean
	 */
	public boolean exist(String key);

	/**
	 * 删除缓存
	 * 
	 * @category 删除缓存
	 * @author prz
	 * @date 2017年7月28日
	 * @param key
	 * @return boolean
	 */
	public boolean del(String key);
	
	/**
	 * 添加key 的list数据缓存  
	 * @param: @param key
	 * @param: @param value      
	 * @return: void      
	 * @throws
	 */
	public  void ladd(String key, T value);
	
	/**
	 * 获得 key 的list数据缓存  
	 * @param: @param key
	 * @param: @return      
	 * @return: RList      
	 * @throws
	 */
	public List list(String key);
}

3.RedisCache

package com.seryo.cache;

import java.util.List;

import org.redisson.api.RList;

import com.seryo.util.RedisKit;
import com.seryo.vo.LogObject;

/**
 * redis cache
 * 
 * @category redis cache
 * @version 1.0
 */
public class RedisCache implements Cache {

	/**
	 * 获取redis 工具
	 * 
	 * @category 获取redis 工具
	 * @return RedisKit
	 */
	private RedisKit kit() {
		return RedisKit.getInstance();
	}

	@Override
	public  T get(String key) {
		return kit().get(key);
	}

	@Override
	public  void set(String key, T value, long timeout) {
		kit().set(key, value, timeout);
	}

	@Override
	public boolean expire(String key, long timeout) {
		return kit().expire(key, timeout);
	}

	@Override
	public boolean exist(String key) {
		return kit().exists(key);
	}

	@Override
	public  void setExpireAt(String key, T value, long expireAt) {
		kit().setExpAt(key, value, expireAt);
	}

	@Override
	public boolean expireAt(String key, long expireAt) {
		return kit().expireAt(key, expireAt);
	}

	@Override
	public boolean del(String key) {
		return kit().del(key);
	}
	
	/**
	 * 添加key 的list数据缓存   
	 * @param: @param key
	 * @param: @param value      
	 * @return: void      
	 * @throws
	 */
	public  void ladd(String key, T value){
		kit().ladd(key, value);
	}
	
	/**
	 * 获得 key 的list数据缓存     
	 * @param: @param key
	 * @param: @return      
	 * @return: RList      
	 * @throws
	 */
	public List list(String key){ 
		return  kit().list(key);
	}
}

4.CacheFactory

package com.seryo.cache;

import com.seryo.util.StringUtils;

public class CacheFactory {

	public static final String REDIS = "redis";
	public static final String EHCACHE_DEFAULT_CACHE = "ehcache_default_cache";

	public static Cache build(String key) {
		if (StringUtils.isBlank(key)) {
			throw new RuntimeException("不存在的缓存工具");
		}
		if (key.equalsIgnoreCase(REDIS)) {
			return new RedisCache();
		} else if(key.equalsIgnoreCase(EHCACHE_DEFAULT_CACHE)){
			return new EhcacheDefaultCache();
		}else{
			throw new RuntimeException("不存在的缓存工具");
		}
	}
}

5.调用

Cache cache = CacheFactory.build(CacheFactory.REDIS);
cache.get(key);// 获取缓存信息
 cache.set(key, 数据, 30 * 60 * 1000L);// 存放缓存30分钟

6.redis.json

{
	"singleServerConfig" : {
		"address" : "redis://(ip):6379"
	},
	"threads" : 1000,
	"useLinuxNativeEpoll" : false
}

redisson-all-2.8.0.jar 包

你可能感兴趣的:(java,缓存)