第五章补充

  • IDE的选择
    • IDEA——插件消耗配置,功能更多
    • SpringToolSuite4——功能较少,流畅
  • 打包
    • war包——已过时
    • jar包
      • sts创建项目的时候已经存在打包部署


        第六章-SpringBoot缓存管理

  • Why:
    • 以前是直接访问数据库获取数据,如果并发多的时候会出现很多问题。对数据库压力大
  • What:
    • 先读取缓存
      • 有则获取缓存的资源数据
      • 无则读取数据库
  • How:

    • 先建立数据库(首先需要能拿到数据)
      • 用以前的springbootdata.sql文件-导入数据库
    • 引入相关依赖()
      • JPA
      • Mysql(数据库)
      • Web(用于测试返回结果)
    • 编写实体类P115-116

      1. @Data
      2. @Entity(name = "t_comment") //设置ORM实体类,并指定映射的表名
      3. public class Comment{
      4. @Id //表明映射对应的主键id
      5. @GeneratedValue(strategy = GenerationType.IDENTITY) //设置主键自增策略
      6. private Integer id;
      7. private String content;
      8. private String author;
      9. //指定映射的表字段名,因为数据库里对应的字段名为a_id,而此处定义的属性名为aId,两者名字不同,需要将此处的aId标注为数据库对应的字段a_id才能建立起连接
      10. @Column(name = "a_id")
      11. private Integer aId;
      12. //下方通过lombok引入和补丁安装,用@data省略get、set方法
      13. //省略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

  1. public interface CommentRepository extends JpaRepository<Comment,Integer>{
  2. //JpaRepository<T,ID>——T是泛型,可以传入各种,
  3. //继承了JpaRepository就有了它的所有方法和属性。我们只用编写额外的
  4. //根据评论id修改评论作者author
  5. @Transactional //写在Dao层不是特别正确,通常是在Service里。用于事务一致化
  6. @Modifying //该注解用于标记以下方法可修改数据库内的数据
  7. @Query("UPDATE t_comment c SET c.author = ?1 WHERE c.id = ?2")
  8. //查询注解,根据找到第二个id再找到对应的author,修改author的内容。?1为下面方法的第一个参数-即comment方法的接收参数author,?2为下面方法的第二个参数-即comment的接收参数id
  9. public int updateComment(String author , Integer id);
  10. }
  • Service层下编写Service实体类P117(该层是用于业务逻辑的实现,服务) ```java @Service //Service层注解,各层有各层注解,便于sts初始化时扫描部署 public class CommentService{ @Autowired //相当于new了 private CommentRepository commentRepository;
  1. //调用repository层编写的接口继承的父级的findById方法
  2. //接收的comment_id是controller从浏览器的参数里获取的
  3. public Comment findById(int comment_id){
  4. //optional是一个类型,可以接收所有类型。我们用Repository层的commentRepository的findById方法用接收的id去数据库找对应数据,存到optional
  5. Optional<Comment> optional = commentRepository.findById(comment_id);
  6. //如果数据库里存在该条数据就返回,否则返回null
  7. if(optional.isPresent()){
  8. return optional.get();
  9. }
  10. return null;
  11. }
  12. //更新直接调用Dao层-即Repository层编写的updateComment方法,接收author和id参数
  13. public Comment updateComment(Comment comment){
  14. commentRepository.updateComment(comment.getAuthor(),comment.getaId());
  15. return comment;
  16. }
  17. //deleteById也来自JPA的父级CrudRepository类
  18. public void deleteComment(int comment_id){
  19. commentRepository.deleteById(comment_id);
  20. }

}

  1. - Controller层编写CommentController实体类用于Comment的访问控制(该层注入Service层的内容)
  2. ```java
  3. package com.example.demo.Controller;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.web.bind.annotation.*;
  6. import com.example.demo.Domain.Comment;
  7. import com.example.demo.Service.CommentService;
  8. @RestController
  9. public class CommentController{
  10. @Autowired // Autowired注解相当于new出一个对象
  11. private CommentService commentService; //讲Service作为一种属性存在
  12. @GetMapping("/get/{id}") //通过url的占位符能力绑定到注解所标示的方法上,与@PathVariable的参数对应
  13. //@PathVariable路径变量对应上方mapping获取的id参数,接收此参数,并设该参数为int型,命名为comment_id。
  14. //findById方法是通过id查找数据的方法,接收id,返回数据。接收的是Comment,返回也需Comment类型。
  15. public Comment findById(@PathVariable("id") int comment_id) {
  16. Comment comment = commentService.findById(comment_id);
  17. return comment;
  18. }
  19. @GetMapping("update/{id}/{author}")
  20. public Comment updateComment(@PathVariable("id") int comment_id,
  21. @PathVariable("author") String author) {
  22. Comment comment = commentService.findById(comment_id);
  23. comment.setAuthor(author);
  24. Comment updateComment = commentService.updateComment(comment);
  25. return updateComment;
  26. }
  27. @GetMapping("/delete/{id}")
  28. public void deleteComment(@PathVariable("id") int comment_id){
  29. commentService.deleteComment(comment_id);
  30. }
  31. }
  • application.properties里修改数据库连接配置

    1. # Mysql数据库连接配置
    2. spring.datasource.url=jdbc:mysql://localhost:3306/springbootdata?serverTimezone=UTC
    3. spring.datasource.username=root
    4. spring.datasource.password=root
    5. #显示实用JPA进行数据库查询的SQL语句
    6. spring.jpa.show-sql=true
    7. #服务器端口设置
    8. 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依赖
    • 在上述的缓存管理实现中没有添加任何缓存管理组件,只是运用了默认的Simple缓存组件。开启缓存管理后SpringBoot会自动按缓存组件列表去顺序查找有效的缓存组件进行缓存管理,如果没有任何缓存组件则默认使用最后一个Simple缓存组件进行管理。该组件使用内存中的ConcurrentHashMap进行缓存存储。

      基于注解的Redis缓存实现

      即在默认缓存管理的基础上引入Redis缓存组件,使用基于注解的方式实现SpringBoot整合Redis缓存。
  1. pom.xml中添加Spring Data Redis依赖启动器(maven仓库搜索) ```xml org.springframework.boot spring-boot-starter-data-redis
  1. 2. Redis服务安装和开启,以及STSRedis服务连接配置
  2. > 使用类似Redis的第三方缓存组件进行缓存管理时缓存数据不是像SpringBoot默认缓存管理那样存储在内存中,而是需要预先搭建类似Redis服务的数据仓库进行缓存存储。
  3. ```properties
  4. #Redis 服务地址=本机端口
  5. spring.redis.host = 127.0.0.1
  6. #Redis 服务器连接端口
  7. spring.redis.port = 6379
  8. #Redis 服务器连接密码(默认为空)
  9. spring.redis.password =

redis可在cmd进入命令行窗口输入redis-cli回车进入,如果返回本机端口和服务连接端口说明成功。 redis的相关命令可以在菜鸟教程查看 https://www.runoob.com/redis/redis-commands.html image.png 通过keys *可以获取所有键名 get 键名可以获取对应键名下的数据,通过16进制的哈希格式显示

有关缓存相关注解的顺序
@Cacheable 先查询缓存再查询数据库
@CachePut 先更新数据库再更新缓存
@CacheEvict 先删除数据库再删除缓存

了解
@caching
@CacheConfig注解写在Service类上,可以简便代码编写,就不用去敲三种Cache了,方便统筹管理缓存