redis工具类
redisUtil
package com.example.util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.util.List;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* Created by tym on 2018/8/27 0027.
*/
@Component
public class RedisUtil {
@Autowired
StringRedisTemplate stringRedisTemplate;
@Autowired
RedisTemplate redisTemplate;
@PostConstruct
public void init(){
System.out.println(redisTemplate);
System.out.println(redisTemplate.getValueSerializer());
System.out.println(stringRedisTemplate);
System.out.println(stringRedisTemplate.getValueSerializer());
}
/**
* 写入缓存
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 写入缓存设置失效时间
* @param key
* @param value
* @return
*/
public boolean set(final String key, Object value, Long expireTime) {
boolean result = false;
try {
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
operations.set(key, value);
redisTemplate.expire(key, expireTime, TimeUnit.SECONDS);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 批量删除对应的value
* @param keys
*/
public void remove(final String... keys) {
for (String key : keys) {
remove(key);
}
}
/**
* 批量删除key
* @param pattern
*/
public void removePattern(final String pattern) {
Set<Serializable> keys = redisTemplate.keys(pattern);
if (keys.size() > 0)
redisTemplate.delete(keys);
}
/**
* 删除对应的value
* @param key
*/
public void remove(final String key) {
if (exists(key)) {
redisTemplate.delete(key);
}
}
/**
* 判断缓存中是否有对应的value
* @param key
* @return
*/
public boolean exists(final String key) {
return redisTemplate.hasKey(key);
}
/**
* 读取缓存
* @param key
* @return
*/
public Object get(final String key) {
Object result = null;
ValueOperations<Serializable, Object> operations = redisTemplate.opsForValue();
result = operations.get(key);
return result;
}
/**
* 哈希 添加
* @param key
* @param hashKey
* @param value
*/
public void hmSet(String key, Object hashKey, Object value){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
hash.put(key,hashKey,value);
}
/**
* 哈希获取数据
* @param key
* @param hashKey
* @return
*/
public Object hmGet(String key, Object hashKey){
HashOperations<String, Object, Object> hash = redisTemplate.opsForHash();
return hash.get(key,hashKey);
}
/**
* 列表添加
* @param k
* @param v
*/
public void lPush(String k,Object v){
ListOperations<String, Object> list = redisTemplate.opsForList();
list.leftPush(k,v);
}
/**
* 列表获取
* @param k
* @param l
* @param l1
* @return
*/
public List<Object> lRange(String k, long l1, long l2){
ListOperations<String, Object> list = redisTemplate.opsForList();
return list.range(k,l1,l2);
}
/**
* 集合添加
* @param key
* @param value
*/
public void add(String key,Object value){
SetOperations<String, Object> set = redisTemplate.opsForSet();
set.add(key,value);
}
/**
* 集合获取
* @param key
* @return
*/
public Set<Object> setMembers(String key){
SetOperations<String, Object> set = redisTemplate.opsForSet();
return set.members(key);
}
/**
* 有序集合添加
* @param key
* @param value
* @param scoure
*/
public void zAdd(String key,Object value,double scoure){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
zset.add(key,value,scoure);
}
/**
* 有序集合获取
* @param key
* @param scoure
* @param scoure1
* @return
*/
public Set<Object> rangeByScore(String key, double scoure, double scoure1){
ZSetOperations<String, Object> zset = redisTemplate.opsForZSet();
return zset.rangeByScore(key, scoure, scoure1);
}
}
使用springboot
Redis桌面管理工具:redis-desktop-manager
官网(收费):https://redisdesktop.com/download
SpringBoot+Redis:
SpringBoot1.x:
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-redis</artifactId>
</dependency>
spring:
redis:
database: 0
host: localhost
port: 6379
password:
timeout: 60
pool:
max-active: 10
max-wait: -1
max-idle: 5
min-idle: 3
SpringBoot2.x:
<!-- redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
spring:
redis:
host: 127.0.0.1
port: 6379
password: root
database: 0
timeout: 10s # 数据库连接超时时间,2.0 中该参数的类型为Duration,这里在配置的时候需要指明单位
# 连接池配置,2.0中直接使用jedis或者lettuce配置连接池
jedis|lettuce:
pool:
max-idle: 50 # 最大空闲连接数
min-idle: 10 # 最小空闲连接数
max-wait: -1s # 等待可用连接的最大时间,负数为不限制
max-active: -1 # 最大活跃连接数,负数为不限制
#集群(注释上面host和port)
cluster:
nodes:
- 192.168.174.131:6379
- 192.168.174.131:6380
- 192.168.174.131:6381
#哨兵
sentinel:
master: mymaster
nodes:
- 192.168.174.131:26379
- 192.168.174.131:26380
一、SpringBoot使用的模板类:
RedisTemplate和StringRedisTemplate的区别:
-
两者的关系是StringRedisTemplate继承RedisTemplate。
-
两者的数据是不共通的;也就是说StringRedisTemplate只能管理StringRedisTemplate里面的数据,RedisTemplate只能管理RedisTemplate中的数据。
-
SDR默认采用的序列化策略有两种,一种是String的序列化策略,一种是JDK的序列化策略。
StringRedisTemplate默认采用的是String的序列化策略,保存的key和value都是采用此策略序列化保存的。
RedisTemplate默认采用的是JDK的序列化策略,保存的key和value都是采用此策略序列化保存的。
二、Spring管理缓存:
@Cacheable、@CachePut、@CacheEvict,必须使用@EnableCaching开启,CacheManager可选
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
//默认缓存管理器
@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheManager cacheManager = RedisCacheManager.create(factory);
return cacheManager;
}
}
使用参数id作为键,方法返回值作为值,而且忽略空值,存入缓存,下次调用根据键取值,如果有直接返回而不调用该方法,condition表示满足条件才执行缓存:
@Cacheable放在一个类上时则表示该类所有的方法都是支持缓存的,条件不满足直接执行方法
@Cacheable(value="user", key="#id", unless="#result==null", condition="#id%2==0")
public Users getUser(int id) {
System.out.println("UsersService:");
Users u = usersDao.findById(id);
return u;
}
注意:返回对象的时候报java.lang.ClassCastException是和热部署冲突!
去掉SpringBoot热部署就可以了
@CachePut类似@Cacheable,不同的是它不会查看缓存是否存在,而是直接保存到缓存
@CacheEvict是用来标注在需要清除缓存元素的方法或类上的,可以指定的属性有value、key、condition、allEntries和beforeInvocation
allEntries表示是否需要清除缓存中的所有元素。默认为false,表示不需要。
beforeInvocation默认是在对应方法成功执行之后触发的,即方法如果因为抛出异常而未能成功返回时也不会触发清除操作。
使用注解版springboot整合redis时可以自行配置redis存储有效期:
Redisconfig.java
package com.example.util;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.context.annotation.Bean;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.cache.RedisCacheWriter;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import java.time.Duration;
import java.util.HashMap;
import java.util.Map;
/**
* Created by tym on 2018/8/27 0027.
* Redis缓存配置类
* 该缓存配置不支持redis2.x.x
*/
//@Configuration
public class RedisConfig extends CachingConfigurerSupport {
//默认缓存管理器
/*@Bean
public CacheManager cacheManager(RedisConnectionFactory factory) {
RedisCacheManager cacheManager = RedisCacheManager.create(factory);
return cacheManager;
}*/
//缓存管理器
@Bean
public CacheManager cacheManager(RedisConnectionFactory connectionFactory) {
//反序列化
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
/*GenericJackson2JsonRedisSerializer serializer = new GenericJackson2JsonRedisSerializer(om);*/
Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
serializer.setObjectMapper(om);
//设置缓存配置
RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
config = config.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(serializer))
.entryTtl(Duration.ofSeconds(300)) //缓存时间,秒
.disableCachingNullValues() //不缓存空值
.prefixKeysWith("user"); //缓存区间
RedisCacheConfiguration config2 = RedisCacheConfiguration.defaultCacheConfig();
config2 = config.serializeValuesWith(
RedisSerializationContext.SerializationPair.fromSerializer(serializer))
.entryTtl(Duration.ofSeconds(60)) //缓存时间,秒
.disableCachingNullValues() //不缓存空值
.prefixKeysWith("news"); //缓存区间
//对每个缓存空间应用不同的配置
Map<String, RedisCacheConfiguration> configMap = new HashMap<>();
configMap.put("user", config);
configMap.put("news", config2);
//初始化一个RedisCacheWriter
RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(connectionFactory);
//初始化RedisCacheManager
RedisCacheManager cacheManager = new RedisCacheManager(redisCacheWriter, config, configMap);
return cacheManager;
}
}