• Springboot 之整合(Druid数据库连接池、PageHelper实现分页、Redis缓存)


    目录

    1. springboot 整合Druid数据库连接池

     1.1 导依赖

     1.2  修改application.properties添加druid相关配置

     1.3 启动主类 访问Druid 数据库连接池

    2. springboot 整合pagehelper实现分页

     2.1 导依赖

     2.2 修改application.properties添加druid相关配置

     2.3 aop模块

     2.4 utils模块

     2.5 service模块

     2.6 serviceimpl模块

     2.7  controller模块

    3. springboot 整合Redis缓存

      3.1 导依赖

      3.2 修改application.properties添加druid相关配置

      3.3 config模块

      3.4 实现类模块


    1. springboot 整合Druid数据库连接池

      1.1 导依赖

    1. <dependency>
    2. <groupId>com.alibabagroupId>
    3. <artifactId>druid-spring-boot-starterartifactId>
    4. <version>1.1.10version>
    5. dependency>

      1.2  修改application.properties添加druid相关配置

    1. spring:
    2. datasource:
    3. type: com.alibaba.druid.pool.DruidDataSource
    4. #配置druid 数据库连接池
    5. druid:
    6. #2.连接池配置
    7. #初始化连接池的连接数量 大小,最小,最大
    8. initial-size: 5
    9. min-idle: 5
    10. max-active: 20
    11. #配置获取连接等待超时的时间
    12. max-wait: 60000
    13. #配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
    14. time-between-eviction-runs-millis: 60000
    15. # 配置一个连接在池中最小生存的时间,单位是毫秒
    16. min-evictable-idle-time-millis: 30000
    17. validation-query: SELECT 1 FROM DUAL
    18. test-while-idle: true
    19. test-on-borrow: true
    20. test-on-return: false
    21. # 是否缓存preparedStatement,也就是PSCache 官方建议MySQL下建议关闭 个人建议如果想用SQL防火墙 建议打开
    22. pool-prepared-statements: true
    23. max-pool-prepared-statement-per-connection-size: 20
    24. # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
    25. filter:
    26. stat:
    27. merge-sql: true
    28. slow-sql-millis: 5000
    29. #3.基础监控配置
    30. web-stat-filter:
    31. enabled: true
    32. url-pattern: /*
    33. #设置不统计哪些URL
    34. exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*"
    35. session-stat-enable: true
    36. session-stat-max-count: 100
    37. stat-view-servlet:
    38. enabled: true
    39. url-pattern: /druid/*
    40. reset-enable: true
    41. #设置监控页面的登录名和密码
    42. login-username: admin
    43. login-password: admin
    44. allow: 127.0.0.1
    45. #deny: 192.168.1.100

      1.3 启动主类 访问Druid 数据库连接池

         http://localhost:8080/druid/index.html

     

    2. springboot 整合pagehelper实现分页

      2.1 导依赖

    1. <dependency>
    2. <groupId>com.github.pagehelpergroupId>
    3. <artifactId>pagehelper-spring-boot-starterartifactId>
    4. <version>1.2.3version>
    5. dependency>
    6. <dependency>
    7. <groupId>org.springframework.bootgroupId>
    8. <artifactId>spring-boot-starter-aopartifactId>
    9. dependency>

      2.2 修改application.properties添加druid相关配置

    1. spring:
    2. #spring 循环依赖处理
    3. main:
    4. allow-circular-references: true
    5. #配置分页插件
    6. pagehelper:
    7. reasonable: true
    8. supportMethodsArguments: true
    9. page-size-zero: true
    10. helper-dialect: mysql

      2.3 aop模块

       PageAspect

    1. package com.jmh.springboot03.aop;
    2. import com.github.pagehelper.PageHelper;
    3. import com.github.pagehelper.PageInfo;
    4. import com.jmh.springboot03.utils.PageBean;
    5. import lombok.extern.slf4j.Slf4j;
    6. import org.aspectj.lang.ProceedingJoinPoint;
    7. import org.aspectj.lang.annotation.Around;
    8. import org.aspectj.lang.annotation.Aspect;
    9. import org.springframework.stereotype.Component;
    10. import java.util.List;
    11. @Component
    12. @Aspect
    13. public class PageAspect {
    14. /**
    15. * *:返回值不限
    16. * *..:包名不限
    17. * *Service:以Service结尾的接口或者是类
    18. * list*:以list开头的方法
    19. * (..):参数及参数类型不限
    20. */
    21. @Around(value="execution(* *..*Service.list*(..))")
    22. public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
    23. //获取目标方法的执行参数数组
    24. Object[] args = joinPoint.getArgs();
    25. //定义PageBean对象
    26. PageBean pageBean=null;
    27. //循环目标方法的参数数组
    28. for (Object arg : args) {
    29. //判断参数是否与PageBean一致
    30. if(arg instanceof PageBean){
    31. pageBean= (PageBean) arg;
    32. break;
    33. }
    34. }
    35. //判断是否是分页,并设置PageHelper的分页参数
    36. if (null != pageBean && pageBean.isPagination())
    37. PageHelper.startPage(pageBean.getPage(), pageBean.getRows());
    38. Object returnValue = joinPoint.proceed(args);
    39. if (null != pageBean && pageBean.isPagination()){
    40. /* //原始List分页配置
    41. List list= (List) returnValue;
    42. PageInfo pageInfo=new PageInfo<>(list);
    43. pageBean.setTotal(pageInfo.getTotal()+"");
    44. //响应分装类分页配置
    45. JsonResponseBody jsonResponseBody= (JsonResponseBody) returnValue;
    46. PageInfo pageInfo=new PageInfo((List) jsonResponseBody.getData());
    47. jsonResponseBody.setTotal((int) pageInfo.getTotal());*/
    48. }
    49. return returnValue;
    50. }
    51. }

      2.4 utils模块

       PageBean

    1. package com.jmh.springboot03.utils;
    2. import java.io.Serializable;
    3. import java.util.Map;
    4. import javax.servlet.http.HttpServletRequest;
    5. public class PageBean implements Serializable {
    6. private static final long serialVersionUID = 2422581023658455731L;
    7. //页码
    8. private int page=1;
    9. //每页显示记录数
    10. private int rows=10;
    11. //总记录数
    12. private int total=0;
    13. //是否分页
    14. private boolean isPagination=true;
    15. //上一次的请求路径
    16. private String url;
    17. //获取所有的请求参数
    18. private Map map;
    19. public PageBean() {
    20. super();
    21. }
    22. //设置请求参数
    23. public void setRequest(HttpServletRequest req) {
    24. String page=req.getParameter("page");
    25. String rows=req.getParameter("rows");
    26. String pagination=req.getParameter("pagination");
    27. this.setPage(page);
    28. this.setRows(rows);
    29. this.setPagination(pagination);
    30. this.url=req.getContextPath()+req.getServletPath();
    31. this.map=req.getParameterMap();
    32. }
    33. public String getUrl() {
    34. return url;
    35. }
    36. public void setUrl(String url) {
    37. this.url = url;
    38. }
    39. public Map getMap() {
    40. return map;
    41. }
    42. public void setMap(Map map) {
    43. this.map = map;
    44. }
    45. public int getPage() {
    46. return page;
    47. }
    48. public void setPage(int page) {
    49. this.page = page;
    50. }
    51. public void setPage(String page) {
    52. if(null!=page&&!"".equals(page.trim()))
    53. this.page = Integer.parseInt(page);
    54. }
    55. public int getRows() {
    56. return rows;
    57. }
    58. public void setRows(int rows) {
    59. this.rows = rows;
    60. }
    61. public void setRows(String rows) {
    62. if(null!=rows&&!"".equals(rows.trim()))
    63. this.rows = Integer.parseInt(rows);
    64. }
    65. public int getTotal() {
    66. return total;
    67. }
    68. public void setTotal(int total) {
    69. this.total = total;
    70. }
    71. public void setTotal(String total) {
    72. this.total = Integer.parseInt(total);
    73. }
    74. public boolean isPagination() {
    75. return isPagination;
    76. }
    77. public void setPagination(boolean isPagination) {
    78. this.isPagination = isPagination;
    79. }
    80. public void setPagination(String isPagination) {
    81. if(null!=isPagination&&!"".equals(isPagination.trim()))
    82. this.isPagination = Boolean.parseBoolean(isPagination);
    83. }
    84. /**
    85. * 获取分页起始标记位置
    86. * @return
    87. */
    88. public int getStartIndex() {
    89. //(当前页码-1)*显示记录数
    90. return (this.getPage()-1)*this.rows;
    91. }
    92. /**
    93. * 末页
    94. * @return
    95. */
    96. public int getMaxPage() {
    97. int totalpage=this.total/this.rows;
    98. if(this.total%this.rows!=0)
    99. totalpage++;
    100. return totalpage;
    101. }
    102. /**
    103. * 下一页
    104. * @return
    105. */
    106. public int getNextPage() {
    107. int nextPage=this.page+1;
    108. if(this.page>=this.getMaxPage())
    109. nextPage=this.getMaxPage();
    110. return nextPage;
    111. }
    112. /**
    113. * 上一页
    114. * @return
    115. */
    116. public int getPreivousPage() {
    117. int previousPage=this.page-1;
    118. if(previousPage<1)
    119. previousPage=1;
    120. return previousPage;
    121. }
    122. @Override
    123. public String toString() {
    124. return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
    125. + "]";
    126. }
    127. }

      2.5 service模块

        PageBean 加到接口方法要实现分页的参数里即可

    List listBook(Book book, PageBean pageBean);

      2.6 serviceimpl模块

        PageBean 加到实现类接口方法要实现分页的参数里即可

    1. @Override
    2. public List listBook(Book book, PageBean pageBean) {
    3. List books = bookMapper.listBook(book);
    4. return books;
    5. }

     2.7  controller模块

    1. @RequestMapping("/listBook")
    2. public JsonResponseBody> listBook(HttpServletRequest request,Book book){
    3. //实例化PageBaen
    4. PageBean pageBean=new PageBean();
    5. //设置打开分页
    6. pageBean.setRequest(request);
    7. List books = bookService.listBook(book,pageBean);
    8. return new JsonResponseBody<>(books,pageBean.getTotal());
    9. }

    3. springboot 整合Redis缓存

      3.1 导依赖

    1. <dependency>
    2. <groupId>org.springframework.bootgroupId>
    3. <artifactId>spring-boot-starter-data-redisartifactId>
    4. dependency>

      3.2 修改application.properties添加druid相关配置

    1. spring:
    2. #配置redis
    3. redis:
    4. host: 127.0.0.1 //ip地址
    5. database: 0 //redis 一共有16个数据库 参数代码数据库下标
    6. password: 1234 //密码 没有密码忽略
    7. port: 6379 //端口号

      3.3 config模块

        RedisConfig

    1. package com.jmh.springboot03.config;
    2. import org.springframework.beans.factory.annotation.Autowired;
    3. import org.springframework.beans.factory.annotation.Configurable;
    4. import org.springframework.context.annotation.Bean;
    5. import org.springframework.context.annotation.Configuration;
    6. import org.springframework.data.redis.connection.RedisConnectionFactory;
    7. import org.springframework.data.redis.core.RedisTemplate;
    8. import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
    9. import org.springframework.data.redis.serializer.StringRedisSerializer;
    10. import javax.annotation.Resource;
    11. /**
    12. * @author 蒋明辉
    13. * @data 2022/10/1 17:08
    14. */
    15. @Configuration
    16. public class RedisConfig {
    17. @Bean
    18. public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
    19. //实例化一个redis模板
    20. RedisTemplate redisTemplate=new RedisTemplate<>();
    21. //设置连接工厂
    22. redisTemplate.setConnectionFactory(redisConnectionFactory);
    23. //针对string类型的key和value进行序列化
    24. redisTemplate.setKeySerializer(new StringRedisSerializer());
    25. redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
    26. //针对has类型的key和value进行序列化
    27. redisTemplate.setHashKeySerializer(new StringRedisSerializer());
    28. redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
    29. //将上诉代码启用
    30. redisTemplate.afterPropertiesSet();
    31. return redisTemplate;
    32. }
    33. }

      3.4 实现类模块

    1. package com.jmh.springboot03.service.impl;
    2. import com.jmh.springboot03.exception.BusinessException;
    3. import com.jmh.springboot03.mapper.BookMapper;
    4. import com.jmh.springboot03.model.Book;
    5. import com.jmh.springboot03.service.IBookService;
    6. import com.jmh.springboot03.utils.JsonResponseStatus;
    7. import com.jmh.springboot03.utils.PageBean;
    8. import org.springframework.data.redis.core.RedisTemplate;
    9. import org.springframework.stereotype.Service;
    10. import javax.annotation.Resource;
    11. import java.util.List;
    12. /**
    13. * @author 蒋明辉
    14. * @data 2022/10/1 15:07
    15. */
    16. @Service
    17. public class BookServiceImpl implements IBookService {
    18. /**
    19. * 注入书本Mapper接口
    20. */
    21. @Resource
    22. private BookMapper bookMapper;
    23. /**
    24. * 注入redis模板
    25. */
    26. @Resource
    27. private RedisTemplate redisTemplate;
    28. @Override
    29. public Book selectByPrimaryKey(Integer id) {
    30. Book book = bookMapper.selectByPrimaryKey(id);
    31. //将获取到的数据保存到redis数据库里面
    32. redisTemplate.opsForValue().set("book:"+book.getId(),book);
    33. return book;
    34. }
    35. }

  • 相关阅读:
    Rust逆向学习 (2)
    数据结构:KMP算法的原理图解和代码解析
    React-Router link方式跳转
    One-YOLOv5 v1.2.0发布:支持分类、检测、实例分割
    Android 逆向入门保姆级教程
    likeadmin和fastapi的bug
    move_base代码解析(一)MoveBase::executeCb
    聊一聊损失函数
    一分钟带你了解音视频开发进阶(先收藏了)
    flask旅游景点推荐
  • 原文地址:https://blog.csdn.net/m0_63300795/article/details/127135897