关于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. 参考
<!-- 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相关文章推荐
- jedis与spring整合及简单的使用RedisTemplate操作
- jedis与spring整合及简单的使用RedisTemplate操作
- spring boot使用redisTemplate存储键值出现乱码
- Spring中使用RedisTemplate操作Redis(spring-data-redis)
- spring boot RedisTemplate的简单使用
- spring整合redis以及使用RedisTemplate的方法
- Spring Boot StringRedisTemplate常用操作
- spring boot 整合 redis,使用@Cacheable,@CacheEvict,@CachePut,jedisPool操作redis数据库
- Spring中使用RedisTemplate操作Redis(spring-data-redis)
- 10、Spring技术栈-整合Redis,使用RedisTemplate实现数据缓存实战
- Spring Boot整合集成StringRedisTemplate的简单记录
- Spring RedisTemplate操作-序列化性能测试(12)
- Spring RedisTemplate操作-HyperLogLog操作(7)
- Spring RedisTemplate操作-注解缓存操作(11)
- [置顶] 在Springboot上使用jedis来操作缓存redis --jedis的配置
- Spring RedisTemplate操作-通道操作(10)
- spring-data-redis使用RedisTemplate模板存储时键值与预设不一致的解决方法
- spring data redis RedisTemplate操作redis相关用法
- Spring RedisTemplate操作-发布订阅操作(8)