基于注解的Redis缓存实现

5.2.2 基于注解的Redis缓存实现


在Spring Boot默认缓存管理的基础上引入Redis缓存组件,使用基于注解的方式讲解Spring Boot整合Redis缓存的具体实现

(1)添加Spring Data Redis依赖启动器。在pom.xml文件中添加Spring Data Redis依赖启动器


<dependency>

       <groupId>org.springframework.boot</groupId>

       <artifactId>spring-boot-starter-data-redis</artifactId>

</dependency>

当我们添加进redis相关的启动器之后,
SpringBoot会使用RedisCacheConfigratioin当做生效的自动配置类进行缓存相关的自动装配,容器中使用的缓存管理器是

RedisCacheManager, 这个缓存管理器创建的Cache为 RedisCache, 进而操控redis进行数据的缓存

(2)Redis服务连接配置


# Redis服务地址

spring.redis.host=127.0.0.1

# Redis服务器连接端口

spring.redis.port=6379

# Redis服务器连接密码(默认为空)

spring.redis.password=

(3)对CommentService类中的方法进行修改使用@Cacheable、@CachePut、@CacheEvict三个注解定制缓存管理,分别进行缓存存储、缓存更新和缓存删除的演示

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,下面是对这三个实验的总结: 1. Spring Boot 整合 Redis 的基本步骤: Spring Boot 提供了对 Redis 的自动配置支持,可以通过配置文件来配置 Redis 连接参数,然后通过@Autowired注解注入 RedisTemplate 来使用 RedisSpring Boot 整合 Redis 的基本步骤如下: 1)在pom.xml文件中添加 redis 依赖:spring-boot-starter-data-redis。 2)在 application.properties 文件中添加 Redis 连接参数配置,例如: spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= 3)在 Java 代码中使用 RedisTemplate 操作 Redis,例如: @Autowired private RedisTemplate<String, Object> redisTemplate; ValueOperations<String, Object> operations = redisTemplate.opsForValue(); operations.set("key", "value"); Object value = operations.get("key"); 2. Redis 第三方技术的应用: 除了 Redis 本身提供的数据结构和操作命令,还有许多第三方技术可以应用在 Redis 中,例如: 1)Redisson:基于 Redis 的分布式 Java 对象和服务框架,提供了分布式锁、分布式集合等功能。 2)Lettuce:高性能的 Redis 客户端,提供了异步、响应式等多种操作方式,支持 Redis Sentinel 和 Redis Cluster。 3)Jedis:RedisJava 客户端库,提供了 Redis 的基本操作命令。 4)Spring Data RedisSpring 提供的 Redis 访问框架,提供了对 Redis 的基本操作和缓存支持。 3. 基于注解Redis 缓存实现Spring Boot 提供了基于注解Redis 缓存实现,可以将方法的返回值缓存Redis 中,下次调用该方法时,如果缓存中存在对应的数据,则直接返回缓存数据,不再执行方法体逻辑。基于注解Redis 缓存实现的基本步骤如下: 1)在 pom.xml 文件中添加 Redis 和 Cache 依赖:spring-boot-starter-data-redisspring-boot-starter-cache。 2)在 Java 代码中添加 @EnableCaching 注解启用缓存功能。 3)在方法上添加 @Cacheable 注解指定方法返回值需要缓存Redis 中,例如: @Cacheable(value = "userCache", key = "#id") public User getUserById(String id) { return userDao.getUserById(id); } 4)在 application.properties 文件中配置 Redis 连接参数和缓存配置,例如: spring.redis.host=localhost spring.redis.port=6379 spring.redis.password= spring.cache.type=redis 通过使用基于注解Redis 缓存实现,可以提高应用程序的性能和响应速度,减少对数据库的访问,提高系统的并发能力。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值