Spring-Boot-Data-Redis使用
Spring Data Redis 是 Spring 框架提供的一个模块,用于简化与 Redis 数据库交互的操作。它支持多种 Redis 客户端库,如 Jedis 和 Lettuce。Spring Boot Data Redis 是 Spring Boot 对 Spring Data Redis 的自动配置模块,它可以极大地简化 Redis 的配置和使用
安装
xml
复制代码
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency>
配置
yaml
复制代码
spring: redis: url: redis://127.0.0.1:6379 database: 0 connect-timeout: 3000ms timeout: 3000ms
使用
@EnableCaching
用于开启基于注解的缓存功能。使用这个注解可以启用 Spring 的缓存抽象,从而使应用程序中的缓存功能得以运作。
示例:
java
复制代码
@SpringBootApplication @EnableCaching public class LearnRedisApplication { public static void main(String[] args) { SpringApplication.run(LearnRedisApplication.class,args); } }
@Cacheable
用于将方法的返回值缓存起来,以提高应用程序的性能。常用于查询方法上。常用属性有:
- value 或 cacheNames:指定缓存的名称或名称列表。
- key:指定缓存条目的键,支持 SpEL 表达式。
- condition:指定缓存条件,满足条件时才缓存,支持 SpEL 表达式。
- unless:指定不缓存的条件,满足条件时不缓存,支持 SpEL 表达式。
- sync:是否使用同步缓存,即同一个方法并发调用时,只有一个线程会执行方法,其它线程会等待结果并返回缓存结果。
示例:
java
复制代码
@Cacheable(key = "'student:' + #id" ,value = RedisConfig.REDIS_KEY_DATABASE) @Override public StudentEntity getById(Integer id) { StudentEntity entity = studentDao.getById(id); return entity; }
@CachePut
用于更新缓存中的数据。与 @Cacheable
注解不同,@CachePut
注解标注的方法总是会执行,并将其返回值更新到指定的缓存中。常用属性:
- value 或 cacheNames:指定缓存的名称或名称列表。
- key:指定缓存条目的键,支持 SpEL 表达式。
- condition:指定缓存条件,满足条件时才缓存,支持 SpEL 表达式。
- unless:指定不缓存的条件,满足条件时不缓存,支持 SpEL 表达式。
示例:
java
复制代码
@CachePut(key = "'student:' + #result.studentId" ,value = RedisConfig.REDIS_KEY_DATABASE) @Override public StudentEntity insert(StudentEntity entity) { StudentEntity inserted = studentDao.insert(entity); return inserted; }
@CacheEvict
在方法执行后移除指定缓存中的数据。常用属性:
- value 或 cacheNames:指定缓存的名称或名称列表。
- key:指定缓存条目的键,支持 SpEL 表达式。
- condition:指定缓存条件,满足条件时才缓存,支持 SpEL 表达式。
示例:
java
复制代码
@CacheEvict(key = "'student:' + #id" ,value = RedisConfig.REDIS_KEY_DATABASE) @Override public int delete(Integer id) { int deleted = studentDao.delete(id); return deleted; }
Redis存储Json数据
Jedis和Lettuce
Spring Data Redis 是 Spring 提供的一个模块,用于与 Redis 进行交互。它提供了对 Redis 的集成支持,并简化了 Redis 操作的使用。Lettuce
则是 Spring Data Redis 中默认的 Redis 客户端。
Jedis
特点
- 同步和阻塞式 API:
Jedis
使用同步和阻塞式 API,这意味着每个 Redis 操作都会阻塞调用线程直到操作完成。 - 连接管理:
Jedis
每次操作都会创建和销毁连接,通常与连接池(如 Apache Commons Pool)一起使用来管理连接。 - 简单易用:
Jedis
API 设计简单,易于使用,非常适合快速开发和简单的 Redis 操作场景。
优点
- 简单易用,API 设计直观。
- 适合单线程环境和简单的使用场景。
缺点
- 阻塞式操作在高并发场景下性能不佳。
- 不支持异步和响应式编程模型。
Lettuce
特点
- 非阻塞和异步 API:
Lettuce
基于 Netty 实现,提供非阻塞和异步 API,支持高并发操作。 - 多种编程模型:支持同步、异步和响应式(Reactive Streams)编程模型,适应不同的使用场景。
- 自动重连和集群支持:提供自动重连机制,支持 Redis 集群和哨兵模式。
优点
- 非阻塞和异步操作,适合高并发场景。
- 支持多种编程模型,灵活性高。
- 支持自动重连和 Redis 高可用配置。
缺点
- API 相对复杂,学习曲线较陡。
配置参数
yaml
复制代码
spring: redis: url: redis://127.0.0.1:6379 database: 0 connect-timeout: 3000ms timeout: 3000ms lettuce: pool: # 连接池最大空闲连接,默认为8 max-idle: 10 # 连接池最小空闲连接,默认为0 min-idle: 5 # 连接池最大连接数(负数代表没有限制) 默认为8 max-active: 50 # 连接池最大阻塞等待时间(使用负值代表没有限制)默认为-1mx max-wait: -1ms
配置类
java
复制代码
@EnableCaching @Configuration public class RedisConfig { public static final String REDIS_KEY_DATABASE = "learn"; @Bean public RedisTemplate<String,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){ RedisSerializer<Object> redisSerializer = redisSerializer(); RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>(); redisTemplate.setConnectionFactory(redisConnectionFactory); redisTemplate.setKeySerializer(new StringRedisSerializer()); redisTemplate.setValueSerializer(redisSerializer); redisTemplate.setHashKeySerializer(new StringRedisSerializer()); redisTemplate.setHashValueSerializer(redisSerializer); return redisTemplate; } @Bean public RedisSerializer<Object> redisSerializer(){ // 创建json序列器 Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class); ObjectMapper objectMapper = new ObjectMapper(); objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY); objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,ObjectMapper.DefaultTyping.NON_FINAL); serializer.setObjectMapper(objectMapper); return serializer; } @Bean public RedisCacheManager redisCacheManager(RedisConnectionFactory redisConnectionFactory){ // 执行缓存时不使用分布式锁,提高性能。避免额外的锁操作 RedisCacheWriter redisCacheWriter = RedisCacheWriter.nonLockingRedisCacheWriter(redisConnectionFactory); // 默认缓存配置,缓存时间为一天 RedisCacheConfiguration redisCacheConfiguration = RedisCacheConfiguration.defaultCacheConfig() .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer())) .entryTtl(Duration.ofDays(1)); return new RedisCacheManager(redisCacheWriter,redisCacheConfiguration); } }
使用
java
复制代码
@Component public class RedisHelper { @Resource private RedisTemplate<String,Object> redisTemplate; public void set(String key,Object value){ redisTemplate.opsForValue().set(key,value); } public Object get(String key){ return redisTemplate.opsForValue().get(key); } public void del (String key){ redisTemplate.delete(key); } .....