记得上下班打卡 | git大法好,push需谨慎

Commit 27847819 authored by anjiabin's avatar anjiabin

redis多数据源

parent 66cd5672
package com.liquidnet.common.cache.redis.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.StringUtils;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: AbstractRedisConfig
* @Package com.liquidnet.common.cache.redis.config
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/10/20 18:21
*/
@Slf4j
public abstract class AbstractRedisConfig {
public int defaultDb = 0;
public int totalDbs = 1;
public static Map<Integer, RedisTemplate<String, Object>> redisTemplateMap = new HashMap<>();
abstract String getHost();
abstract int getPort();
abstract String getPassword();
abstract int getMaxActive();
abstract int getMaxIdle();
abstract int getMinIdle();
abstract int getMaxWait();
abstract List<Integer> getDbs();
@PostConstruct
public void initRedisTemp() throws Exception {
log.info("###### START 初始化 Redis "+this.getClass().getSimpleName()+"连接池 START ######");
if(StringUtils.isEmpty(getHost())||getHost().equalsIgnoreCase("null")){
log.info("无配置,不需要初始化!");
return;
}
defaultDb = this.getDbs().get(0);
if(this.getDbs().size()==2&&this.getDbs().get(1)!=null){
totalDbs = this.getDbs().get(1);
log.info("init totalDbs : {}",totalDbs);
for (int i = 0;i < totalDbs; i++) {
log.info("###### 正在加载Redis-db-" + i+ " ######");
redisTemplateMap.put(i, getRedisTemplate(i));
}
}else{
log.info("init defaultDb : {}",defaultDb);
redisTemplateMap.put(defaultDb, getRedisTemplate(defaultDb));
}
log.info("###### END 初始化 Redis 连接池 END ######");
}
private RedisTemplate<String, Object> getRedisTemplate(int dbNo) {
return getRedisTemplate(getDbFactory(dbNo));
}
private LettuceConnectionFactory getDbFactory(int dbNo){
LettuceConnectionFactory factory = new LettuceConnectionFactory(getRedisConfig(dbNo), getClientConfig());
factory.afterPropertiesSet();//必须初始化实例
return factory;
}
private RedisStandaloneConfiguration getRedisConfig(int dbNo) {
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
config.setHostName(this.getHost());
config.setPort(this.getPort());
config.setPassword(this.getPassword());
config.setDatabase(dbNo);
return config;
}
private LettuceClientConfiguration getClientConfig() {
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(this.getMaxActive());
poolConfig.setMaxIdle(this.getMaxIdle());
poolConfig.setMinIdle(this.getMinIdle());
poolConfig.setMaxWaitMillis(this.getMaxWait());
return LettucePoolingClientConfiguration.builder().poolConfig(poolConfig).build();
}
private RedisTemplate<String, Object> getRedisTemplate(LettuceConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
setSerializer(redisTemplate);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
public RedisTemplate<String, Object> getRedisTemplateByDb(int db){
return redisTemplateMap.get(db);
}
@Bean
public RedisTemplate redisTemplate() {
LettuceConnectionFactory factory = null;
if(totalDbs==1){
factory = getDbFactory(defaultDb);
}else{
factory = getDbFactory(totalDbs-1);
}
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
setSerializer(redisTemplate);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public StringRedisTemplate stringRedisTemplate() {
LettuceConnectionFactory factory = null;
if(totalDbs==1){
factory = getDbFactory(defaultDb);
}else{
factory = getDbFactory(totalDbs-1);
}
StringRedisTemplate redisTemplate = new StringRedisTemplate();
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
private void setSerializer(RedisTemplate<String, Object> template) {
Jackson2JsonRedisSerializer j2jrs = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
om.registerModule(new JavaTimeModule());
om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
j2jrs.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(j2jrs);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(j2jrs);
template.afterPropertiesSet();
}
}
package com.liquidnet.common.cache.redis.config;//package com.liquidnet.common.cache.redis.config; package com.liquidnet.common.cache.redis.config;//package com.liquidnet.common.cache.redis.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Value; import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import javax.annotation.PostConstruct;
import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map;
/** /**
...@@ -36,137 +18,49 @@ import java.util.Map; ...@@ -36,137 +18,49 @@ import java.util.Map;
*/ */
@Slf4j @Slf4j
@Configuration @Configuration
public class RedisConfig { public class RedisConfig extends AbstractRedisConfig{
@Value("${spring.redis.host}") @Value("${spring.redis.host:null}")
private String host; private String host;
@Value("${spring.redis.port}") @Value("${spring.redis.port:-1}")
private int port; private int port;
@Value("${spring.redis.password}") @Value("${spring.redis.password:null}")
private String password; private String password;
@Value("${spring.redis.lettuce.pool.max-active}") @Value("${spring.redis.lettuce.pool.max-active:-1}")
private int maxActive; private int maxActive;
@Value("${spring.redis.lettuce.pool.max-idle}") @Value("${spring.redis.lettuce.pool.max-idle:-1}")
private int maxIdle; private int maxIdle;
@Value("${spring.redis.lettuce.pool.min-idle}") @Value("${spring.redis.lettuce.pool.min-idle:-1}")
private int minIdle; private int minIdle;
@Value("${spring.redis.lettuce.pool.max-wait}") @Value("${spring.redis.lettuce.pool.max-wait:-1}")
private int maxWait; private int maxWait;
public static int defaultDb = 0; @Value("${spring.redis.dbs:${spring.redis.database:-1}}")
public static int totalDbs = 1;
@Value("${spring.redis.dbs:${spring.redis.database}}")
private List<Integer> dbs; private List<Integer> dbs;
String getHost(){
public static Map<Integer, RedisTemplate<String, Object>> redisTemplateMap = new HashMap<>(); return this.host;
@PostConstruct
public void initRedisTemp() throws Exception {
log.info("###### START 初始化 Redis 连接池 START ######");
defaultDb = dbs.get(0);
if(dbs.size()==2&&dbs.get(1)!=null){
totalDbs = dbs.get(1);
log.info("init totalDbs : {}",totalDbs);
for (int i = 0;i < totalDbs; i++) {
log.info("###### 正在加载Redis-db-" + i+ " ######");
redisTemplateMap.put(i, getRedisTemplate(i));
}
}else{
log.info("init defaultDb : {}",defaultDb);
redisTemplateMap.put(defaultDb, getRedisTemplate(defaultDb));
}
log.info("###### END 初始化 Redis 连接池 END ######");
} }
private RedisTemplate<String, Object> getRedisTemplate(int dbNo) { int getPort(){
return getRedisTemplate(getDbFactory(dbNo)); return this.port;
} }
String getPassword(){
private LettuceConnectionFactory getDbFactory(int dbNo){ return this.password;
LettuceConnectionFactory factory = new LettuceConnectionFactory(getRedisConfig(dbNo), getClientConfig());
factory.afterPropertiesSet();//必须初始化实例
return factory;
} }
int getMaxActive(){
private RedisStandaloneConfiguration getRedisConfig(int dbNo) { return this.maxActive;
RedisStandaloneConfiguration config = new RedisStandaloneConfiguration();
config.setHostName(host);
config.setPort(port);
config.setPassword(password);
config.setDatabase(dbNo);
return config;
} }
int getMaxIdle(){
private LettuceClientConfiguration getClientConfig() { return this.maxIdle;
GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
poolConfig.setMaxTotal(maxActive);
poolConfig.setMaxIdle(maxIdle);
poolConfig.setMinIdle(minIdle);
poolConfig.setMaxWaitMillis(maxWait);
return LettucePoolingClientConfiguration.builder().poolConfig(poolConfig).build();
} }
int getMinIdle(){
private RedisTemplate<String, Object> getRedisTemplate(LettuceConnectionFactory factory) { return this.minIdle;
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
redisTemplate.setConnectionFactory(factory);
setSerializer(redisTemplate);
redisTemplate.afterPropertiesSet();
return redisTemplate;
} }
int getMaxWait(){
public RedisTemplate<String, Object> getRedisTemplateByDb(int db){ return this.maxWait;
return redisTemplateMap.get(db);
}
@Bean
public RedisTemplate redisTemplate() {
LettuceConnectionFactory factory = null;
if(totalDbs==1){
factory = getDbFactory(defaultDb);
}else{
factory = getDbFactory(totalDbs-1);
} }
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); List<Integer> getDbs(){
redisTemplate.setConnectionFactory(factory); return this.dbs;
setSerializer(redisTemplate);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
@Bean
public StringRedisTemplate stringRedisTemplate() {
LettuceConnectionFactory factory = null;
if(totalDbs==1){
factory = getDbFactory(defaultDb);
}else{
factory = getDbFactory(totalDbs-1);
}
StringRedisTemplate redisTemplate = new StringRedisTemplate();
redisTemplate.setConnectionFactory(factory);
return redisTemplate;
}
private void setSerializer(RedisTemplate<String, Object> template) {
Jackson2JsonRedisSerializer j2jrs = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
om.registerModule(new JavaTimeModule());
om.activateDefaultTyping(om.getPolymorphicTypeValidator(), ObjectMapper.DefaultTyping.NON_FINAL);
j2jrs.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(j2jrs);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(j2jrs);
template.afterPropertiesSet();
} }
} }
\ No newline at end of file
package com.liquidnet.common.cache.redis.config;//package com.liquidnet.common.cache.redis.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: RedisConfig
* @Package com.liquidnet.common.cache.redis.config
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/8/10 16:28
*/
@Slf4j
@Configuration
public class RedisDb2Config extends AbstractRedisConfig{
@Value("${spring.redis.db2.host:null}")
private String host;
@Value("${spring.redis.db2.port:-1}")
private int port;
@Value("${spring.redis.db2.password:null}")
private String password;
@Value("${spring.redis.db2.lettuce.pool.max-active:-1}")
private int maxActive;
@Value("${spring.redis.db2.lettuce.pool.max-idle:-1}")
private int maxIdle;
@Value("${spring.redis.db2.lettuce.pool.min-idle:-1}")
private int minIdle;
@Value("${spring.redis.db2.lettuce.pool.max-wait:-1}")
private int maxWait;
@Value("${spring.redis.db2.dbs:${spring.redis.db2.database:-1}}")
private List<Integer> dbs;
public RedisDb2Config(){
}
String getHost(){
return this.host;
}
int getPort(){
return this.port;
}
String getPassword(){
return this.password;
}
int getMaxActive(){
return this.maxActive;
}
int getMaxIdle(){
return this.maxIdle;
}
int getMinIdle(){
return this.minIdle;
}
int getMaxWait(){
return this.maxWait;
}
List<Integer> getDbs(){
return this.dbs;
}
}
\ No newline at end of file
package com.liquidnet.common.cache.redis.config;//package com.liquidnet.common.cache.redis.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: RedisConfig
* @Package com.liquidnet.common.cache.redis.config
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/8/10 16:28
*/
@Slf4j
@Configuration
public class RedisDb3Config extends AbstractRedisConfig{
@Value("${spring.redis.db3.host:null}")
private String host;
@Value("${spring.redis.db3.port:-1}")
private int port;
@Value("${spring.redis.db3.password:null}")
private String password;
@Value("${spring.redis.db3.lettuce.pool.max-active:-1}")
private int maxActive;
@Value("${spring.redis.db3.lettuce.pool.max-idle:-1}")
private int maxIdle;
@Value("${spring.redis.db3.lettuce.pool.min-idle:-1}")
private int minIdle;
@Value("${spring.redis.db3.lettuce.pool.max-wait:-1}")
private int maxWait;
@Value("${spring.redis.db3.dbs:${spring.redis.db3.database:-1}}")
private List<Integer> dbs;
String getHost(){
return this.host;
}
int getPort(){
return this.port;
}
String getPassword(){
return this.password;
}
int getMaxActive(){
return this.maxActive;
}
int getMaxIdle(){
return this.maxIdle;
}
int getMinIdle(){
return this.minIdle;
}
int getMaxWait(){
return this.maxWait;
}
List<Integer> getDbs(){
return this.dbs;
}
}
\ No newline at end of file
package com.liquidnet.common.cache.redis.config;//package com.liquidnet.common.cache.redis.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: RedisConfig
* @Package com.liquidnet.common.cache.redis.config
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/8/10 16:28
*/
@Slf4j
@Configuration
public class RedisDb4Config extends AbstractRedisConfig {
@Value("${spring.redis.db4.host:null}")
private String host;
@Value("${spring.redis.db4.port:-1}")
private int port;
@Value("${spring.redis.db4.password:null}")
private String password;
@Value("${spring.redis.db4.lettuce.pool.max-active:-1}")
private int maxActive;
@Value("${spring.redis.db4.lettuce.pool.max-idle:-1}")
private int maxIdle;
@Value("${spring.redis.db4.lettuce.pool.min-idle:-1}")
private int minIdle;
@Value("${spring.redis.db4.lettuce.pool.max-wait:-1}")
private int maxWait;
@Value("${spring.redis.db4.dbs:${spring.redis.db4.database:-1}}")
private List<Integer> dbs;
String getHost(){
return this.host;
}
int getPort(){
return this.port;
}
String getPassword(){
return this.password;
}
int getMaxActive(){
return this.maxActive;
}
int getMaxIdle(){
return this.maxIdle;
}
int getMinIdle(){
return this.minIdle;
}
int getMaxWait(){
return this.maxWait;
}
List<Integer> getDbs(){
return this.dbs;
}
}
\ No newline at end of file
package com.liquidnet.common.cache.redis.config;//package com.liquidnet.common.cache.redis.config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import java.util.List;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: RedisConfig
* @Package com.liquidnet.common.cache.redis.config
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/8/10 16:28
*/
@Slf4j
@Configuration
public class RedisDb5Config extends AbstractRedisConfig {
@Value("${spring.redis.db5.host:null}")
private String host;
@Value("${spring.redis.db5.port:-1}")
private int port;
@Value("${spring.redis.db5.password:null}")
private String password;
@Value("${spring.redis.db5.lettuce.pool.max-active:-1}")
private int maxActive;
@Value("${spring.redis.db5.lettuce.pool.max-idle:-1}")
private int maxIdle;
@Value("${spring.redis.db5.lettuce.pool.min-idle:-1}")
private int minIdle;
@Value("${spring.redis.db5.lettuce.pool.max-wait:-1}")
private int maxWait;
@Value("${spring.redis.db5.dbs:${spring.redis.db5.database:-1}}")
private List<Integer> dbs;
String getHost(){
return this.host;
}
int getPort(){
return this.port;
}
String getPassword(){
return this.password;
}
int getMaxActive(){
return this.maxActive;
}
int getMaxIdle(){
return this.maxIdle;
}
int getMinIdle(){
return this.minIdle;
}
int getMaxWait(){
return this.maxWait;
}
List<Integer> getDbs(){
return this.dbs;
}
}
\ No newline at end of file
package com.liquidnet.common.cache.redis.util;
import com.liquidnet.common.cache.redis.config.AbstractRedisConfig;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.concurrent.TimeUnit;
/**
* @author AnJiabin <jiabin.an@lightnet.io>
* @version V1.0
* @Description: Redis工具类
* @class: RedisUtil
* @Package com.liquidnet.stellar.utils
* @Copyright: LightNet @ Copyright (c) 2020
* @date 2020/8/26 13:11
*/
public abstract class AbstractRedisUtil {
/**
* 获取redis初始化信息
*/
public abstract int getDbs();
/**
* 设置redis数据源
* @return
*/
abstract AbstractRedisConfig getRedisConfig();
// =============================common============================
/**
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
if (time > 0) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).expire(key, time, TimeUnit.SECONDS);
}
return true;
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).hasKey(key);
}
/**
* 根据前缀模糊删除
*
* @param prefix Key前缀
*/
public void delKeysByPrefix(String prefix) {
if (null != prefix && prefix.trim().length() > 0) {
for (Integer key : this.getRedisConfig().redisTemplateMap.keySet()) {
Set<String> keys = this.getRedisConfig().getRedisTemplateByDb(key).keys(prefix.concat("*"));
if (!CollectionUtils.isEmpty(keys)) {
this.getRedisConfig().getRedisTemplateByDb(key).delete(keys);
}
}
}
}
/**
* 删除缓存(多db情况需要单独实现批量删除-该方法慎重使用)
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key[0])).delete(key[0]);
} else {
// redisTemplate.delete(CollectionUtils.arrayToList(key));
for (String keyStr : key) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(keyStr)).delete(keyStr);
}
}
}
}
private static final ArrayList<String> STRING_ARRAY_LIST = new ArrayList<>();
private static final HashMap<Integer, ArrayList<String>> INTEGER_ARRAY_LIST_HASH_MAP = new HashMap();
public static ArrayList<String> arrayListString() {
return (ArrayList<String>) STRING_ARRAY_LIST.clone();
}
public static HashMap<Integer, ArrayList<String>> hashMapIntegerArrayList() {
return (HashMap<Integer, ArrayList<String>>) INTEGER_ARRAY_LIST_HASH_MAP.clone();
}
public void delList(List<String> key) {
HashMap<Integer, ArrayList<String>> hashMap;
if (key != null && key.size() > 0) {
hashMap = hashMapIntegerArrayList();
//构建 需要删除的Redis HashMapDBKey
for (String keyStr : key) {
Integer dbPosition = this.getIndex(keyStr);
ArrayList<String> dbArray;
if (hashMap.containsKey(dbPosition)) {
dbArray = hashMap.get(dbPosition);
} else {
dbArray = arrayListString();
}
dbArray.add(keyStr);
hashMap.put(dbPosition, dbArray);
}
//删除Redis
for (Integer redisDb : hashMap.keySet()) {
ArrayList<String> delRedisKeyList = hashMap.get(redisDb);
this.getRedisConfig().getRedisTemplateByDb(redisDb).delete(delRedisKeyList);
}
}
}
// ============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForValue().set(key, value);
return true;
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
if (time > 0) {
RedisTemplate<String, Object> redisTemplate = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key));
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
}
/**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForValue().increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().get(key, item);
}
public Object hkeys(String key) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().keys(key);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().putAll(key, map);
return true;
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().put(key, item, value);
return true;
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().members(key);
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().isMember(key, value);
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().add(key, values);
}
/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
Long count = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public long sGetSetSize(String key) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().size(key);
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
Long count = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForSet().remove(key, values);
return count;
}
// ===============================list=================================
/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().range(key, start, end);
}
/**
* 获取list缓存的长度
*
* @param key 键
* @return
*/
public long lGetListSize(String key) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().size(key);
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key, long index) {
return this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().index(key, index);
}
/**
* 将list放入缓存
*
* @param key
* @param value
* @return
*/
public boolean lSet(String key, Object value) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().rightPush(key, value);
return true;
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
}
/**
* 将list放入缓存
*
* @param key
* @param value
* @return
*/
public boolean lSet(String key, List<Object> value) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().rightPushAll(key, value);
return true;
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().set(key, index, value);
return true;
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
Long remove = this.getRedisConfig().getRedisTemplateByDb(this.getIndex(key)).opsForList().remove(key, count, value);
return remove;
}
public RedisTemplate<String, Object> getRedisTemplateByDb(int db) {
return this.getRedisConfig().getRedisTemplateByDb(db);
}
public Object getDB15RedisHGet(String redisKey, String item) {
return this.getRedisConfig().getRedisTemplateByDb(15).opsForHash().get(redisKey, item);
}
public Object getDB15RedisGet(String redisKey) {
return this.getRedisConfig().getRedisTemplateByDb(15).opsForValue().get(redisKey);
}
public boolean getDB15RedisHasKey(String redisKey, String item) {
return this.getRedisConfig().getRedisTemplateByDb(15).opsForSet().isMember(redisKey, item);
}
public static void main(String[] args) {
String[] keys = {
"kylin:order:id:302739831268147207565446"
};
for (String key : keys) {
long value = key.hashCode();
int idx = ((int) (value ^ (value >>> 32)) % 250);
System.out.printf("\n[%s] - idx:%s", key, idx);
}
}
private int getIndex(String key){
return MathUtil.getIndex(key,this.getRedisConfig().defaultDb,this.getRedisConfig().totalDbs);
}
}
...@@ -14,10 +14,10 @@ import lombok.extern.slf4j.Slf4j; ...@@ -14,10 +14,10 @@ import lombok.extern.slf4j.Slf4j;
*/ */
@Slf4j @Slf4j
public class MathUtil { public class MathUtil {
public static int getIndex(String key){ public static int getIndex(String key,int defaultDb,int totalDbs){
log.debug("MathUtil.getIndex key:{} hashcode:{}",key,key.hashCode()); log.debug("MathUtil.getIndex key:{} hashcode:{}",key,key.hashCode());
int defaultDb = RedisConfig.defaultDb; // int defaultDb = RedisConfig.defaultDb;
int totalDbs = RedisConfig.totalDbs; // int totalDbs = RedisConfig.totalDbs;
if(totalDbs==1){ if(totalDbs==1){
log.info("only one db : {} ",defaultDb); log.info("only one db : {} ",defaultDb);
return defaultDb; return defaultDb;
...@@ -39,6 +39,8 @@ public class MathUtil { ...@@ -39,6 +39,8 @@ public class MathUtil {
public static void main(String[] args) { public static void main(String[] args) {
RedisConfig redisConfig = new RedisConfig(); RedisConfig redisConfig = new RedisConfig();
redisConfig.getRedisTemplateByDb(MathUtil.getIndex("1")); log.info("redisConfig.defaultDb===",redisConfig.defaultDb);
log.info("redisConfig.totalDbs===",redisConfig.totalDbs);
redisConfig.getRedisTemplateByDb(MathUtil.getIndex("1",redisConfig.defaultDb,redisConfig.totalDbs));
} }
} }
package com.liquidnet.common.cache.redis.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author AnJiabin <anjiabin@zhengzai.tv>
* @version V1.0
* @Description: TODO
* @class: PlatformRedisUtil
* @Package com.liquidnet.common.cache.redis.util
* @Copyright: LightNet @ Copyright (c) 2021
* @date 2021/10/20 18:13
*/
@Component
public class RedisDataSourceUtil {
@Autowired
private RedisUtil redisUtil;
@Autowired
private RedisDb2Util redisDb2Util;
@Autowired
private RedisDb3Util redisDb3Util;
@Autowired
private RedisDb4Util redisDb4Util;
@Autowired
private RedisDb5Util redisDb5Util;
public AbstractRedisUtil getRedisDb1Util(){
return this.redisUtil;
}
public AbstractRedisUtil getRedisDb2Util(){
return this.redisDb2Util;
}
public AbstractRedisUtil getRedisDb3Util(){
return this.redisDb3Util;
}
public AbstractRedisUtil getRedisDb4Util(){
return this.redisDb4Util;
}
public AbstractRedisUtil getRedisDb5Util(){
return this.redisDb5Util;
}
}
package com.liquidnet.common.cache.redis.util;
import com.liquidnet.common.cache.redis.config.AbstractRedisConfig;
import com.liquidnet.common.cache.redis.config.RedisDb2Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author AnJiabin <jiabin.an@lightnet.io>
* @version V1.0
* @Description: Redis工具类
* @class: RedisUtil
* @Package com.liquidnet.stellar.utils
* @Copyright: LightNet @ Copyright (c) 2020
* @date 2020/8/26 13:11
*/
@Slf4j
@Component("redisDb2Util")
public final class RedisDb2Util extends AbstractRedisUtil{
@Autowired
private RedisDb2Config redisConfig;
@Override
public int getDbs() {
log.info("redisDb2Config.totalDbs===",redisConfig.totalDbs);
return redisConfig.totalDbs;
}
@Override
AbstractRedisConfig getRedisConfig() {
return this.redisConfig;
}
}
package com.liquidnet.common.cache.redis.util;
import com.liquidnet.common.cache.redis.config.AbstractRedisConfig;
import com.liquidnet.common.cache.redis.config.RedisDb3Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author AnJiabin <jiabin.an@lightnet.io>
* @version V1.0
* @Description: Redis工具类
* @class: RedisUtil
* @Package com.liquidnet.stellar.utils
* @Copyright: LightNet @ Copyright (c) 2020
* @date 2020/8/26 13:11
*/
@Slf4j
@Component("redisDb3Util")
public final class RedisDb3Util extends AbstractRedisUtil{
@Autowired
private RedisDb3Config redisConfig;
@Override
public int getDbs() {
log.info("redisDb3Config.totalDbs===",redisConfig.totalDbs);
return redisConfig.totalDbs;
}
@Override
AbstractRedisConfig getRedisConfig() {
return this.redisConfig;
}
}
package com.liquidnet.common.cache.redis.util;
import com.liquidnet.common.cache.redis.config.AbstractRedisConfig;
import com.liquidnet.common.cache.redis.config.RedisDb4Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author AnJiabin <jiabin.an@lightnet.io>
* @version V1.0
* @Description: Redis工具类
* @class: RedisUtil
* @Package com.liquidnet.stellar.utils
* @Copyright: LightNet @ Copyright (c) 2020
* @date 2020/8/26 13:11
*/
@Slf4j
@Component("redisDb4Util")
public final class RedisDb4Util extends AbstractRedisUtil{
@Autowired
private RedisDb4Config redisConfig;
@Override
public int getDbs() {
log.info("redisDb4Config.totalDbs===",redisConfig.totalDbs);
return redisConfig.totalDbs;
}
@Override
AbstractRedisConfig getRedisConfig() {
return this.redisConfig;
}
}
package com.liquidnet.common.cache.redis.util;
import com.liquidnet.common.cache.redis.config.AbstractRedisConfig;
import com.liquidnet.common.cache.redis.config.RedisDb5Config;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
/**
* @author AnJiabin <jiabin.an@lightnet.io>
* @version V1.0
* @Description: Redis工具类
* @class: RedisUtil
* @Package com.liquidnet.stellar.utils
* @Copyright: LightNet @ Copyright (c) 2020
* @date 2020/8/26 13:11
*/
@Slf4j
@Component("redisDb5Util")
public final class RedisDb5Util extends AbstractRedisUtil{
@Autowired
private RedisDb5Config redisConfig;
@Override
public int getDbs() {
log.info("redisDb5Config.totalDbs===",redisConfig.totalDbs);
return redisConfig.totalDbs;
}
@Override
AbstractRedisConfig getRedisConfig() {
return this.redisConfig;
}
}
package com.liquidnet.common.cache.redis.util; package com.liquidnet.common.cache.redis.util;
import com.liquidnet.common.cache.redis.config.AbstractRedisConfig;
import com.liquidnet.common.cache.redis.config.RedisConfig; import com.liquidnet.common.cache.redis.config.RedisConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import java.util.*;
import java.util.concurrent.TimeUnit;
/** /**
* @author AnJiabin <jiabin.an@lightnet.io> * @author AnJiabin <jiabin.an@lightnet.io>
...@@ -18,750 +15,22 @@ import java.util.concurrent.TimeUnit; ...@@ -18,750 +15,22 @@ import java.util.concurrent.TimeUnit;
* @Copyright: LightNet @ Copyright (c) 2020 * @Copyright: LightNet @ Copyright (c) 2020
* @date 2020/8/26 13:11 * @date 2020/8/26 13:11
*/ */
@Slf4j
@Component("redisUtil") @Component("redisUtil")
public final class RedisUtil { public final class RedisUtil extends AbstractRedisUtil{
@Autowired @Autowired
private RedisConfig redisConfig; private RedisConfig redisConfig;
@Override
// =============================common============================ public int getDbs() {
// log.info("redisConfig.totalDbs===",redisConfig.totalDbs);
/** return redisConfig.totalDbs;
* 指定缓存失效时间
*
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key, long time) {
if (time > 0) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).expire(key, time, TimeUnit.SECONDS);
}
return true;
}
/**
* 根据key 获取过期时间
*
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
*
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).hasKey(key);
}
/**
* 根据前缀模糊删除
*
* @param prefix Key前缀
*/
public void delKeysByPrefix(String prefix) {
if (null != prefix && prefix.trim().length() > 0) {
for (Integer key : RedisConfig.redisTemplateMap.keySet()) {
Set<String> keys = redisConfig.getRedisTemplateByDb(key).keys(prefix.concat("*"));
if (!CollectionUtils.isEmpty(keys)) {
redisConfig.getRedisTemplateByDb(key).delete(keys);
}
}
}
}
/**
* 删除缓存(多db情况需要单独实现批量删除-该方法慎重使用)
*
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key[0])).delete(key[0]);
} else {
// redisTemplate.delete(CollectionUtils.arrayToList(key));
for (String keyStr : key) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(keyStr)).delete(keyStr);
}
}
}
}
private static final ArrayList<String> STRING_ARRAY_LIST = new ArrayList<>();
private static final HashMap<Integer, ArrayList<String>> INTEGER_ARRAY_LIST_HASH_MAP = new HashMap();
public static ArrayList<String> arrayListString() {
return (ArrayList<String>) STRING_ARRAY_LIST.clone();
}
public static HashMap<Integer, ArrayList<String>> hashMapIntegerArrayList() {
return (HashMap<Integer, ArrayList<String>>) INTEGER_ARRAY_LIST_HASH_MAP.clone();
}
public void delList(List<String> key) {
HashMap<Integer, ArrayList<String>> hashMap;
if (key != null && key.size() > 0) {
hashMap = hashMapIntegerArrayList();
//构建 需要删除的Redis HashMapDBKey
for (String keyStr : key) {
Integer dbPosition = MathUtil.getIndex(keyStr);
ArrayList<String> dbArray;
if (hashMap.containsKey(dbPosition)) {
dbArray = hashMap.get(dbPosition);
} else {
dbArray = arrayListString();
}
dbArray.add(keyStr);
hashMap.put(dbPosition, dbArray);
}
//删除Redis
for (Integer redisDb : hashMap.keySet()) {
ArrayList<String> delRedisKeyList = hashMap.get(redisDb);
redisConfig.getRedisTemplateByDb(redisDb).delete(delRedisKeyList);
}
}
}
// ============================String=============================
/**
* 普通缓存获取
*
* @param key 键
* @return 值
*/
public Object get(String key) {
return key == null ? null : redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForValue().get(key);
}
/**
* 普通缓存放入
*
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key, Object value) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForValue().set(key, value);
return true;
}
/**
* 普通缓存放入并设置时间
*
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key, Object value, long time) {
if (time > 0) {
RedisTemplate<String, Object> redisTemplate = redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key));
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
}
/**
* 递增
*
* @param key 键
* @param delta 要增加几(大于0)
* @return
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForValue().increment(key, delta);
}
/**
* 递减
*
* @param key 键
* @param delta 要减少几(小于0)
* @return
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key, String item) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForHash().get(key, item);
}
public Object hkeys(String key) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForHash().keys(key);
}
/**
* 获取hashKey对应的所有键值
*
* @param key 键
* @return 对应的多个键值
*/
public Map<Object, Object> hmget(String key) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForHash().entries(key);
}
/**
* HashSet
*
* @param key 键
* @param map 对应多个键值
* @return true 成功 false 失败
*/
public boolean hmset(String key, Map<String, Object> map) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForHash().putAll(key, map);
return true;
}
/**
* HashSet 并设置时间
*
* @param key 键
* @param map 对应多个键值
* @param time 时间(秒)
* @return true成功 false失败
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForHash().putAll(key, map);
if (time > 0) {
expire(key, time);
}
return true;
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForHash().put(key, item, value);
return true;
}
/**
* 向一张hash表中放入数据,如果不存在将创建
*
* @param key 键
* @param item 项
* @param value 值
* @param time 时间(秒) 注意:如果已存在的hash表有时间,这里将会替换原有的时间
* @return true 成功 false失败
*/
public boolean hset(String key, String item, Object value, long time) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForHash().put(key, item, value);
if (time > 0) {
expire(key, time);
}
return true;
}
/**
* 删除hash表中的值
*
* @param key 键 不能为null
* @param item 项 可以使多个 不能为null
*/
public void hdel(String key, Object... item) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
*
* @param key 键 不能为null
* @param item 项 不能为null
* @return true 存在 false不存在
*/
public boolean hHasKey(String key, String item) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
*
* @param key 键
* @param item 项
* @param by 要增加几(大于0)
* @return
*/
public double hincr(String key, String item, double by) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForHash().increment(key, item, by);
}
/**
* hash递减
*
* @param key 键
* @param item 项
* @param by 要减少记(小于0)
* @return
*/
public double hdecr(String key, String item, double by) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForHash().increment(key, item, -by);
}
// ============================set=============================
/**
* 根据key获取Set中的所有值
*
* @param key 键
* @return
*/
public Set<Object> sGet(String key) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForSet().members(key);
}
/**
* 根据value从一个set中查询,是否存在
*
* @param key 键
* @param value 值
* @return true 存在 false不存在
*/
public boolean sHasKey(String key, Object value) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForSet().isMember(key, value);
}
/**
* 将数据放入set缓存
*
* @param key 键
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSet(String key, Object... values) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForSet().add(key, values);
}
/**
* 将set数据放入缓存
*
* @param key 键
* @param time 时间(秒)
* @param values 值 可以是多个
* @return 成功个数
*/
public long sSetAndTime(String key, long time, Object... values) {
Long count = redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForSet().add(key, values);
if (time > 0)
expire(key, time);
return count;
}
/**
* 获取set缓存的长度
*
* @param key 键
* @return
*/
public long sGetSetSize(String key) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForSet().size(key);
}
/**
* 移除值为value的
*
* @param key 键
* @param values 值 可以是多个
* @return 移除的个数
*/
public long setRemove(String key, Object... values) {
Long count = redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForSet().remove(key, values);
return count;
}
// ===============================list=================================
/**
* 获取list缓存的内容
*
* @param key 键
* @param start 开始
* @param end 结束 0 到 -1代表所有值
* @return
*/
public List<Object> lGet(String key, long start, long end) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForList().range(key, start, end);
} }
@Override
/** AbstractRedisConfig getRedisConfig() {
* 获取list缓存的长度 return this.redisConfig;
*
* @param key 键
* @return
*/
public long lGetListSize(String key) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForList().size(key);
}
/**
* 通过索引 获取list中的值
*
* @param key 键
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
* @return
*/
public Object lGetIndex(String key, long index) {
return redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForList().index(key, index);
}
/**
* 将list放入缓存
*
* @param key
* @param value
* @return
*/
public boolean lSet(String key, Object value) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForList().rightPush(key, value);
return true;
}
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, Object value, long time) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForList().rightPush(key, value);
if (time > 0)
expire(key, time);
return true;
}
/**
* 将list放入缓存
*
* @param key
* @param value
* @return
*/
public boolean lSet(String key, List<Object> value) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForList().rightPushAll(key, value);
return true;
} }
/**
* 将list放入缓存
*
* @param key 键
* @param value 值
* @param time 时间(秒)
* @return
*/
public boolean lSet(String key, List<Object> value, long time) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForList().rightPushAll(key, value);
if (time > 0)
expire(key, time);
return true;
}
/**
* 根据索引修改list中的某条数据
*
* @param key 键
* @param index 索引
* @param value 值
* @return
*/
public boolean lUpdateIndex(String key, long index, Object value) {
redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForList().set(key, index, value);
return true;
}
/**
* 移除N个值为value
*
* @param key 键
* @param count 移除多少个
* @param value 值
* @return 移除的个数
*/
public long lRemove(String key, long count, Object value) {
Long remove = redisConfig.getRedisTemplateByDb(MathUtil.getIndex(key)).opsForList().remove(key, count, value);
return remove;
}
public RedisTemplate<String, Object> getRedisTemplateByDb(int db) {
return redisConfig.getRedisTemplateByDb(db);
}
public Object getDB15RedisHGet(String redisKey, String item) {
return redisConfig.getRedisTemplateByDb(15).opsForHash().get(redisKey, item);
}
public Object getDB15RedisGet(String redisKey) {
return redisConfig.getRedisTemplateByDb(15).opsForValue().get(redisKey);
}
public boolean getDB15RedisHasKey(String redisKey, String item) {
return redisConfig.getRedisTemplateByDb(15).opsForSet().isMember(redisKey, item);
}
public static void main(String[] args) {
String[] keys = {
"kylin:order:id:302739831268147207565446"
};
for (String key : keys) {
long value = key.hashCode();
int idx = ((int) (value ^ (value >>> 32)) % 250);
System.out.printf("\n[%s] - idx:%s", key, idx);
}
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment