SpringBoot整合Redis缓存及Redis工具操作类
1. 加入Redis依赖
<!-- 整合Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
2. 配置Redis基础信息
配置文件:application.properties
#Redis
spring.redis.database=0
spring.redis.hostName=127.0.0.1
spring.redis.port=6379
spring.redis.password=123456
spring.redis.pool.max-active=200
spring.redis.pool.max-wait=-1
spring.redis.pool.max-idle=10
spring.redis.pool.min-idle=0
spring.redis.timeout=1000
创建Redis配置类:RedisConfig.java
@Configuration
@EnableCaching //开启注解,redis缓存
public class RedisConfig extends CachingConfigurerSupport {
@Bean
@SuppressWarnings("all")
public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig()
.entryTtl(Duration.ofSeconds(30)); //设置缓存有效期30分钟
cacheNames.add("redisCache"); //缓存命名
Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
configMap.put("redisCache",config); //缓存配置
return RedisCacheManager
.builder(factory)
.initialCacheNames(cacheNames)
.withInitialCacheConfigurations(configMap)
.build();
}
@Bean
@SuppressWarnings("all")
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<String, Object>();
template.setConnectionFactory(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);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
//key-value序列化方式
template.setKeySerializer(stringRedisSerializer); //key采用String的序列化方式
template.setValueSerializer(jackson2JsonRedisSerializer); //value序列化方式采用jackson
//hash-value序列化方式
template.setHashKeySerializer(stringRedisSerializer); //hash的key也采用String的序列化方式
template.setHashValueSerializer(jackson2JsonRedisSerializer); //hash的value序列化方式采用jackson
template.afterPropertiesSet();
return template;
}
}
3.修改启动类,开启缓存
@SpringBootApplication
@EnableTransactionManagement //开启事务管理
@EnableCaching //开启缓存
public class ShanxiangcrmApplication extends SpringBootServletInitializer {
public static void main(String[] args) {
SpringApplication.run(ShanxiangcrmApplication.class, args);
}
}
4.创建Redis工具类RedisUtil.java
@Component
public final class RedisUtil {
@Resource
private RedisTemplate<String, Object> redisTemplate;
/**
* 指定key失效时间,单位为秒
* @param key 指定的key
* @param secondsTime 国企时间
*/
public boolean expire(String key, long secondsTime){
try {
if (secondsTime > 0) {
redisTemplate.expire(key, secondsTime, TimeUnit.SECONDS);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 查询指定key的过期时间
* @param key 指定key
*/
public long getExpire(String key) {
if(null == key){
return 0;
}
return redisTemplate.getExpire(key, TimeUnit.SECONDS);
}
/**
* 判断是否存在指定key的缓存
* @param key 指定key
*/
public boolean hasKey(String key) {
try {
return redisTemplate.hasKey(key);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除指定的key的缓存
* @param key 指定key
*/
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));
}
}
}
/**
* 普通缓存获取
* @param key 指定的key
*/
public Object get(String key) {
return key == null ? null : redisTemplate.opsForValue().get(key);
}
/**
* 添加普通缓存
* @param key key
* @param value value
*/
public boolean set(String key, Object value) {
try {
redisTemplate.opsForValue().set(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 添加普通缓存
* @param key key
* @param value value
* @param time time过期时间
*/
public boolean set(String key, Object value, long time) {
try {
if (time > 0) {
redisTemplate.opsForValue().set(key, value, time, TimeUnit.SECONDS);
}else{
set(key, value);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 递增
* @param key key
* @param delta 大于0
*/
public long incr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递增因子必须大于零");
}
return redisTemplate.opsForValue().increment(key, delta);
}
/**
* 递减
* @param key key
* @param delta 大于0
*/
public long decr(String key, long delta) {
if (delta < 0) {
throw new RuntimeException("递减因子必须大于零");
}
return redisTemplate.opsForValue().increment(key, -delta);
}
/**
* HashGet
* @param key 不能为null
* @param item 不能为null
*/
public Object hget(String key, String item) {
if(null == key || null == item){
throw new RuntimeException("存入键值或数据为空");
}
return redisTemplate.opsForHash().get(key, item);
}
/**
* 获取hashKey对应的所有键值
* @param key 不能为null
*/
public Map<Object, Object> hmget(String key) {
if(null == key){
throw new RuntimeException("查询键值为空");
}
return redisTemplate.opsForHash().entries(key);
}
/**
* HashSet 是否存在
* @param key
* @param map
*/
public boolean hmset(String key, Map<String, Object> map) {
try {
redisTemplate.opsForHash().putAll(key, map);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* HashSet 并设置时间
* @param key 键值
* @param map 存储数据
* @param time 过期时间
*/
public boolean hmset(String key, Map<String, Object> map, long time) {
try {
redisTemplate.opsForHash().putAll(key, map);
if (time > 0) {
expire(key,time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key
* @param item
* @param value
*/
public boolean hset(String key, String item, Object value) {
try {
redisTemplate.opsForHash().put(key, item, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 向一张hash表中放入数据,如果不存在将创建
* @param key
* @param item
* @param value
* @param time 如果已存在的hash表有时间,这里将会替换原有的时间
*/
public boolean hset(String key, String item, Object value, long time) {
try {
redisTemplate.opsForHash().put(key, item, value);
if (time > 0) {
expire(key,time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 删除hash表中的值
* @param key
* @param item
*/
public void hdel(String key, Object[] item) {
redisTemplate.opsForHash().delete(key, item);
}
/**
* 判断hash表中是否有该项的值
* @param key
* @param item
*/
public boolean hHasKey(String key, String item) {
return redisTemplate.opsForHash().hasKey(key, item);
}
/**
* hash递增 如果不存在,就会创建一个 并把新增后的值返回
* @param key
* @param item
* @param by 要增加几(大于0)
*/
public double hincr(String key, String item, double by) {
if(by < 0){
throw new RuntimeException("递增必须大于零");
}
return redisTemplate.opsForHash().increment(key, item, by);
}
/**
* hash递减
* @param key
* @param item
* @param by 要增加几(大于0)
*/
public double hdecr(String key, String item, double by) {
if(by < 0){
throw new RuntimeException("递减必须大于零");
}
return redisTemplate.opsForHash().increment(key, item, -by);
}
/**
* 根据key获取Set中的所有值
* @param key
*/
public Set<Object> sGet(String key) {
try {
return redisTemplate.opsForSet().members(key);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 根据value从一个set中查询,是否存在
* @param key
* @param value
*/
public boolean sHasKey(String key, Object value) {
try {
return redisTemplate.opsForSet().isMember(key, value);
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将数据放入set缓存
* @param key
* @param values
*/
public long sSet(String key, Object... values) {
try {
return redisTemplate.opsForSet().add(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 将set数据放入缓存
* @param key
* @param time 过期时间
* @param values
*/
public long sSetAndTime(String key, long time, Object... values) {
try {
Long count = redisTemplate.opsForSet().add(key, values);
if(time > 0){
expire(key,time);
}
return count;
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取set缓存的长度
* @param key
*/
public long sGetSetSize(String key) {
try {
return redisTemplate.opsForSet().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 移除值为value的数据
* @param key
* @param values
*/
public long setRemove(String key, Object... values) {
try {
return redisTemplate.opsForSet().remove(key, values);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 获取list缓存的内容
* @param key
* @param start 开始
* @param end 结束 0 到 -1代表所有值
*/
public List<Object> lGet(String key, long start, long end) {
try {
return redisTemplate.opsForList().range(key, start, end);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 获取list缓存的长度
* @param key
*/
public long lGetListSize(String key) {
try {
return redisTemplate.opsForList().size(key);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
/**
* 通过索引 获取list中的值
* @param key
* @param index 索引 index>=0时, 0 表头,1 第二个元素,依次类推;index<0时,-1,表尾,-2倒数第二个元素,依次类推
*/
public Object lGetIndex(String key, long index) {
try {
return redisTemplate.opsForList().index(key, index);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
/**
* 将list放入缓存
* @param key
* @param value
*/
public boolean lSet(String key, Object value) {
try {
redisTemplate.opsForList().rightPush(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key
* @param value
* @param time time 时间(秒)
*/
public boolean lSet(String key, Object value, long time) {
try {
redisTemplate.opsForList().rightPush(key, value);
if(time > 0){
expire(key,time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key
* @param value
*/
public boolean lSet(String key, List<Object> value) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 将list放入缓存
* @param key
* @param value
* @param time
*/
public boolean lSet(String key, List<Object> value, long time) {
try {
redisTemplate.opsForList().rightPushAll(key, value);
if(time > 0){
expire(key,time);
}
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 根据索引修改list中的某条数据
* @param key
* @param index
* @param value
*/
public boolean lUpdateIndex(String key, long index, Object value) {
try {
redisTemplate.opsForList().set(key, index, value);
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
/**
* 移除N个值为value
* @param key
* @param count
* @param value
*/
public long lRemove(String key, long count, Object value) {
try {
return redisTemplate.opsForList().remove(key, count, value);
} catch (Exception e) {
e.printStackTrace();
return 0;
}
}
}
5.缓存操作
@Override
@Cacheable(value = "redisCache",key = "#root.method.name")
public List<User> getAll() throws Exception {
List<User> list = userMapper.getAll();
redisUtil.lSet("UserList",list); //通过redis工具类操作redis数据库
return list;
}
运行并访问方法,查看Redis
可以看到,redis库中存在两条记录