您的位置:首页 > 数据库 > Redis

关于springboot整合redis(使用RedisTemplate操作redis)

2018-03-14 10:41 1031 查看
1.maven添加redis依赖
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>

2.application.yml或application.properties配置redis参数(注意yml不识别tab)redis:
host: 127.0.0.1
port: 6379
timeout: 1000
pool:
max-active: 8
min-idle: 0
max-idle: 8
max-wait: -1

# Redis数据库索引(默认为0)
#spring.redis.database=0
# Redis服务器地址
#spring.redis.host=127.0.0.1
# Redis服务器连接端口
#spring.redis.port=6379
# Redis服务器连接密码(默认为空)
#spring.redis.password=
# 连接池最大连接数(使用负值表示没有限制)
#spring.redis.pool.max-active=8
# 连接池最大阻塞等待时间(使用负值表示没有限制)
#spring.redis.pool.max-wait=-1
# 连接池中的最大空闲连接
#spring.redis.pool.max-idle=8
# 连接池中的最小空闲连接
#spring.redis.pool.min-idle=0
# 连接超时时间(毫秒)
#spring.redis.timeout=1000

3.重写CacheManager,RedisTemplate
CacheManager中设置setDefaultExpiration缓存失效时间 貌似无效。
package com.imm.redis;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
//@EnableRedisHttpSession(maxInactiveIntervalInSeconds = 3600 * 12)
@EnableCaching
public class RedisAutoConfig extends CachingConfigurerSupport {

@Bean
public CacheManager cacheManager(RedisTemplate redisTemplate) {
RedisCacheManager rcm = new RedisCacheManager(redisTemplate);
//设置缓存过期时间
//Map<String, Long> expires = new HashMap<>();
//expires.put("12h",3600 * 12L);
//expires.put("1h",3600 * 1L);
//expires.put("10m",60 * 5L);
//rcm.setExpires(expires);

//rcm.setDefaultExpiration(10); //秒
return rcm;
}
/*@Bean
public RedisTemplate<String, ?> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> redisTemplate = new RedisTemplate();
red
4000
isTemplate.setConnectionFactory(factory);
RedisSerializer<String> stringRedisSerializer = new StringRedisSerializer();//Long类型不可以会出现异常信息;
redisTemplate.setKeySerializer(stringRedisSerializer);
return redisTemplate;
}*/

@Bean
public RedisTemplate redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<Object, Object> 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;
}

}
4.RedisTemplate操作LIST/**
* redis 关于LIST 的操作
* @param map
* @param isSql 1.使用sql 0.不使用sql
* @return
*/
public List<Map<String, Object>> doRedisList(Map<String, Object> map,int isSql){

    // 从缓存中通过key获取信息
String key = "";
if(map.get("cacheKey")!=null){
key = map.get("cacheKey").toString();
}
List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();
list = redisTemplate.opsForList().range(key,0,-1);
// 缓存存在
long cacheSize = redisTemplate.opsForList().size(key);
if (cacheSize>0) {
return list;
}
//判读获取list的方法
if(isSql==0){
list = sysdao.getList(map);
}else if(isSql==1){
list = sysdao.getListBySql(map);
}

if(list !=null && list.size()>0){
// 插入缓存
redisTemplate.opsForList().leftPushAll(key,list);
//设置缓存失效时间
redisTemplate.expire(key, RedisTime.EXPIRETIME, TimeUnit.SECONDS);
}

return list;
}

5.RedisTemplate操作HASH
/**
* redis 关于MAP 的操作
* @param map
* @param isSql 1.使用sql 0.不使用sql
* @return
*/
public Map<String, Object> doRedisMap(Map<String, Object> map,int isSql){

    // 从缓存中通过key获取信息
String key = "";
if(map.get("cacheKey")!=null){
key = map.get("cacheKey").toString();
}
Map<String, Object> newmap = new HashMap<String, Object>();

newmap = redisTemplate.opsForHash().entries(key);
// 缓存存在
long cacheSize = redisTemplate.opsForHash().size(key);
if (cacheSize>0) {
return newmap;
}
//判读获取list的方法
if(isSql==0){
newmap = sysdao.getMapById(map);
}else if(isSql==1){
newmap = sysdao.getMapBySql(map);
}

if(newmap !=null && newmap.size()>0){
// 插入缓存
redisTemplate.opsForHash().putAll(key,newmap);
//设置缓存失效时间
redisTemplate.expire(key, RedisTime.EXPIRETIME, TimeUnit.SECONDS);
}

return newmap;
}

6.RedisTemplate 删除缓存
/**
* redis 删除 操作
* 此处除了删除单条信息及对应缓存、包括父级所有缓存
* @param map
* @return
*/
public void doRedisDelete(Map<String, Object> map){

// 从缓存中通过key获取信息
String key = ""; //当前key
String keys = ""; //父一级key的前缀
if(map.get("cacheKey")!=null){
key = map.get("cacheKey").toString();
String[] keyArr = key.split("_");
keys = keyArr[0]+"_List";
}

boolean hasKey = redisTemplate.hasKey(key);
if (hasKey) {
redisTemplate.delete(key);
}

//获取父一级所有key
Set<String> keySet = redisTemplate.keys(keys + "*");
redisTemplate.delete(keySet);
}
7.注意缓存的key的命名问题,更新和删除单条信息时,需要删除父一级所有缓存。

8. 存入非string类型的值,可能会出现\xAC\xED\x00\x05t\x00\x0。对取值数据没有影响。
9. 参考

Spring中使用RedisTemplate操作Redis(spring-data-redis)

 https://www.cnblogs.com/EasonJim/p/7803067.html#autoid-2-6-0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: