springboot集成redis其实比较简单,但是网上很多集成不够全面,存取值转换封装的不够完美,好了,废话不多说,
直接上代码。
配置代码如下:
package com.serverconfig.cache;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
*
* @Title: RedisConfig.java
* @Package com.shop.cache
* @Description: TODO(redis配置类)
* @author: jiazhenlong
* @date: 2018年5月29日 上午9:56:11
* @version V1.0
* @Copyright: 2018 wehere All rights reserved.
*/
@Configuration
public class RedisConfig extends CachingConfigurerSupport {
@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory factory) {
RedisTemplate redisTemplate = new RedisTemplate();
redisTemplate.setConnectionFactory(factory);
//设置序列化工具
setSerializer(redisTemplate);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
private void setSerializer(RedisTemplate template) {
@SuppressWarnings("rawtypes")
RedisSerializer stringSerializer = new StringRedisSerializer();
template.setValueSerializer(stringSerializer);
template.setKeySerializer(stringSerializer);
template.setHashKeySerializer(stringSerializer);
template.setHashValueSerializer(stringSerializer);
}
}
工具代码如下:
package com.serverconfig.cache;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
/**
*
* @Title: RedisTemplateHelp.java
* @Package com.shop.cache
* @Description: TODO(redis服务类)
* @author: jiazhenlong
* @date: 2018年5月29日 上午11:01:06
* @version V1.0
* @Copyright: 2018 wehere All rights reserved.
*/
@Service
public class RedisTemplateHelp {
private static final Logger LOG = LoggerFactory.getLogger(RedisTemplateHelp.class);
@Autowired
private RedisTemplate redisTemplate;
public void setRedisTemplate(RedisTemplate redisTemplate) {
this.redisTemplate = redisTemplate;
}
// =============================common============================
/**
* 指定缓存失效时间
* @param key 键
* @param time 时间(秒)
* @return
*/
public boolean expire(String key,
long time) {
try {
if (time > 0) {
redisTemplate.expire(key, time, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return false;
}
}
/**
* 根据key 获取过期时间
* @param key 键 不能为null
* @return 时间(秒) 返回0代表为永久有效
*/
public long getExpire(String key) {
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断key是否存在
* @param key 键
* @return true 存在 false不存在
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return false;
}
}
/**
* 删除缓存
* @param key 可以传一个值 或多个
*/
@SuppressWarnings("unchecked")
public void del(String... key) {
if (key != null && key.length > 0) {
if (key.length == 1) {
redisTemplate.delete(key[0]);
} else {
redisTemplate.delete(CollectionUtils.arrayToList(key));
}
}
}
// ============================String=============================
/**
* 普通缓存获取
* @param key 键
* @return 值
*/
@SuppressWarnings({"unchecked", "static-access"})
public T get(String key, Class clazz) {
Object value = redisTemplate.opsForValue().get(key);
if (value != null) {
String temp;
try {
temp = new String();
temp = temp.valueOf(value);
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return null;
}
if (clazz.isPrimitive()) {
if (String.class.isAssignableFrom(clazz)) {
return (T) temp;
} else if (int.class.isAssignableFrom(clazz)) {
return (T) new Integer(temp);
} else if (long.class.isAssignableFrom(clazz)) {
return (T) new Long(temp);
} else if (boolean.class.isAssignableFrom(clazz)) {
return (T) new Boolean(temp);
} else if (double.class.isAssignableFrom(clazz)) {
return (T) new Double(temp);
} else if (float.class.isAssignableFrom(clazz)) {
return (T) new Float(temp);
} else if (byte.class.isAssignableFrom(clazz)) {
return (T) new Byte(temp);
} else if (short.class.isAssignableFrom(clazz)) {
return (T) new Short(temp);
} else {
throw new RuntimeException("unsupport type:type=" + clazz.getName() + "value="
+ temp);
}
} else {
return JSON.parseObject(temp, clazz);
}
}
return null;
}
/**
* 普通缓存放入
* @param key 键
* @param value 值
* @return true成功 false失败
*/
public boolean set(String key,
Object value) {
try {
redisTemplate.opsForValue().set(key,
JSON.toJSONString(value, SerializerFeature.WriteClassName));
return true;
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return false;
}
}
/**
* 普通缓存放入并设置时间
* @param key 键
* @param value 值
* @param time 时间(秒) time要大于0 如果time小于等于0 将设置无限期
* @return true成功 false 失败
*/
public boolean set(String key,
T value,
long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key,
JSON.toJSONString(value, SerializerFeature.WriteClassName), time, TimeUnit.SECONDS);
} else {
set(key, value);
}
return true;
} catch (Exception e) {
LOG.error(e.getMessage(), e);
return false;
}
}
/**
* 递增
* @param key 键
* @param by 要增加几(大于0)
* @return
*/
public long incr(String key,
long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* @param key 键
* @param by 要减少几(小于0)
* @return
*/
public long decr(String key,
long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于0");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
// ================================Map=================================
/**
* HashGet
* @param key 键 不能为null
* @param item 项 不能为null
* @return 值
*/
public Object hget(String key,
String item) {
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key 键
* @return 对应的多个键值
*/
public Map