1.Redis简介
redis是一个key-value存储系统。和Memcached类似,它支持存储的value类型相对更多,包括string(字符串)、list(链表)、set(集合)、zset(sorted set --有序集合)和hash(哈希类型)。这些数据类型都支持push/pop、add/remove及取交集并集和差集及更丰富的操作,而且这些操作都是原子性的。在此基础上,redis支持各种不同方式的排序。与memcached一样,为了保证效率,数据都是缓存在内存中。区别的是redis会周期性的把更新的数据写入磁盘或者把修改操作写入追加的记录文件,并且在此基础上实现了master-slave(主从)同步。
Redis 是一个高性能的key-value数据库。 redis的出现,很大程度补偿了memcached这类key/value存储的不足,在部 分场合可以对关系数据库起到很好的补充作用。它提供了Java,C/C++,C#,PHP,JavaScript,Perl,Object-C,Python,Ruby,Erlang等客户端,使用很方便。
2.启动运行Redis
安装及启动可自行百度
3.pom.xml引用redis依赖
org.springframework.boot
spring-boot-starter-data-redis
4.application.yml配置文件配置Redis参数
# redis 配置
spring:
redis:
# 地址
host: 127.0.0.1
# 端口,默认为6379
port: 6379
# 数据库索引
database: 0
# 密码
password:
# 连接超时时间
timeout: 10s
lettuce:
pool:
# 连接池中的最小空闲连接
min-idle: 0
# 连接池中的最大空闲连接
max-idle: 8
# 连接池的最大数据库连接数
max-active: 8
# #连接池最大阻塞等待时间(使用负值表示没有限制)
max-wait: -1ms
5.组装Redis配置类RedisConfig.java
/**
* redis配置
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport
{
@Bean
@SuppressWarnings(value = { "unchecked", "rawtypes" })
public RedisTemplate<Object, Object> redisTemplate(RedisConnectionFactory connectionFactory)
{
RedisTemplate<Object, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
FastJson2JsonRedisSerializer serializer = new FastJson2JsonRedisSerializer(Object.class);
ObjectMapper mapper = new ObjectMapper();
mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
mapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
serializer.setObjectMapper(mapper);
template.setValueSerializer(serializer);
// 使用StringRedisSerializer来序列化和反序列化redis的key值
template.setKeySerializer(new StringRedisSerializer());
template.afterPropertiesSet();
return template;
}
}
6.自定义Redis操作工具类RedisCache.java
@Component
public class RedisCache {
@Autowired
public RedisTemplate redisTemplate;
public RedisCache() {
}
public <T> void setCacheObject(String key, T value) {
this.redisTemplate.opsForValue().set(key, value);
}
public <T> void setCacheObject(String key, T value, Integer timeout, TimeUnit timeUnit) {
this.redisTemplate.opsForValue().set(key, value, (long)timeout, timeUnit);
}
public boolean expire(String key, long timeout) {
return this.expire(key, timeout, TimeUnit.SECONDS);
}
public boolean expire(String key, long timeout, TimeUnit unit) {
return this.redisTemplate.expire(key, timeout, unit);
}
public <T> T getCacheObject(String key) {
ValueOperations<String, T> operation = this.redisTemplate.opsForValue();
return operation.get(key);
}
public boolean deleteObject(String key) {
return this.redisTemplate.delete(key);
}
public long deleteObject(Collection collection) {
return this.redisTemplate.delete(collection);
}
public <T> long setCacheList(String key, List<T> dataList) {
Long count = this.redisTemplate.opsForList().rightPushAll(key, dataList);
return count == null ? 0L : count;
}
public <T> List<T> getCacheList(String key) {
return this.redisTemplate.opsForList().range(key, 0L, -1L);
}
public <T> BoundSetOperations<String, T> setCacheSet(String key, Set<T> dataSet) {
BoundSetOperations<String, T> setOperation = this.redisTemplate.boundSetOps(key);
Iterator it = dataSet.iterator();
while(it.hasNext()) {
setOperation.add(new Object[]{it.next()});
}
return setOperation;
}
public <T> Set<T> getCacheSet(String key) {
return this.redisTemplate.opsForSet().members(key);
}
public <T> void setCacheMap(String key, Map<String, T> dataMap) {
if (dataMap != null) {
this.redisTemplate.opsForHash().putAll(key, dataMap);
}
}
public <T> Map<String, T> getCacheMap(String key) {
return this.redisTemplate.opsForHash().entries(key);
}
public <T> void setCacheMapValue(String key, String hKey, T value) {
this.redisTemplate.opsForHash().put(key, hKey, value);
}
public <T> T getCacheMapValue(String key, String hKey) {
HashOperations<String, String, T> opsForHash = this.redisTemplate.opsForHash();
return opsForHash.get(key, hKey);
}
public <T> List<T> getMultiCacheMapValue(String key, Collection<Object> hKeys) {
return this.redisTemplate.opsForHash().multiGet(key, hKeys);
}
public Collection<String> keys(String pattern) {
return this.redisTemplate.keys(pattern);
}
}
7.编写测试工具类测试
@SpringBootTest
class WebApplicationTests {
@Autowired
private RedisCache redisCache;
@Test
void contextLoads() {
redisCache.deleteObject("test_key");
redisCache.setCacheObject("test_key", "123123");
}
}