Skip to content

Commit

Permalink
更新 Redis 配置及工具类
Browse files Browse the repository at this point in the history
  • Loading branch information
micyo202 committed May 6, 2021
1 parent 6b3ab2c commit f2c61a4
Show file tree
Hide file tree
Showing 3 changed files with 103 additions and 8 deletions.
31 changes: 31 additions & 0 deletions lion-common/src/main/java/com/lion/common/config/RedisConfig.java
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,14 @@
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.cache.interceptor.CacheErrorHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
Expand All @@ -46,6 +49,7 @@
*/
@Configuration
@EnableCaching
@Slf4j
public class RedisConfig extends CachingConfigurerSupport {

/**
Expand All @@ -54,6 +58,32 @@ public class RedisConfig extends CachingConfigurerSupport {
@Value("${spring.cache.redis.time-to-live:300000}")
private Duration timeToLive;

/**
* 自定义缓存异常处理
* 当缓存读写异常时,忽略异常
*/
@Override
public CacheErrorHandler errorHandler() {
return new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object o) {
log.error(e.getMessage(), e);
}
@Override
public void handleCachePutError(RuntimeException e, Cache cache, Object o, Object o1) {
log.error(e.getMessage(), e);
}
@Override
public void handleCacheEvictError(RuntimeException e, Cache cache, Object o) {
log.error(e.getMessage(), e);
}
@Override
public void handleCacheClearError(RuntimeException e, Cache cache) {
log.error(e.getMessage(), e);
}
};
}

/**
* 配置 Redis 缓存
*/
Expand Down Expand Up @@ -81,6 +111,7 @@ public CacheManager cacheManager(@Autowired RedisConnectionFactory redisConnecti
*/
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
log.info("初始化 Redis");
RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
// 配置连接工厂
redisTemplate.setConnectionFactory(redisConnectionFactory);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,10 @@
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.lion.common.lock.config;
package com.lion.common.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;
Expand All @@ -30,6 +32,7 @@
* @date 2020/3/24
*/
@Configuration
@Slf4j
public class RedissonConfig {

@Value("${spring.redis.host:localhost}")
Expand All @@ -49,12 +52,15 @@ public class RedissonConfig {

@Bean
public RedissonClient redissonClient() {
log.info("初始化 Redisson");
Config config = new Config();
config.useSingleServer()
.setAddress("redis://" + host + ":" + port)
.setPassword(password)
.setTimeout(timeout)
.setDatabase(database);
if (StringUtils.isNotBlank(password)) {
config.useSingleServer().setPassword(password);
}
//.setConnectionPoolSize(10)
//.setConnectionMinimumIdleSize(8)
return Redisson.create(config);
Expand Down
70 changes: 64 additions & 6 deletions lion-common/src/main/java/com/lion/common/util/RedisUtil.java
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,12 @@
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;

import java.io.BufferedOutputStream;
import java.io.File;
Expand All @@ -37,14 +40,28 @@
* @author Yanzheng (https://github.com/micyo202)
* @date 2020/11/25
*/
@Component
public class RedisUtil {

private RedisUtil() {}

//private static RedisTemplate<String, Object> redisTemplate = SpringUtil.getBean("redisTemplate", RedisTemplate.class);
private static RedisTemplate<String, Object> redisTemplate;

/**
* 获取 redisTemplate 模板
*/
private static RedisTemplate<String, Object> redisTemplate = SpringUtil.getBean("redisTemplate", RedisTemplate.class);
@Autowired
public void setRedisTemplate(RedisTemplate<String, Object> redisTemplate) {
RedisUtil.redisTemplate = redisTemplate;
}

/**
* 暴露 RedisTemplate 模板
*/
public static RedisTemplate<String, Object> getRedisTemplate() {
return redisTemplate;
}

/**
* 设置值
Expand Down Expand Up @@ -213,6 +230,48 @@ public static long zsetAdd(final String key, final Set<ZSetOperations.TypedTuple
return count == null ? 0 : count;
}

/**
* 往ZSet中存入数据
*
* @param key Redis键
* @param value 值
* @param score 分数
*/
public static Boolean zsetAdd(final String key, final Object value, final double score) {
return redisTemplate.opsForZSet().add(key, value, score);
}

/**
* 从ZSet中获取range在start到end之间的元素
*
* @param key Redis键
* @param start 开始位置
* @param end 结束位置(start=0,end=-1表示获取全部元素)
*/
public static Set<Object> zsetGet(final String key, final long start, final long end) {
return redisTemplate.opsForZSet().range(key, start, end);
}

/**
* 从ZSet中获取score在min到max之间的元素
*
* @param key Redis键
* @param min 最小分数
* @param max 最大分数
*/
public static Set<Object> zsetGet(final String key, final double min, final double max) {
return redisTemplate.opsForZSet().rangeByScore(key, min, max);
}

/**
* 从ZSet中获取所有元素
*
* @param key Redis键
*/
public static Set<Object> zsetGetAll(final String key) {
return redisTemplate.opsForZSet().range(key, 0, -1);
}

/**
* 删除ZSet中的数据
*
Expand Down Expand Up @@ -259,13 +318,13 @@ public static long listPushAll(final String key, final Object... values) {
}

/**
* 从List中获取begin到end之间的元素
* 从List中获取start到end之间的元素
*
* @param key Redis键
* @param start 开始位置
* @param end 结束位置(start=0,end=-1表示获取全部元素)
*/
public static List<Object> listGet(final String key, final int start, final int end) {
public static List<Object> listGet(final String key, final long start, final long end) {
return redisTemplate.opsForList().range(key, start, end);
}

Expand Down Expand Up @@ -316,7 +375,7 @@ public static File fileGet(String fileName) {
final HashOperations<String, Object, Object> ops = redisTemplate.opsForHash();
// 缓存 Key
final Map<Object, Object> entries = ops.entries(CACHE_KEY_PREFIX + Objects.requireNonNull(fileName, "文件名不能为空"));
if (MapUtils.isEmpty(entries)) {
if (ObjectUtils.isEmpty(entries)) {
return null;
}
final String cachedFileName = MapUtils.getString(entries, FIELD_FILE_NAME);
Expand Down Expand Up @@ -388,5 +447,4 @@ public static long deleteKeys(final Collection<String> keys) {
public static boolean expire(String key, long seconds) {
return Optional.ofNullable(redisTemplate.expire(key, seconds, TimeUnit.SECONDS)).orElse(false);
}

}
}

0 comments on commit f2c61a4

Please sign in to comment.