Redis配置
#Redis
spring.redis.host=
spring.redis.port=6379
spring.redis.database=0
# Redis服务器连接密码(默认为空)
spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
spring.redis.pool.max-active=1500
# 连接池最大阻塞等待时间(使用负值表示没有限制)
spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
spring.redis.timeout=30000
RedisConfig.java Redis配置文件
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
@Configuration
@Component
public class RedisConfig extends CachingConfigurerSupport {
private static final Logger logger = LoggerFactory.getLogger(RedisConfig.class);
public RedisConfig(){
logger.info("init RedisConfig...");
}
/**
* 生成key的策略
*
* @return
*/
@Bean
public KeyGenerator keyGenerator() {
return new KeyGenerator() {
@Override
public Object generate(Object target, Method method, Object... params) {
StringBuilder sb = new StringBuilder();
sb.append(target.getClass().getName());
sb.append(method.getName());
for (Object obj : params) {
sb.append(obj.toString());
}
return sb.toString();
}
};
}
/**
* 管理缓存
*
* @param redisTemplate
* @return
*/
@SuppressWarnings("rawtypes")
@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
// rcm.setDefaultExpiration(60);//秒
return rcm;
}
/**
* RedisTemplate配置
* @param factory
* @return
*/
@Bean
public RedisTemplate<String, String> redisTemplate(RedisConnectionFactory factory) {
StringRedisTemplate template = new StringRedisTemplate(factory);
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
template.setValueSerializer(jackson2JsonRedisSerializer);//如果key是String 需要配置一下StringSerializer,不然key会乱码 /XX/XX
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
RedisUtils.java Redis工具类
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.connection.DataType;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;
import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* redicache 工具类
*
*/
@SuppressWarnings("unchecked")
@Component
public class RedisUtils {
private static final Logger log = LoggerFactory.getLogger(RedisUtils.class);
private static final PropertiesUtils redisProper = new PropertiesUtils("spring/redis-time-config.properties");
@SuppressWarnings("rawtypes")
@Autowired
private RedisTemplate redisTemplate;
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
public int getCountPattern(String pattern){
Set<Serializable> keys = redisTemplate.keys(pattern);
return keys==null?0:keys.size();
}
/**
* 批量删除key
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 批量删除key
*
* @param keys
*/
public void removeKeys(final Set<String> keys) {
if (keys.size() > 0)
redisTemplate.delete(keys);
}
public Long ttl(String key) {
return StringUtils.isNoneEmpty(key) ? Long.valueOf(-1L) : redisTemplate.getExpire(key);
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Long size(final String key) {
Long result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.size(key);
return result;
}
public <K> Set<K> keys(K pattern){
return redisTemplate.keys(pattern);
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
return set(key, value, expireTime, TimeUnit.SECONDS);
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime, TimeUnit timeUnit) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean setInt(final String key, int value, Long expireTime, TimeUnit timeUnit) {
boolean result = false;
try {
ValueOperations<String, Integer> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, timeUnit);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean setInt(final String key, int value) {
boolean result = false;
try {
ValueOperations<String, Integer> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存
*
* @param key
* @param key
* @return
*/
public int getInt(final String key) {
int result = -1;
if (exists(key)) {
ValueOperations<String, Integer> operations = redisTemplate.opsForValue();
result = operations.get(key);
}
return result;
}
public Long increment(String key, long val){
if( exists(key) ){
return redisTemplate.opsForValue().increment(key, val);
}
return null;
}
public Long addHyperLogLog(Object val1, Object ...val2){
return redisTemplate.opsForHyperLogLog().add(val1, val2);
}
public Long sAdd(Object key, Object... values) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForSet().add(key, values);
}
public Set<String> sMembers(String key) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForSet().members(key);
}
public Long sRem(Object key, Object... values) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForSet().remove(key, values);
}
public Object sPop(Object key) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForSet().pop(key);
}
public boolean sMove(Object srcKey, Object destKey, Object member) {
return (!isNullOrEmpty(srcKey) && !isNullOrEmpty(destKey)) && ((member != null) && redisTemplate.opsForSet().move(srcKey, member, destKey));
}
public Long sLen(Object key) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForSet().size(key);
}
public boolean sIsMember(Object key, Object member) {
return !isNullOrEmpty(key) && redisTemplate.opsForSet().isMember(key, member);
}
public Set<Object> sInter(Object key, Object... keys) {
return key == null ? null : redisTemplate.opsForSet().intersect(key, keys);
}
public Long sInterStore(Object destKey, Object srckey, Object... srcKeys) {
return !isNullOrEmpty(destKey) && srckey != null ? redisTemplate.opsForSet().intersectAndStore(srckey, srcKeys, destKey) : null;
}
public Set<Object> sUnion(Object... keys) {
if (keys != null && keys.length != 0) {
List keyList = Arrays.asList(keys);
return redisTemplate.opsForSet().union(keyList.remove(0), keyList);
} else {
return null;
}
}
public Long sUnionStore(Object dstKey, Object... keys) {
if (keys != null && keys.length != 0 && dstKey != null) {
List keyList = Arrays.asList(keys);
return redisTemplate.opsForSet().unionAndStore(keyList.remove(0), keyList, dstKey);
} else {
return null;
}
}
public Set<Object> sDiff(Object... keys) {
if (keys != null && keys.length != 0) {
List keyList = Arrays.asList(keys);
return redisTemplate.opsForSet().difference(keyList.remove(0), keyList);
} else {
return null;
}
}
public Long sDiffStore(Object dstKey, Object... keys) {
if (!isNullOrEmpty(dstKey) && keys != null && keys.length != 0) {
List keyList = Arrays.asList(keys);
return redisTemplate.opsForSet().differenceAndStore(keyList.remove(0), keyList, dstKey);
} else {
return null;
}
}
public boolean hSet(String key, Map<String, Object> param, Long expireTime, TimeUnit timeUnit) {
try {
hSet(key, param);
redisTemplate.expire(key, expireTime, timeUnit);
return true;
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public void hSet(String key, Map<String, Object> param) {
HashOperations<String, String, Object> hashOperations = redisTemplate.opsForHash();
Set<Map.Entry<String, Object>> entrySet = param.entrySet();
for (Map.Entry<String, Object> entry : entrySet) {
hashOperations.put(key, entry.getKey(), entry.getValue());
}
}
public void hSet(String key, Object field, Object value) {
redisTemplate.opsForHash().put(key, field, value);
}
public Object hGet(String key, Object field) {
if (StringUtils.isEmpty(key)) {
return null;
}
return redisTemplate.opsForHash().get(key, field);
}
public String hGet(String key, String field) {
if (StringUtils.isEmpty(key)) {
return null;
}
HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
return hashOperations.get(key, field);
}
public boolean hExists(String key, Object hashKey) {
return !isNullOrEmpty(key) && redisTemplate.opsForHash().hasKey(key, hashKey);
}
public Long hDel(Object key, Object... hashKeys) {
return isNullOrEmpty(key) ? Long.valueOf(0L) : redisTemplate.opsForHash().delete(key, hashKeys);
}
public Long hLen(String key) {
return StringUtils.isNoneEmpty(key) ? Long.valueOf(0L) : redisTemplate.opsForHash().size(key);
}
public Set<Object> hKeys(Object key) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForHash().keys(key);
}
public List<Object> hValues(Object key) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForHash().values(key);
}
public Map<Object, Object> hGetAll(Object key) {
return isNullOrEmpty(key) ? null : redisTemplate.opsForHash().entries(key);
}
public Object getUnknownType(Object key){
try {
DataType dataType = redisTemplate.type(key);
switch (dataType){
case NONE:
log.info("key:[{}]不存在", key);
return null;
case STRING:
return redisTemplate.opsForValue().get(key);
case LIST:
return redisTemplate.opsForList().range(key, 0, -1);
case SET:
return redisTemplate.opsForSet().members(key);
case ZSET:
return redisTemplate.opsForZSet().range(key, 0, -1);
case HASH:
return redisTemplate.opsForHash().entries(key);
default:
return null;
}
}catch (Exception e){
log.error("查询出现异常:{}", e);
return null;
}
}
private static boolean isNullOrEmpty(Object obj) {
boolean result = false;
if (obj == null || "null".equals(obj) || "".equals(obj.toString().trim())) {
result = true;
}
return result;
}
public void setRedisValue(String key, Object value,String redisKey){
//添加缓存
String[] redispropers=redisProper.getPropertiesValues(redisKey);
Long redisExp=Long.valueOf(redispropers[0]);
TimeUnit redisTimeType= UtilHelper.getTimeUtil(redispropers[1]);
redisTemplate.opsForValue().set(key,value,redisExp, redisTimeType);
}
}