开发者学堂课程【微服务+全栈在线教育实战项目演练(SpringCloud Alibaba+SpringBoot):首页数据显示-添加 redis 缓存(1)】学习笔记,与课程紧密联系,让用户快速学习知识。
课程地址:https://developer.aliyun.com/learning/course/667/detail/11435
首页数据显示-添加 redis 缓存(1)
内容简介
一、Spring Boot 缓存注解
二、Common 的 pum 文件引入
现在用 redis 把首页数据添加到页面中去
首先需要添加依赖
<
!--redis-->
< dependency >
<groupId>org. springframework . boot</groupId>
<artifact Id>spring-boot-starger-data-redis</ artifactld >
</ dependency >
<1--spring2.X
集成redis所需common-pool2-->
cdependency >
<groupsd>org. apache/commons</groupId>
=kartifact Id>commons-pool2</artifact Id)
<version>2.6.0</version>
</ dependency >
有了依赖之后,我们可以在里边创建一个 cinfiguration,缓存一个配置类,代码就是两个插件,一个是做缓存的一个是做缓存管理的,里边主要用到 redis,用注解实现
在接口中添加redis缓存
由于首页数据变化不是很频繁,而且首页访问量相对较大,所以我们有必要把首页接口数据缕存到 redis 缕存中,减少数据库压力和提高访问速度。
改造 service-cms 横块首页 banner 接口,首页课程与讲师接口类似
一、Spring Boot 缓存注解
1、缓存@Cacheable
根据方法对其返回结果进行缓弃,下次请求时,如果缓弃存在,则直接读取缓存数据返回;如果缓存不存在,则执行方法,并把返回的结果存入缓存中,一般用在香询方法上
第一步,创建redis配置类,写道 common 里面
(1)引入 springboot 整合 redis 相关依赖
(2)创建 redis 缓存配置类,配置插件
<!-redis-->
<dependency >
<groupId>org. springframework . boot</groupId>
( artifactld spring-boot-starter-data-redis(/artifactl/ dependency )
<!--spring2.X
集成redis所需common-pool2->
<dependency >
<group Id>org=apache/commons/groupId
</artifactId >commons=poo12</ artifactld >
<version>2.6.0</version>
这个依赖经常会下载失败,直接复制就可以了。
二、Common 的 pum 文件引入
package com atguigu, servicebase ;
Importorg, springframework ,cache, annotation , CachingConfigurerSupport
Importorgspringframework
, cache. annotation , EnableCaching .
importorg.springframework. context, annotation . Configuration .
@EnableCaching
//开启缓存
@ Configuration
//配置类
public class RedisConfig extends CachingConfigurerSupport
引入两个插件,里边不需要改什么,直接复制即可,限制时间,超过600数据就没有了。
Banner 找到方法
//查询所有 banner
@ GetNapping (" getA1lBanner ")
pxblic RgetAllBanner ()(
List<CrmBanner) list= bannerService . select AllBanner().
return R. ok(). data("list", list);
1、缓存@Cacheable
根据方法对其返回结果进行缓弃,下次请求时,如果缓弃存在,则直接读取缓存数据返回;如果缓存不存在,则执行方法,并把返回的结果存入缓存中,一般用在香询方法上。
三个注解:
Value 缓存名,必填,它指定了你的缓存存放在哪块命名空间
cacheNames 与 value 差不多,二选一即可
Key 可选属性,可以使用 SpEL 标签自定义缓存的 key
可以把注解加到方法上,方法上加属性控制基本操作
第二步
在查询所有 banner 的方法上面添加缓存注解@Cacheable
第一次查询,首先查询数据库,把数据库查询数据返回,并且返回数据到缓存中
第二次查询,查询缓存,发现缓存有数据,直接返回
如图所示
2、缓存@CachePut
使用该注解标志的方法,每次都会执行,并将结果存入指定的缓存中。其他方法可以直接从响应的缓存中读取暖存数据,而不需要再去查询数据库。一般用在新增方法上。
三个注解:
Value 缓存名,必填,它指定了你的缓存存放在哪块命名空间
cacheNames 与 value 差不多,二选一即可
Key 可选属性,可以使用 SpEL 标签自定义缓存的 key
3、缓存@ CacheEvict
使用该注解标志的方法,会清空指定的缓存。一般用在更新或者删除方法上