java redis 配置使用

本文详细介绍了Java中如何配置并使用Redis,包括RedisKit、Cache、RedisCache、CacheFactory的使用步骤,以及如何进行调用操作。同时提到了配置文件redis.json,和依赖的redisson-all-2.8.0.jar包。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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 操作辅助工具 <br />
 * 
 * @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();
			}
		}
	}

	/**
	 * 断开连接<br />
	 * 断开连接后,如果需要重新使用,只能重新获取实例了
	 * 
	 * @category 断开连接
	 */
	public void disconnect() {
		if (client != null) {
			client.shutdown();
			client = null;
		}
	}

	/**
	 * set 不设置过期时间
	 * 
	 * @category set
	 * @param key
	 * @param value
	 * @return
	 */
	private <T> RBucket<T> _set(String key, T value) {
		RBucket<T> bucket = client.getBucket(key);
		bucket.set(value);
		return bucket;
	}

	/**
	 * 获取缓存bucket
	 * 
	 * @category 获取缓存bucket
	 * @author prz
	 * @date 2017年7月28日
	 * @param key
	 * @return
	 * @return RBucket<T>
	 */
	private <T> RBucket<T> _getBucket(String key) {
		return client.<T>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 <br />
	 * 不设置过期时间
	 * 
	 * @category set
	 * @param key
	 * @param value
	 */
	public <T> void set(String key, T value) {
		_set(key, value);
	}

	/**
	 * cache set<br />
	 * x毫秒后过期
	 * 
	 * @category cache set
	 * @param key
	 *            键
	 * @param value
	 *            值
	 * @param timeout
	 *            x毫秒后过期
	 */
	public <T> 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 <T> 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 <br />
	 * 支持所有数据处理
	 * 
	 * @category get
	 * @param key
	 * @return T
	 */
	public <T> T get(String key) {
		return this.<T>_getBucket(key).get();
	}

	/**
	 * delete <br />
	 * 支持所有数据类似处理
	 * 
	 * @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<Object> 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 <T> SortedSet<T> zset(String key) {
		return client.getSortedSet(key);
	}

	/**
	 * 取排序集合第一个
	 * 
	 * @category 取排序集合第一个
	 * @param key
	 * @return
	 */
	public <T> T zsetFirst(String key) {
		return this.<T>zset(key).first();
	}

	/**
	 * 取排序集合最后一个
	 * 
	 * @category 取排序集合最后一个
	 * @param key
	 * @return
	 */
	public <T> T zsetLast(String key) {
		return this.<T>zset(key).last();
	}

	/**
	 * 排序集合添加一个
	 * 
	 * @category 排序集合添加一个
	 * @param key
	 * @param value
	 */
	public <T> void zsetAdd(String key, T value) {
		zset(key).add(value);
	}

	/**
	 * 获取所有的key
	 * 
	 * @category 获取所有的key
	 * @return
	 */
	public List<String> keys() {
		RKeys rKeys = client.getKeys();
		Iterator<String> iterator = rKeys.getKeys().iterator();
		List<String> keys = new ArrayList<String>();
		while (iterator.hasNext()) {
			keys.add(iterator.next());
		}
		return keys;
	}
	
	/** 
     * 获取消息的Topic 
     * @param redisson 
     * @param objectName 
     * @return 
     */  
    public <M> RTopic<M> getRTopic(String objectName){  
         RTopic<M> 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<String> list = (RList<String>)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 <T> void set(String key, T value, long timeout);

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

	/**
	 * 获取缓存
	 * 
	 * @category 获取缓存
	 * @param key
	 * @return Object 缓存对象
	 */
	public <T> 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 <T> void ladd(String key, T value);
	
	/**
	 * 获得 key 的list数据缓存  
	 * @param: @param key
	 * @param: @return      
	 * @return: RList<String>      
	 * @throws
	 */
	public List<LogObject> 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> T get(String key) {
		return kit().get(key);
	}

	@Override
	public <T> 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 <T> void setExpireAt(String key, T value, long expireAt) {
		kit().<T>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 <T> void ladd(String key, T value){
		kit().ladd(key, value);
	}
	
	/**
	 * 获得 key 的list数据缓存     
	 * @param: @param key
	 * @param: @return      
	 * @return: RList<String>      
	 * @throws
	 */
	public List<LogObject> 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 包

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值