Springboot 整合 Redis
前言
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等客户端,使用很方便。
Redis支持主从同步。数据可以从主服务器向任意数量的从服务器上同步,从服务器可以是关联其他从服务器的主服务器。这使得Redis可执行单层树复制。存盘可以有意无意的对数据进行写操作。由于完全实现了发布/订阅机制,使得从数据库在任何地方同步树时,可订阅一个频道并接收主服务器完整的消息发布记录。同步对读取操作的可扩展性和数据冗余很有帮助。
pom 依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
<version>2.0</version>
</dependency>
application.yml
spring:
redis:
# Redis数据库索引(默认为0)
database: 0
# Redis服务器地址
host: 192.168.230.11
# Redis服务器连接端口
port: 6379
# Redis服务器连接密码(默认为空)
password: 123456
# 连接超时时间(毫秒)
timeout: 10000
# 连接池最大连接数(使用负值表示没有限制)
lettuce.pool.max-active: 8
# 连接池最大阻塞等待时间
lettuce.pool.max-wait: -1ms
# 连接池中的最大空闲连接
lettuce.pool.max-idle: 8
# 连接池中的最小空闲连接
lettuce.pool.min-idle: 0
RedisConfig
package com.example.demo.common.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
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.StringRedisSerializer;
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory factory){
RedisTemplate<String,Object> redisTemplate= new RedisTemplate<>();
// 序列化方式
Jackson2JsonRedisSerializer jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper objectMapper = new ObjectMapper();
// 指定要序列化的域,field,get和set,以及修饰符范围,ANY是都有包括private和public
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
// 指定序列化输入的类型,类必须是非final修饰的,final修饰的类,比如String,Integer等会抛出异常
objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
//最近升级SpringBoot,发现enableDefaultTyping方法过期过期了。可以使用下面的方法代替
//objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.WRAPPER_ARRAY);
jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
// 连接工厂
redisTemplate.setConnectionFactory(factory);
// key 值的序列化方式
redisTemplate.setKeySerializer(new StringRedisSerializer());
// hash Key 值的序列化方式
redisTemplate.setHashKeySerializer(new StringRedisSerializer());
// value 序列化方式
redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
// hash 的 value序列化方式
redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
redisTemplate.afterPropertiesSet();
return redisTemplate;
}
}
简单使用
package com.example.demo.module.test;
import com.example.demo.common.dto.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
@Slf4j
@RestController
public class TestController {
@Autowired
RedisTemplate redisTemplate;
@GetMapping("cachingTest")
public R cachingTest(){
if(redisTemplate.hasKey("cachingTest")){
log.info("------读取缓存------");
Object cachingTest = redisTemplate.opsForValue().get("cachingTest");
return R.ok(cachingTest);
}else{
log.info("------读取本地------");
List<String> list = new ArrayList<>();
list.add("蜡笔小新");
list.add("哆啦A梦");
list.add("四驱兄弟");
//redis 存入键及数据,不设置过期时间
//redisTemplate.opsForValue().set("cachingTest",list);
//对键“cachingTest” 进行设置过期时间
//redisTemplate.expire("cachingTest",10,TimeUnit.SECONDS);
//redis 存入键及数据,并设置键过期时间为 10 单位为秒。 即键“cachingTest” 10秒后过期
redisTemplate.opsForValue().set("cachingTest",list,10, TimeUnit.SECONDS);
return R.ok(list);
}
}
}
测试
第一次访问,数据读取本地信息
10秒内再次访问时,数据将从 Redis 中获取
Redis 中存储的数据信息
RedisTemplate 常用方法
//redis 对象操作
redisTemplate.opsForValue();
//根据key键获取值
redisTemplate.opsForValue().get("cachingTest");
//截取key键对应值得字符串,从开始下标位置开始到结束下标的位置(包含结束下标)的字符串
redisTemplate.opsForValue().get("cachingTest",0,3);
//在原有的值基础上新增字符串到末尾
redisTemplate.opsForValue().append("cachingTest","abc");
//获取原来key键对应的值并重新赋新值
redisTemplate.opsForValue().getAndSet("cachingTest","def");
//设置键为 cachingTest 值为 abc ,不设置过期时间
redisTemplate.opsForValue().set("cachingTest","abc");
//覆盖从指定位置开始的值
redisTemplate.opsForValue().set("cachingTest","abc",1);
//存入键及数据,并设置键过期时间为 10 单位为秒。 即键“cachingTest” 10秒后过期
redisTemplate.opsForValue().set("cachingTest","abc",10,TimeUnit.SECONDS);
//如果键不存在则新增 返回 true,存在则不改变已经有的值 返回 false,可用作分布式锁
redisTemplate.opsForValue().setIfAbsent("cachingTest","abc");
// list 操作
redisTemplate.opsForList();
// hash 操作
redisTemplate.opsForHash();
// set 操作
redisTemplate.opsForSet();
// zset 操作
redisTemplate.opsForZSet();
//查看是否含有指定 key true false
redisTemplate.hasKey("cachingTest");
//获取指定 key 过期时间
redisTemplate.getExpire("cachingTest");
//给指定 key 设置过期时间
redisTemplate.expire("cachingTest",10,TimeUnit.SECONDS);
//删除指定 key
redisTemplate.delete("cachingTest");