说明:本文旨在整理SpringBoot 2.X整合Redis基础功能,如有问题请指出
org.springframework.boot
spring-boot-starter-data-redis
redis.clients
jedis
2.4.2
spring:
redis:
database: 0 # Redis数据库索引(默认为0)
host: 10.0.9.6 # Redis服务器地址
port: 6379 # Redis服务器连接端口
timeout: 10000ms # Redis连接超时时间
jedis:
pool:
max-active: 5000 # 连接池最大连接数(使用负值表示没有限制)
max-wait: 1000ms # 连接池最大阻塞等待时间(使用负值表示没有限制)
max-idle: 5000 # 连接池中的最大空闲连接
min-idle: 0 # 连接池中的最小空闲连接
这里的cacheManager是基于SpringBoot 2.X的配置
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
private Logger logger = LoggerFactory.getLogger(this.getClass());
@Bean
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig().entryTtl(Duration.ofHours(1)); // 设置缓存有效期一小时
return RedisCacheManager.builder(RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory)).cacheDefaults(redisCacheConfiguration).build();
}
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
//使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
//使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
/**
* redis数据操作异常处理 这里的处理:在日志中打印出错误信息,但是放行
* 保证redis服务器出现连接等问题的时候不影响程序的正常运行,使得能够出问题时不用缓存
*/
@Bean
@Override
public CacheErrorHandler errorHandler() {
CacheErrorHandler cacheErrorHandler = new CacheErrorHandler() {
@Override
public void handleCacheGetError(RuntimeException e, Cache cache, Object key) {
logger.error("redis异常:key=[{}]", key, e);
}
@Override
public void handleCachePutError(RuntimeException e, Cache cache, Object key, Object value) {
logger.error("redis异常:key=[{}]", key, e);
}
@Override
public void handleCacheEvictError(RuntimeException e, Cache cache, Object key) {
logger.error("redis异常:key=[{}]", key, e);
}
@Override
public void handleCacheClearError(RuntimeException e, Cache cache) {
logger.error("redis异常:", e);
}
};
return cacheErrorHandler;
}
}
Redis常用工具类
@Component
public class RedisApi {
@Autowired
private RedisTemplate redisTemplate;
/***
* 获取所有的key
*/
public Set getKeys(String pattern) {
return redisTemplate.keys(pattern);
}
/**
* 写入缓存
*
* @param key 键
* @param value 值
* @return 写入是否成功
*/
public boolean setCache(final String key, Object value) {
boolean res = false;
try {
ValueOperations opsForValue = redisTemplate.opsForValue();
opsForValue.set(key, value);
res = true;
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
/**
* 写入缓存设置失效时间
*
* @param key 键
* @param vaule 值
* @param expireTime 失效时间
* @param timeType 失效时间类型
* @return 是否写入成功
*/
public boolean setCache(final String key, Object vaule, Long expireTime, TimeUnit timeType) {
boolean res = false;
try {
ValueOperations opsForValue = redisTemplate.opsForValue();
opsForValue.set(key, vaule);
redisTemplate.expire(key, expireTime, timeType);
res = true;
} catch (Exception e) {
e.printStackTrace();
}
return res;
}
/**
* 读取缓存
*
* @param key
* @return
*/
public Object getCache(final String key) {
ValueOperations opsForValue = redisTemplate.opsForValue();
return opsForValue.get(key);
}
/**
* 删除对应的值
*
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 批量删除对应的value
*
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 判断缓存中是否对应的值
*
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 批量删除keys
*
* @param pattern
*/
public void removePattern(final String pattern) {
Set keys = redisTemplate.keys(pattern);
if (keys.size() > 0) {
redisTemplate.delete(keys);
}
}
/**
* 哈希 添加 注意:hmSet方法,
* isForce :false 只有当值不存在时存入 有值是忽略
* true 无论如何都存入
*
* @param key
* @param hashKey
* @param value
* @return 原先旧值
*/
public Object hmSet(String key, Object hashKey, Object value, boolean update) {
Object obj = null;
try {
HashOperations opsForHash = redisTemplate.opsForHash();
obj = opsForHash.get(key, hashKey);
if (obj != null && update) {
opsForHash.delete(key, hashKey);
}
opsForHash.putIfAbsent(key, hashKey, value);
} catch (Exception e) {
e.printStackTrace();
}
return obj;
}
/**
* 获取所有hashMap 键值
*/
public Map
@RestController
public class UserController {
@Autowired
private RedisApi redisApi;
@RequestMapping("/testCache")
public String testCache() {
String cache = "This have no one";
if (redisApi.getCache("testCache") == null) {
redisApi.setCache("testCache", "This is testCache");
} else {
cache = redisApi.getCache("testCache").toString();
}
return cache;
}
}