public class RedisUtils {
@Autowired
private StringRedisTemplate redisTemplate;
/**
* 写入缓存
*
* @param key
* @param value
* @return
*/
public boolean set(final String key, String value) {
boolean result = false;
try {
ValueOperations<String, String> operations = redisTemplate.opsForValue();
byte[] bytes = key.getBytes("ISO8859-1");
byte[] bytes2 = value.getBytes("ISO8859-1");
String str = new String(bytes, "UTF-8");
String str2 = new String(bytes2, "UTF-8");
operations.set(str, str2);
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
}
return result;
}
/**
* 写入缓存设置时效时间
*
* @param key
* @param value
* @return
*/
public boolean setExp(final String key, String value, Long expireTime) {
boolean result = false;
try {
ValueOperations<String, String> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
}
return result;
}
/**
* 批量删除对应的value
*
* @param keys
*/
public void removes(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
*
* @param pattern
*/
public void removes(final String pattern) {
try {
Set<String> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
} finally {
RedisConnectionUtils.unbindConnection(redisTemplate.getConnectionFactory());
}
}
/**
* 删除对应的value
*
* @param key
*/
public void remove(final String key) {
try {
if (exists(key)) {
redisTemplate操作Redis工具类
最新推荐文章于 2024-07-28 12:18:58 发布