Redis提供Java的操作工具Jedis稍稍实现封装就可以直接拿来使用了,单节点和多节点这个封装就太简单了。Redis默认数据库实例个数0-15即16个实例。正常情况下,我们通过get或者set方法是从db0中取数据。
- redis提供了 select命令,可以通过select index 这个指令,将数据库切换到index所在的那个数据库上
- jedis客户端也提供了对应的方法,可以通过jedis.select(N)来选择对应的数据库
注意:如果redis是集群部署的时候,选择对应的数据库是没用的,因为在redis在进群配置的时候默认使用db0;如果需要远程访问Redis需要适当调整调大连接超时时间。
目录
属性配置
config.properties
#-------------------------REDIS缓存配置------------------------
#REDIS启动;
redisServer=true
#REDIS主机,必须
redisServerHost=192.168.1.111
#REDIS端口,必须
redisServerPort=6379
#REDIS密码,必须
redisServerAuth=dlwy@2019
#REDIS连接超时时间(ms)
redisTimeout=10000
#REDIS最大连接数
redisMaxTotal=50000
#REDIS最大空闲连接数
redisMaxIdle=1000
#REDIS最小空闲连接数
redisMinIdle=500
#REDIS数据库连接实例
redisInstanceIndex=2
#REDIS是否可写入==== APILimit REDIS限流依赖redisServer
redisEnableWrite=true
#REDIS启用护林员缓存,依赖redisEnableWrite
redisCacheHlyInfo=true
#REDIS是否执行初始化==集群可以单独设定一个初始化依赖redisEnableWrite
redisEnableInitData=true
Java读取配置
package com.boonya.cache;
import java.io.File;
import java.net.URISyntaxException;
import org.springframework.stereotype.Controller;
import com.boonya.common.StringUtils;
import com.boonya.xht.util.YWPTUtil;
/**
*
* @function 功能:系统配置属性管理
* @author PJL
* @package com.forestar.cache
* @filename XHTSystemConfig.java
* @time 2019年12月23日 下午2:57:02
*/
@Controller
public class XHTSystemConfig {
// 初始化项目路径
public static String realPath = "";
// 初始化头像路径
public static String photoPath = "";
// 初始化运维日志文件路径
public static String logfilePath = "";
/**
* 默认非redisServer
*/
public static boolean redisServer = false;
/**
* 默认不启用Nginx服务器
*/
public static boolean nginxServer = false;
/**
* Nginx配置地址
*/
public static String nginxFilePath = "";
/**
* 是否单独提供移动端接口服务访问能力
*/
public static boolean isVisitMobileInterface = false;
/**
* 应用访问接口安全验证码
*/
public static String url = "";
/**
* 应用访问接口安全验证码
*/
public static String secureCode = "";
/**
* 代码调试模式
*/
public static boolean isDebug = false;
/**
* 是否启用REDIS缓存护林员信息
*/
public static boolean redisCacheHlyInfo=false;
/**
* 是否启用TOMCAT CLUSTER集群模式
*/
public static boolean clusterModeForTomcat=false;
/**
* TOMCAT CLUSTER集群模式统一附件上传地址基础路径
*/
public static String clusterUploadFilePath="";
/**
* 应用节点是否可写入REDIS
*/
public static boolean redisEnableWrite=false;
/**
* 应用节点是否可初始化数据到REDIS
*/
public static boolean redisEnableInitData=false;
static {
try {
initSettings();
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
public static void initSettings() throws URISyntaxException {
// 系统策略配置相关变量
isDebug = "true".equalsIgnoreCase(YWPTUtil.getYwptConfig("ISDEBUG"));
redisServer="true".equalsIgnoreCase(YWPTUtil.getYwptConfig("redisServer"));
if(redisServer){
redisEnableWrite= "true".equalsIgnoreCase(YWPTUtil.getYwptConfig("redisEnableWrite"));
}
// REDIS可写入初始化数据和集群模式建立才有意义
if(redisEnableWrite){
redisCacheHlyInfo = "true".equalsIgnoreCase(YWPTUtil.getYwptConfig("redisCacheHlyInfo"));
clusterModeForTomcat = "true".equalsIgnoreCase(YWPTUtil.getYwptConfig("clusterModeForTomcat"));
redisEnableInitData= "true".equalsIgnoreCase(YWPTUtil.getYwptConfig("redisEnableInitData"));
}
// 添加配置路径,如果有配置路径,则变更项目路径为配置路径
url = YWPTUtil.getYwptConfig("url");
secureCode = YWPTUtil.getYwptConfig("SecureCode");
nginxFilePath = YWPTUtil.getYwptConfig("nginxFilePath");
if (!StringUtils.IsNullOrEmpty(secureCode)) {
isVisitMobileInterface = true;
}
// 获取文件上传基础路径
if(XHTSystemConfig.clusterModeForTomcat){
clusterUploadFilePath=YWPTUtil.getYwptConfig("clusterUploadFilePath");
realPath=clusterUploadFilePath;
}else{
realPath = XHTSystemConfig.class.getResource("").toURI().getPath();
realPath = realPath.substring(0,realPath.lastIndexOf("/WEB-INF/") + 1);
}
// 获得服务器相对路径
if (!StringUtils.IsNullOrEmpty(nginxFilePath)) {
if (!nginxFilePath.endsWith("/")) {
nginxFilePath += "/";
}
nginxServer = true;
}
/*
* if(RedisUtil.getJedisBoolean() &&
* nginxServer){//如果没有配置redisServer,且启动了nginxServer时,默认启动redisServer
* redisServer = true; }else{ redisServer
* =Boolean.valueOf(redisServerStr); }
*/
// REDIS只通过配置开启,不依赖NGINX
photoPath = realPath + "/upload/eventAttach/eventphoto/";
File file = new File(photoPath);
// 判断文件夹是否存在
if (!file.exists()){
file.mkdirs();// 不存在则创建
}
logfilePath = realPath + "/upload/yw/log/";
file = new File(logfilePath);
// 判断文件夹是否存在
if (!file.exists()){
file.mkdirs();// 不存在则创建
}
}
}
Redis单节点操作
Redis连接池
- 通过读取配置初始化Redis连接池
- 通过参数生成Redis连接池
package com.boonya.webservice.util;
import com.boonya.core.util.StringUtils;
import com.boonya.xht.util.YWPTUtil;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;
public class RedisPool {
/**
* JEDIS连接池
*/
private static JedisPool pool;
/**
* REDIS端口号
*/
private static int port = 6379;
/**
* 最大连接数
*/
private static int maxTotal = 500;
/**
* 最大空闲连接数
*/
private static int maxIdle = 10;
/**
* 最小空闲连接数
*/
private static int minIdle = 5;
/**
* 连接超时时间
*/
private static int timeout = 5000;
/**
* 在取连接时测试连接的可用性
*/
private static boolean testOnBorrow = true;
/**
* 再还连接时不测试连接的可用性
*/
private static boolean testOnReturn = false;
/**
* REDIS数据库ID实例
*/
public static int redisInstanceIndex=0;
private static String host = YWPTUtil.getYwptConfig("redisServerHost");
private static String portStr = YWPTUtil.getYwptConfig("redisServerPort");
private static String auth = YWPTUtil.getYwptConfig("redisServerAuth");
private static String redisTimeout = YWPTUtil.getYwptConfig("redisTimeout");
private static String redisMaxTotal = YWPTUtil.getYwptConfig("redisMaxTotal");
private static String redisMaxIdle = YWPTUtil.getYwptConfig("redisMaxIdle");
private static String redisMinIdle = YWPTUtil.getYwptConfig("redisMinIdle");
private static Boolean redisServer = Boolean.parseBoolean(YWPTUtil.getYwptConfig("redisServer"));
private static String redisInstanceIndexStr= YWPTUtil.getYwptConfig("redisInstanceIndex");
static {
if(!StringUtils.IsNullOrEmpty(redisMaxTotal)){
try {
maxTotal=Integer.valueOf(redisMaxTotal);
} catch (Exception e) {
e.printStackTrace();
}
}
if(!StringUtils.IsNullOrEmpty(redisMaxIdle)){
try {
maxIdle=Integer.valueOf(redisMaxIdle);
} catch (Exception e) {
e.printStackTrace();
}
}
if(!StringUtils.IsNullOrEmpty(redisMinIdle)){
try {
minIdle=Integer.valueOf(redisMinIdle);
} catch (Exception e) {
e.printStackTrace();
}
}
initPool();// 初始化连接池
}
public static Jedis getJedis() {
if(redisServer) {
Jedis jedis= pool.getResource();
if (!StringUtils.IsNullOrEmpty(redisInstanceIndexStr)) {
redisInstanceIndex=Integer.valueOf(redisInstanceIndexStr);
}
jedis.select(redisInstanceIndex);
return jedis;
} else {
return null;
}
}
public static void close(Jedis jedis) {
jedis.close();
}
private static void initPool() {
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(testOnReturn);
config.setBlockWhenExhausted(true);
if(!StringUtils.IsNullOrEmpty(host) && redisServer){
if(!StringUtils.IsNullOrEmpty(portStr)){
port = Integer.parseInt(portStr);
}
if(!StringUtils.IsNullOrEmpty(redisTimeout)){
timeout = Integer.parseInt(redisTimeout);
}
pool = new JedisPool(config, host, port, timeout, auth);
//设置token存活时间为60秒
System.out.println("Redis初始化完成");
}else{
System.out.println("Redis未初始化");
}
}
public static JedisPool generateJedisPool(String host,String portStr,String auth){
JedisPool pool=null;
JedisPoolConfig config = new JedisPoolConfig();
config.setMaxTotal(maxTotal);
config.setMaxIdle(maxIdle);
config.setMinIdle(minIdle);
config.setTestOnBorrow(testOnBorrow);
config.setTestOnReturn(testOnReturn);
config.setBlockWhenExhausted(true);
if(!StringUtils.IsNullOrEmpty(host)){
if(!StringUtils.IsNullOrEmpty(portStr)){
port = Integer.parseInt(portStr);
}
if(!StringUtils.IsNullOrEmpty(redisTimeout)){
timeout = Integer.parseInt(redisTimeout);
}
pool = new JedisPool(config, host, port, timeout, auth);
//设置token存活时间为60秒
System.out.println(host+":"+port+" redis节点初始化完成");
}else{
System.out.println(host+":"+portStr+" redis节点未初始化");
}
return pool;
}
}
Redis Jedis工具类
package com.boonya.webservice.util;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.boonya.xht.util.Constants;
import net.sf.json.JSONArray;
import redis.clients.jedis.GeoCoordinate;
import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.geo.GeoRadiusParam;
/**
* Jedis控制类
* @author PJL
*/
public class RedisUtil {
/**判断是否连接Jedis*/
public static Boolean getJedisBoolean(){
Jedis jedis = null;
boolean result = false;
try {
jedis = RedisPool.getJedis();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null){
result = true;
jedis.close();
}
}
return result;
}
private static Jedis getJedisFromPool(){
return RedisPool.getJedis();
}
//keys
public static Set<String> keys(String key){
Jedis jedis = null;
Set<String> result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.keys(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//get
public static String get(String key){
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//set
public static String set(String key, String value){
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.set(key, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//hset
public static Long hset(String key, String field, String value){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.hset(key, field, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//hget
public static String hget(String key, String field){
Jedis jedis = null;
String result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.hget(key, field);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//hmget
public static List<String> hmget(String key, String[] field){
Jedis jedis = null;
List<String> result = new ArrayList<String>();
try {
jedis = RedisPool.getJedis();
result = jedis.hmget(key, field);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//hget
public static Map<String,String> hgetAll(String key){
Jedis jedis = null;
Map<String,String> result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.hgetAll(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//hdel
public static Long hdel(String key, String... fields){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.hdel(key, fields);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//hkeys
public static Set<String> hkeys(String key){
Jedis jedis = null;
Set<String> result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.hkeys(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//sadd
public static Long sadd(String key, String... members){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.sadd(key, members);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//smembers
public static Set<String> smembers(String key){
Jedis jedis = null;
Set<String> result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.smembers(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//lpush
public static Long lpush(String key, String... strings){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.lpush(key, strings);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//lrange
public static List<String> lrange(String key, long start, long end){
Jedis jedis = null;
List<String> result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.lrange(key, start, end);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//llen
public static Long llen(String key){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.llen(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//del
public static Long del(String key){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.del(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//ttl
public static Long ttl(String key){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.ttl(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//expire
public static Long expire(String key, int seconds){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.expire(key, seconds);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//pexpireAt
public static Long pexpireAt(String key, long millisecondsTimestamp){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisPool.getJedis();
result = jedis.pexpireAt(key, millisecondsTimestamp);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
/**
* 增加地理位置的坐标
* @param key
* @param coordinate
* @param memberName
* @return
*/
public static Long geoadd(String key, GeoCoordinate coordinate, String memberName) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.geoadd(key,coordinate.getLongitude(),coordinate.getLatitude(),memberName);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/**
* 批量添加地理位置
* @param key
* @param memberCoordinateMap
* @return
*/
public static Long geoadd(String key, Map<String, GeoCoordinate> memberCoordinateMap){
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.geoadd(key, memberCoordinateMap);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/**
* 根据给定地理位置坐标获取指定范围内的地理位置集合(返回匹配位置的经纬度 + 匹配位置与给定地理位置的距离 + 从近到远排序,)
* @param key
* @param coordinate
* @param radius
* @return List<GeoRadiusResponse>
*/
public static List<GeoRadiusResponse> georadius(String key, GeoCoordinate coordinate, double radius) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.georadius(key, coordinate.getLongitude(), coordinate.getLatitude(), radius, GeoUnit.KM, GeoRadiusParam.geoRadiusParam().withDist().withCoord().sortAscending());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/**
* 根据给定地理位置获取指定范围内的地理位置集合(返回匹配位置的经纬度 + 匹配位置与给定地理位置的距离 + 从近到远排序,)
* @param key
* @param member
* @param radius
* @return List<GeoRadiusResponse>
*/
public static List<GeoRadiusResponse> georadiusByMember(String key, String member, double radius){
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.georadiusByMember(key, member, radius, GeoUnit.KM, GeoRadiusParam.geoRadiusParam().withDist().withCoord().sortAscending());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/**
* 查询两位置距离
* @param key
* @param member1
* @param member2
* @param unit
* @return
*/
public static Double geoDist(String key, String member1, String member2, GeoUnit unit){
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.geodist(key, member1, member2, unit);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/**
* 可以获取某个地理位置的geohash值
* @param key
* @param members
* @return
*/
public static List<String> geohash(String key, String... members){
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.geohash(key, members);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/**
* 获取地理位置的坐标
* @param key
* @param members
* @return
*/
public static List<GeoCoordinate> geopos(String key, String... members){
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.geopos(key, members);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/** * 向集合中增加一条记录,如果这个值已存在,这个值对应的权重将被置为新的权重
* @param key String
* @param score double 权重
* @param member String 要加入的值,
* @return 状态码 1成功,0已存在member的值
* */
public static long zadd(String key, double score, String member) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.zadd(key, score, member);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
public static long zadd(String key, Map<String, Double> scoreMembers) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.zadd(key, scoreMembers);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/** * 获取集合中元素的数量
* @param key String
* @return 如果返回0则集合不存在
* */
public static long zcard(String key) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.zcard(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/**
* 获取指定权重区间内集合的数量
* @param key String
* @param min double 最小排序位置
* @param max double 最大排序位置
* */
public static long zcount(String key, double min, double max) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.zcount(key, min, max);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/** * 返回指定位置的集合元素,0为第一个元素,-1为最后一个元素
* @param key String
* @param start int 开始位置(包含)
* @param end int 结束位置(包含)
* @return Set<String>
* */
public static Set<String> zrange(String key, int start, int end) {
Jedis jedis = null;
Set<String> set = new HashSet<String>();
try {
jedis = RedisPool.getJedis();
set = jedis.zrange(key, start, end);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return set;
}
/*** 返回指定权重区间的元素集合
* @param key String
* @param min double上限权重
* @param max double 下限权重
* @return Set<String>
* */
public static Set<String> zrangeByScore(String key, double min, double max) {
Jedis jedis = null;
Set<String> set = new HashSet<String>();
try {
jedis = RedisPool.getJedis();
set = jedis.zrangeByScore(key, min, max);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return set;
}
/** * 获取指定值在集合中的位置,集合排序从低到高
* @param key String
* @param member String
* @return long 位置
* */
public static long zrank(String key, String member) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.zrank(key, member);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/** * 获取指定值在集合中的位置,集合排序从高到低
* @param key String
* @param member String
* @return long 位置
* */
public static long zrevrank(String key, String member) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.zrevrank(key, member);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/** * 从集合中删除成员
* @param key String
* @param member String
* @return 返回1成功
* */
public static long zrem(String key, String... member) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.zrem(key, member);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/** * 删除
* @param key
* @return
*/
public static long zrem(String key) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.del(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/** * 删除给定位置区间的元素
* @param key String
* @param start int 开始区间,从0开始(包含)
* @param end int 结束区间,-1为最后一个元素(包含)
* @return 删除的数量
* */
public static long zremrangeByRank(String key, int start, int end) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.zremrangeByRank(key, start, end);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/*** 删除给定权重区间的元素
* @param key String
* @param min double 下限权重(包含)
* @param max double上限权重(包含)
* @return 删除的数量
* */
public static long zremrangeByScore(String key, double min, double max) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.zremrangeByScore(key, min, max);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/**
* 获取给定区间的元素,原始按照权重由高到低排序
* @param key String
* @param start int
* @param end int
* @return Set<String>
* */
public static Set<String> zrevrange(String key, int start, int end) {
Jedis jedis = null;
Set<String> set = new HashSet<String>();
try {
jedis = RedisPool.getJedis();
set = jedis.zrevrange(key, start, end);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return set;
}
/** * 获取给定值在集合中的权重
* @param key String
* @param member String
* @return double 权重
* */
public static double zscore(String key, String member) {
Jedis jedis = null;
try {
jedis = RedisPool.getJedis();
return jedis.zscore(key, member);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
}
Redis多节点操作
Redis节点管理
package com.boonya.webservice.util;
import java.util.concurrent.ConcurrentHashMap;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import com.boonya.common.StringUtils;
import com.boonya.util.Util;
/**
*
* @author PJL
*
* @note 功能描述:TODO Redis节点管理
* @package com.boonya.webservice.util
* @filename RedisNodeManger.java
* @date 2019年5月9日 下午6:57:04
*/
public class RedisNodeManger {
private static boolean dwRedisFilter =false ;
private static ConcurrentHashMap<String, JedisPool> redisNodes=new ConcurrentHashMap<String, JedisPool>();
static {
init();
}
public static boolean isDwRedisFilter(){
return dwRedisFilter;
}
private static void init(){
String connections=Util.getConfig("dwRedisConnections");
if(!StringUtils.IsNullOrEmpty(connections)){
String nodes[]=connections.split(",");
for (String node : nodes) {
parseNode(node);
}
if(redisNodes.size()>0){
dwRedisFilter=true;
}
}
}
private static void parseNode(String node){
String[] values=node.split("#");
String dwCode=values[0];
String host=values[1];
String port=values[2];
String auth=values[3];
JedisPool pool=RedisPool.generateJedisPool(host, port, auth);
if(!StringUtils.IsNullOrEmpty(dwCode)){
if(pool!=null)redisNodes.put(dwCode, pool);
}
}
public static Jedis getJedis(String dwCode){
if(redisNodes.containsKey(dwCode)){
return redisNodes.get(dwCode).getResource();
}
return null;
}
public static boolean hasRedisNode(String dwCode){
return redisNodes.containsKey(dwCode);
}
}
Redis节点管理工具类
package com.boonya.webservice.util;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import com.boonya.xht.util.Constants;
import net.sf.json.JSONArray;
import redis.clients.jedis.GeoCoordinate;
import redis.clients.jedis.GeoRadiusResponse;
import redis.clients.jedis.GeoUnit;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.params.geo.GeoRadiusParam;
/**
* Jedis控制类
* @author PJL
*/
public class RedisNodeManagerUtil {
/**判断是否连接Jedis*/
public static Boolean getJedisBoolean(String node){
Jedis jedis = null;
boolean result = false;
try {
jedis = RedisNodeManger.getJedis(node);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null){
result = true;
jedis.close();
}
}
return result;
}
private static Jedis getJedisFromPool(String node){
return RedisNodeManger.getJedis(node);
}
//keys
public static Set<String> keys(String node,String key){
Jedis jedis = null;
Set<String> result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.keys(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//get
public static String get(String node,String key){
Jedis jedis = null;
String result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.get(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//set
public static String set(String node,String key, String value){
Jedis jedis = null;
String result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.set(key, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//hset
public static Long hset(String node,String key, String field, String value){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.hset(key, field, value);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//hget
public static String hget(String node,String key, String field){
Jedis jedis = null;
String result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.hget(key, field);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//hmget
public static List<String> hmget(String node,String key, String[] field){
Jedis jedis = null;
List<String> result = new ArrayList<String>();
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.hmget(key, field);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//hgetall
public static Map<String,String> hgetAll(String node,String key){
Jedis jedis = null;
Map<String,String> result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.hgetAll(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//hdel
public static Long hdel(String node,String key, String... fields){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.hdel(key, fields);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//hkeys
public static Set<String> hkeys(String node,String key){
Jedis jedis = null;
Set<String> result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.hkeys(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//sadd
public static Long sadd(String node,String key, String... members){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.sadd(key, members);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//smembers
public static Set<String> smembers(String node,String key){
Jedis jedis = null;
Set<String> result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.smembers(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
/**
* 在List头部插入元素
* @param node
* @param key
* @param strings
* @return
*/
public static Long lpush(String node,String key, String... strings){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.lpush(key, strings);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
/**
* 在List尾部插入元素
* @param node
* @param key
* @param strings
* @return
*/
public static Long rpush(String node,String key, String... strings){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.rpush(key, strings);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//lrange
public static List<String> lrange(String node,String key, long start, long end){
Jedis jedis = null;
List<String> result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.lrange(key, start, end);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//llen
public static Long llen(String node,String key){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.llen(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//del
public static Long del(String node,String key){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.del(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//ttl
public static Long ttl(String node,String key){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.ttl(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//expire
public static Long expire(String node,String key, int seconds){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.expire(key, seconds);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
//pexpireAt
public static Long pexpireAt(String node,String key, long millisecondsTimestamp){
Jedis jedis = null;
Long result = null;
try {
jedis = RedisNodeManger.getJedis(node);
result = jedis.pexpireAt(key, millisecondsTimestamp);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (jedis != null) jedis.close();
}
return result;
}
/**
* 增加地理位置的坐标
* @param key
* @param coordinate
* @param memberName
* @return
*/
public static Long geoadd(String node,String key, GeoCoordinate coordinate, String memberName) {
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.geoadd(key,coordinate.getLongitude(),coordinate.getLatitude(),memberName);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/**
* 批量添加地理位置
* @param key
* @param memberCoordinateMap
* @return
*/
public static Long geoadd(String node,String key, Map<String, GeoCoordinate> memberCoordinateMap){
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.geoadd(key, memberCoordinateMap);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/**
* 根据给定地理位置坐标获取指定范围内的地理位置集合(返回匹配位置的经纬度 + 匹配位置与给定地理位置的距离 + 从近到远排序,)
* @param key
* @param coordinate
* @param radius
* @return List<GeoRadiusResponse>
*/
public static List<GeoRadiusResponse> georadius(String node,String key, GeoCoordinate coordinate, double radius) {
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
// System.out.println("---------------"+jedis.info());
return jedis.georadius(key, coordinate.getLongitude(), coordinate.getLatitude(), radius, GeoUnit.KM,GeoRadiusParam.geoRadiusParam().withCoord());
// return jedis.georadius(key, coordinate.getLongitude(), coordinate.getLatitude(), radius, GeoUnit.KM, GeoRadiusParam.geoRadiusParam().withDist().withCoord().sortAscending());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/**
* 根据给定地理位置获取指定范围内的地理位置集合(返回匹配位置的经纬度 + 匹配位置与给定地理位置的距离 + 从近到远排序,)
* @param key
* @param member
* @param radius
* @return List<GeoRadiusResponse>
*/
public static List<GeoRadiusResponse> georadiusByMember(String node,String key, String member, double radius){
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.georadiusByMember(key, member, radius, GeoUnit.KM, GeoRadiusParam.geoRadiusParam().withDist().withCoord().sortAscending());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/**
* 查询两位置距离
* @param key
* @param member1
* @param member2
* @param unit
* @return
*/
public static Double geoDist(String node,String key, String member1, String member2, GeoUnit unit){
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.geodist(key, member1, member2, unit);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/**
* 可以获取某个地理位置的geohash值
* @param key
* @param members
* @return
*/
public static List<String> geohash(String node,String key, String... members){
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.geohash(key, members);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/**
* 获取地理位置的坐标
* @param key
* @param members
* @return
*/
public static List<GeoCoordinate> geopos(String node,String key, String... members){
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.geopos(key, members);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return null;
}
/** * 向集合中增加一条记录,如果这个值已存在,这个值对应的权重将被置为新的权重
* @param key String
* @param score double 权重
* @param member String 要加入的值,
* @return 状态码 1成功,0已存在member的值
* */
public static long zadd(String node,String key, double score, String member) {
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.zadd(key, score, member);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
public static long zadd(String node,String key, Map<String, Double> scoreMembers) {
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.zadd(key, scoreMembers);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/** * 获取集合中元素的数量
* @param key String
* @return 如果返回0则集合不存在
* */
public static long zcard(String node,String key) {
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.zcard(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/**
* 获取指定权重区间内集合的数量
* @param key String
* @param min double 最小排序位置
* @param max double 最大排序位置
* */
public static long zcount(String node,String key, double min, double max) {
Jedis jedis = null;
try {
jedis =RedisNodeManger.getJedis(node);
return jedis.zcount(key, min, max);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/** * 返回指定位置的集合元素,0为第一个元素,-1为最后一个元素
* @param key String
* @param start int 开始位置(包含)
* @param end int 结束位置(包含)
* @return Set<String>
* */
public static Set<String> zrange(String node,String key, int start, int end) {
Jedis jedis = null;
Set<String> set = new HashSet<String>();
try {
jedis = RedisNodeManger.getJedis(node);
set = jedis.zrange(key, start, end);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return set;
}
/*** 返回指定权重区间的元素集合
* @param key String
* @param min double上限权重
* @param max double 下限权重
* @return Set<String>
* */
public static Set<String> zrangeByScore(String node,String key, double min, double max) {
Jedis jedis = null;
Set<String> set = new HashSet<String>();
try {
jedis = RedisNodeManger.getJedis(node);
set = jedis.zrangeByScore(key, min, max);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return set;
}
/** * 获取指定值在集合中的位置,集合排序从低到高
* @param key String
* @param member String
* @return long 位置
* */
public static long zrank(String node,String key, String member) {
Jedis jedis = null;
try {
jedis =RedisNodeManger.getJedis(node);
return jedis.zrank(key, member);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/** * 获取指定值在集合中的位置,集合排序从高到低
* @param key String
* @param member String
* @return long 位置
* */
public static long zrevrank(String node,String key, String member) {
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.zrevrank(key, member);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/** * 从集合中删除成员
* @param key String
* @param member String
* @return 返回1成功
* */
public static long zrem(String node,String key, String... member) {
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.zrem(key, member);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/** * 删除
* @param key
* @return
*/
public static long zrem(String node,String key) {
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.del(key);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/** * 删除给定位置区间的元素
* @param key String
* @param start int 开始区间,从0开始(包含)
* @param end int 结束区间,-1为最后一个元素(包含)
* @return 删除的数量
* */
public static long zremrangeByRank(String node,String key, int start, int end) {
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.zremrangeByRank(key, start, end);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/*** 删除给定权重区间的元素
* @param key String
* @param min double 下限权重(包含)
* @param max double上限权重(包含)
* @return 删除的数量
* */
public static long zremrangeByScore(String node,String key, double min, double max) {
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.zremrangeByScore(key, min, max);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
/**
* 获取给定区间的元素,原始按照权重由高到低排序
* @param key String
* @param start int
* @param end int
* @return Set<String>
* */
public static Set<String> zrevrange(String node,String key, int start, int end) {
Jedis jedis = null;
Set<String> set = new HashSet<String>();
try {
jedis = RedisNodeManger.getJedis(node);
set = jedis.zrevrange(key, start, end);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return set;
}
/** * 获取给定值在集合中的权重
* @param key String
* @param member String
* @return double 权重
* */
public static double zscore(String node,String key, String member) {
Jedis jedis = null;
try {
jedis = RedisNodeManger.getJedis(node);
return jedis.zscore(key, member);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (null != jedis)
jedis.close();
}
return -1;
}
}
Redis分布式锁
分布式锁一般有三种实现方式:1. 数据库乐观锁;2. 基于Redis的分布式锁;3. 基于ZooKeeper的分布式锁。
首先,为了确保分布式锁可用,我们至少要确保锁的实现同时满足以下四个条件:
- 互斥性。在任意时刻,只有一个客户端能持有锁。
- 不会发生死锁。即使有一个客户端在持有锁的期间崩溃而没有主动解锁,也能保证后续其他客户端能加锁。
- 具有容错性。只要大部分的Redis节点正常运行,客户端就可以加锁和解锁。
- 解铃还须系铃人。加锁和解锁必须是同一个客户端,客户端自己不能把别人加的锁给解了。
package com.boonya.webservice.util;
import java.util.Collections;
import redis.clients.jedis.Jedis;
/**
*
* @function 功能:REDIS分布式锁
* @author PJL
* @package com.boonya.webservice.util
* @filename RedisDistributedLock.java
* @time 2019年12月20日 上午11:40:10
*/
public class RedisDistributedLock {
private static final String LOCK_SUCCESS = "OK";
private static final String SET_IF_NOT_EXIST = "NX";
private static final String SET_WITH_EXPIRE_TIME = "PX";
private static final Long RELEASE_SUCCESS = 1L;
/**
* 尝试获取分布式锁[记得关闭连接]
*
* @param lockKey
* 锁
* @param requestId
* 请求标识
* @param expireTime
* 超期时间
* @return 是否获取成功
*/
public static boolean tryGetDistributedLock(String lockKey, String requestId, int expireTime) {
Jedis jedis=null;
try {
jedis = RedisPool.getJedis();
String result = jedis.set(lockKey, requestId, SET_IF_NOT_EXIST,
SET_WITH_EXPIRE_TIME, expireTime);
if (LOCK_SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(null!=jedis){
jedis.close();
}
}
return false;
}
/**
* 释放分布式锁[记得关闭连接]
*
* @param lockKey
* 锁
* @param requestId
* 请求标识
* @return 是否释放成功
*/
public static boolean releaseDistributedLock(String lockKey,String requestId) {
Jedis jedis=null;
try {
jedis = RedisPool.getJedis();
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Object result = jedis.eval(script, Collections.singletonList(lockKey),
Collections.singletonList(requestId));
if (RELEASE_SUCCESS.equals(result)) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}finally{
if(null!=jedis){
jedis.close();
}
}
return false;
}
}
注意:redis连接用完后必须要关闭。