Spring-Boot-Data-Redis学习使用

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
特点
  1. 同步和阻塞式 APIJedis 使用同步和阻塞式 API,这意味着每个 Redis 操作都会阻塞调用线程直到操作完成。
  2. 连接管理Jedis 每次操作都会创建和销毁连接,通常与连接池(如 Apache Commons Pool)一起使用来管理连接。
  3. 简单易用Jedis API 设计简单,易于使用,非常适合快速开发和简单的 Redis 操作场景。
优点
  • 简单易用,API 设计直观。
  • 适合单线程环境和简单的使用场景。
缺点
  • 阻塞式操作在高并发场景下性能不佳。
  • 不支持异步和响应式编程模型。
Lettuce
特点
  1. 非阻塞和异步 APILettuce 基于 Netty 实现,提供非阻塞和异步 API,支持高并发操作。
  2. 多种编程模型:支持同步、异步和响应式(Reactive Streams)编程模型,适应不同的使用场景。
  3. 自动重连和集群支持:提供自动重连机制,支持 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); } .....

使用 `spring-boot-starter-data-redis` 时,如果遇到该依赖不存在的问题,可能是由于版本管理、仓库配置或项目构建错误导致的。以下是可能的原因分析和解决方案。 ### 原因分析 1. **版本不匹配**:Spring Boot 的不同版本可能会对 `spring-boot-starter-data-redis` 的版本进行更新或调整,若手动指定版本号而未与 Spring Boot 版本兼容,可能导致依赖无法解析。 2. **Maven 仓库问题**:如果 Maven 配置中没有正确设置中央仓库或 Spring 官方仓库,会导致依赖无法下载。 3. **拼写错误或错误的 artifactId**:常见的拼写错误如 `spring-boot-starter-data-redis` 被误写为 `spring-boot-starter-redis` 或其他形式,也可能导致找不到依赖。 4. **网络问题或代理限制**:某些环境下(如企业内部网络),Maven 可能无法访问远程仓库,从而无法下载相关依赖。 ### 解决方案 1. **确认依赖配置是否正确** ```xml <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-redis</artifactId> </dependency> ``` 确保 `groupId` 和 `artifactId` 没有拼写错误,并且不要手动指定版本号,除非你明确知道要使用的版本与 Spring Boot 兼容[^3]。 2. **检查 Spring Boot 版本兼容性** 不同版本的 Spring Boot 对应不同的 `spring-boot-starter-data-redis` 版本。可以通过查看 [Spring Boot Release Notes](https://docs.spring.io/spring-boot/docs/) 来确认当前使用Spring Boot 版本是否支持该 starter。 3. **确保 Maven 配置了正确的仓库** 在 `pom.xml` 或 `settings.xml` 中添加以下仓库配置: ```xml <repositories> <repository> <id>central</id> <url>https://repo1.maven.org/maven2</url> </repository> <repository> <id>spring-releases</id> <url>https://repo.spring.io/release</url> </repository> </repositories> ``` 4. **尝试使用替代库** - **Lettuce**:`spring-boot-starter-data-redis` 默认使用 Lettuce 作为 Redis 客户端,可以直接引入 Lettuce 的依赖并手动配置连接池[^2]。 ```xml <dependency> <groupId>io.lettuce.core</groupId> <artifactId>lettuce-core</artifactId> <version>6.1.4</version> </dependency> ``` - **Redisson**:另一个流行的 Redis Java 客户端,提供了丰富的功能(如分布式锁、集合操作等)。 ```xml <dependency> <groupId>org.redisson</groupId> <artifactId>redisson-spring-boot-starter</artifactId> <version>3.16.6</version> </dependency> ``` 注意:使用 Redisson 时需确保其与 Spring Data Redis 的兼容性,避免出现 `NoClassDefFoundError` 等异常[^4]。 - **Jedis**:虽然不如 Lettuce 流行,但 Jedis 是一个轻量级的 Redis 客户端,适用于简单场景。 ```xml <dependency> <groupId>redis.clients</groupId> <artifactId>jedis</artifactId> <version>4.0.1</version> </dependency> ``` 5. **清除本地 Maven 缓存并重新下载** 有时本地 Maven 缓存损坏也会导致依赖解析失败,可以尝试删除本地缓存目录后重新构建项目: ```bash rm -rf ~/.m2/repository/org/springframework/boot/spring-boot-starter-data-redis mvn clean install ``` 6. **使用 Gradle 用户可执行以下命令** 如果使用的是 Gradle 构建工具,可以尝试以下方式添加依赖: ```groovy implementation 'org.springframework.boot:spring-boot-starter-data-redis' ``` ###
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值