第五章补充
- IDE的选择
- IDEA——插件消耗配置,功能更多
- SpringToolSuite4——功能较少,流畅
- 打包
- Why:
- 以前是直接访问数据库获取数据,如果并发多的时候会出现很多问题。对数据库压力大
- What:
- 先读取缓存
- 有则获取缓存的资源数据
- 无则读取数据库
- 先读取缓存
How:
- 先建立数据库(首先需要能拿到数据)
- 用以前的springbootdata.sql文件-导入数据库
- 引入相关依赖()
- JPA
- Mysql(数据库)
- Web(用于测试返回结果)
编写实体类P115-116
@Data@Entity(name = "t_comment") //设置ORM实体类,并指定映射的表名public class Comment{@Id //表明映射对应的主键id@GeneratedValue(strategy = GenerationType.IDENTITY) //设置主键自增策略private Integer id;private String content;private String author;//指定映射的表字段名,因为数据库里对应的字段名为a_id,而此处定义的属性名为aId,两者名字不同,需要将此处的aId标注为数据库对应的字段a_id才能建立起连接@Column(name = "a_id")private Integer aId;//下方通过lombok引入和补丁安装,用@data省略get、set方法//省略toString()方法
引入Lombok,上Project Lombok官网打补丁在sts安装路径下(他就可以找到sts的路径),之后可用@data注解替换get、set方法
repository(Dao层)下编写Repository接口文件(用于操作Comment实体,这层是用于数据访问-查询、更新、删除、修改),
Controller的作用的接收浏览器的请求,将请求的数据转换成DTO(Data Transfer Object),DTO绑定到Controller方法参数里面,再传递到Service,将DTO作为Service类里的一个方法里的参数存进去,到达Service后通过BeanCopir
- 先建立数据库(首先需要能拿到数据)
public interface CommentRepository extends JpaRepository<Comment,Integer>{//JpaRepository<T,ID>——T是泛型,可以传入各种,//继承了JpaRepository就有了它的所有方法和属性。我们只用编写额外的//根据评论id修改评论作者author@Transactional //写在Dao层不是特别正确,通常是在Service里。用于事务一致化@Modifying //该注解用于标记以下方法可修改数据库内的数据@Query("UPDATE t_comment c SET c.author = ?1 WHERE c.id = ?2")//查询注解,根据找到第二个id再找到对应的author,修改author的内容。?1为下面方法的第一个参数-即comment方法的接收参数author,?2为下面方法的第二个参数-即comment的接收参数idpublic int updateComment(String author , Integer id);}
- Service层下编写Service实体类P117(该层是用于业务逻辑的实现,服务) ```java @Service //Service层注解,各层有各层注解,便于sts初始化时扫描部署 public class CommentService{ @Autowired //相当于new了 private CommentRepository commentRepository;
//调用repository层编写的接口继承的父级的findById方法//接收的comment_id是controller从浏览器的参数里获取的public Comment findById(int comment_id){//optional是一个类型,可以接收所有类型。我们用Repository层的commentRepository的findById方法用接收的id去数据库找对应数据,存到optionalOptional<Comment> optional = commentRepository.findById(comment_id);//如果数据库里存在该条数据就返回,否则返回nullif(optional.isPresent()){return optional.get();}return null;}//更新直接调用Dao层-即Repository层编写的updateComment方法,接收author和id参数public Comment updateComment(Comment comment){commentRepository.updateComment(comment.getAuthor(),comment.getaId());return comment;}//deleteById也来自JPA的父级CrudRepository类public void deleteComment(int comment_id){commentRepository.deleteById(comment_id);}
}
- 在Controller层编写CommentController实体类用于Comment的访问控制(该层注入Service层的内容)```javapackage com.example.demo.Controller;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.*;import com.example.demo.Domain.Comment;import com.example.demo.Service.CommentService;@RestControllerpublic class CommentController{@Autowired // Autowired注解相当于new出一个对象private CommentService commentService; //讲Service作为一种属性存在@GetMapping("/get/{id}") //通过url的占位符能力绑定到注解所标示的方法上,与@PathVariable的参数对应//@PathVariable路径变量对应上方mapping获取的id参数,接收此参数,并设该参数为int型,命名为comment_id。//findById方法是通过id查找数据的方法,接收id,返回数据。接收的是Comment,返回也需Comment类型。public Comment findById(@PathVariable("id") int comment_id) {Comment comment = commentService.findById(comment_id);return comment;}@GetMapping("update/{id}/{author}")public Comment updateComment(@PathVariable("id") int comment_id,@PathVariable("author") String author) {Comment comment = commentService.findById(comment_id);comment.setAuthor(author);Comment updateComment = commentService.updateComment(comment);return updateComment;}@GetMapping("/delete/{id}")public void deleteComment(@PathVariable("id") int comment_id){commentService.deleteComment(comment_id);}}
application.properties里修改数据库连接配置
# Mysql数据库连接配置spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTCspring.datasource.username=rootspring.datasource.password=root#显示实用JPA进行数据库查询的SQL语句spring.jpa.show-sql=true#服务器端口设置server.port=8083
启动SpringBootApp
- 报错检测-看控制台最前面的报错
- 如果started …in …seconds说明启动成功
- 浏览器输入localhost:端口号/get/{id}
- 前面是没加入缓存的情况,现在加入缓存,提升并发情况下的响应速度
- how
- Application入口程序上添加@EnableCaching
- //开启SpringBoot基于注解的缓存管理支持
- 在Service类的findById方法上添加@Cacheable注解用于缓存
- @Cacheable(cacheNames = “comment”) //为缓存添加空间存储comment
- 项目启动,浏览器测试,显示不管刷新多少次控制台显示只执行了一次操作,说明项目的默认缓存支持已经生效-simple
- pom.xml引入Redis依赖
- Application入口程序上添加@EnableCaching
- 在上述的缓存管理实现中没有添加任何缓存管理组件,只是运用了默认的Simple缓存组件。开启缓存管理后SpringBoot会自动按缓存组件列表去顺序查找有效的缓存组件进行缓存管理,如果没有任何缓存组件则默认使用最后一个Simple缓存组件进行管理。该组件使用内存中的ConcurrentHashMap进行缓存存储。
基于注解的Redis缓存实现
即在默认缓存管理的基础上引入Redis缓存组件,使用基于注解的方式实现SpringBoot整合Redis缓存。
- how
- pom.xml中添加Spring Data Redis依赖启动器(maven仓库搜索)
```xml
org.springframework.boot spring-boot-starter-data-redis
2. Redis服务安装和开启,以及STS内Redis服务连接配置> 使用类似Redis的第三方缓存组件进行缓存管理时缓存数据不是像SpringBoot默认缓存管理那样存储在内存中,而是需要预先搭建类似Redis服务的数据仓库进行缓存存储。```properties#Redis 服务地址=本机端口spring.redis.host = 127.0.0.1#Redis 服务器连接端口spring.redis.port = 6379#Redis 服务器连接密码(默认为空)spring.redis.password =
redis可在cmd进入命令行窗口输入redis-cli回车进入,如果返回本机端口和服务连接端口说明成功。 redis的相关命令可以在菜鸟教程查看 https://www.runoob.com/redis/redis-commands.html
通过keys *可以获取所有键名 get 键名可以获取对应键名下的数据,通过16进制的哈希格式显示
有关缓存相关注解的顺序
@Cacheable 先查询缓存再查询数据库
@CachePut 先更新数据库再更新缓存
@CacheEvict 先删除数据库再删除缓存
了解
@caching
@CacheConfig注解写在Service类上,可以简便代码编写,就不用去敲三种Cache了,方便统筹管理缓存
通过keys *可以获取所有键名
get 键名可以获取对应键名下的数据,通过16进制的哈希格式显示