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 导依赖

        
        
            com.alibaba
            druid-spring-boot-starter
            1.1.10
        

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

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

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

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

 Springboot 之整合(Druid数据库连接池、PageHelper实现分页、Redis缓存)_第1张图片

2. springboot 整合pagehelper实现分页

  2.1 导依赖

        
        
            com.github.pagehelper
            pagehelper-spring-boot-starter
            1.2.3
        
        
        
            org.springframework.boot
            spring-boot-starter-aop
        

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


spring:
  #spring 循环依赖处理
  main:
    allow-circular-references: true

#配置分页插件
pagehelper:
  reasonable: true
  supportMethodsArguments: true
  page-size-zero: true
  helper-dialect: mysql


  2.3 aop模块

   PageAspect

package com.jmh.springboot03.aop;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jmh.springboot03.utils.PageBean;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Aspect
public class PageAspect {

    /**
     *  *:返回值不限
     *  *..:包名不限
     *  *Service:以Service结尾的接口或者是类
     *  list*:以list开头的方法
     *  (..):参数及参数类型不限
     */
    @Around(value="execution(* *..*Service.list*(..))")
    public Object invoke(ProceedingJoinPoint joinPoint) throws Throwable {
        //获取目标方法的执行参数数组
        Object[] args = joinPoint.getArgs();
        //定义PageBean对象
        PageBean pageBean=null;
        //循环目标方法的参数数组
        for (Object arg : args) {
            //判断参数是否与PageBean一致
            if(arg instanceof PageBean){
                pageBean= (PageBean) arg;
                break;
            }
        }

        //判断是否是分页,并设置PageHelper的分页参数
        if (null != pageBean && pageBean.isPagination())
            PageHelper.startPage(pageBean.getPage(), pageBean.getRows());

        Object returnValue = joinPoint.proceed(args);

        if (null != pageBean && pageBean.isPagination()){
           /* //原始List分页配置
            List list= (List) returnValue;
            PageInfo pageInfo=new PageInfo<>(list);
            pageBean.setTotal(pageInfo.getTotal()+"");

             //响应分装类分页配置
            JsonResponseBody jsonResponseBody= (JsonResponseBody) returnValue;
            PageInfo pageInfo=new PageInfo((List) jsonResponseBody.getData());
            jsonResponseBody.setTotal((int) pageInfo.getTotal());*/
        }

        return returnValue;
    }
}

  2.4 utils模块

   PageBean

package com.jmh.springboot03.utils;

import java.io.Serializable;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

public class PageBean implements Serializable {

	private static final long serialVersionUID = 2422581023658455731L;

	//页码
	private int page=1;
	//每页显示记录数
	private int rows=10;
	//总记录数
	private int total=0;
	//是否分页
	private boolean isPagination=true;
	//上一次的请求路径
	private String url;
	//获取所有的请求参数
	private Map map;
	
	public PageBean() {
		super();
	}
	
	//设置请求参数
	public void setRequest(HttpServletRequest req) {
		String page=req.getParameter("page");
		String rows=req.getParameter("rows");
		String pagination=req.getParameter("pagination");
		this.setPage(page);
		this.setRows(rows);
		this.setPagination(pagination);
		this.url=req.getContextPath()+req.getServletPath();
		this.map=req.getParameterMap();
	}
	public String getUrl() {
		return url;
	}

	public void setUrl(String url) {
		this.url = url;
	}

	public Map getMap() {
		return map;
	}

	public void setMap(Map map) {
		this.map = map;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}
	
	public void setPage(String page) {
		if(null!=page&&!"".equals(page.trim()))
			this.page = Integer.parseInt(page);
	}

	public int getRows() {
		return rows;
	}

	public void setRows(int rows) {
		this.rows = rows;
	}
	
	public void setRows(String rows) {
		if(null!=rows&&!"".equals(rows.trim()))
			this.rows = Integer.parseInt(rows);
	}

	public int getTotal() {
		return total;
	}

	public void setTotal(int total) {
		this.total = total;
	}
	
	public void setTotal(String total) {
		this.total = Integer.parseInt(total);
	}

	public boolean isPagination() {
		return isPagination;
	}
	
	public void setPagination(boolean isPagination) {
		this.isPagination = isPagination;
	}
	
	public void setPagination(String isPagination) {
		if(null!=isPagination&&!"".equals(isPagination.trim()))
			this.isPagination = Boolean.parseBoolean(isPagination);
	}
	
	/**
	 * 获取分页起始标记位置
	 * @return
	 */
	public int getStartIndex() {
		//(当前页码-1)*显示记录数
		return (this.getPage()-1)*this.rows;
	}
	
	/**
	 * 末页
	 * @return
	 */
	public int getMaxPage() {
		int totalpage=this.total/this.rows;
		if(this.total%this.rows!=0)
			totalpage++;
		return totalpage;
	}
	
	/**
	 * 下一页
	 * @return
	 */
	public int getNextPage() {
		int nextPage=this.page+1;
		if(this.page>=this.getMaxPage())
			nextPage=this.getMaxPage();
		return nextPage;
	}
	
	/**
	 * 上一页
	 * @return
	 */
	public int getPreivousPage() {
		int previousPage=this.page-1;
		if(previousPage<1)
			previousPage=1;
		return previousPage;
	}

	@Override
	public String toString() {
		return "PageBean [page=" + page + ", rows=" + rows + ", total=" + total + ", isPagination=" + isPagination
				+ "]";
	}
}

  2.5 service模块

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

List listBook(Book book, PageBean pageBean);

  2.6 serviceimpl模块

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

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

 2.7  controller模块

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

3. springboot 整合Redis缓存

  3.1 导依赖

        
            org.springframework.boot
            spring-boot-starter-data-redis
        

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

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

  3.3 config模块

    RedisConfig

package com.jmh.springboot03.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Configurable;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import javax.annotation.Resource;

/**
 * @author 蒋明辉
 * @data 2022/10/1 17:08
 */
@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory){
        //实例化一个redis模板
        RedisTemplate redisTemplate=new RedisTemplate<>();
        //设置连接工厂
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //针对string类型的key和value进行序列化
        redisTemplate.setKeySerializer(new StringRedisSerializer());
        redisTemplate.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        //针对has类型的key和value进行序列化
        redisTemplate.setHashKeySerializer(new StringRedisSerializer());
        redisTemplate.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        //将上诉代码启用
        redisTemplate.afterPropertiesSet();
        return redisTemplate;

    }
}


  3.4 实现类模块

package com.jmh.springboot03.service.impl;

import com.jmh.springboot03.exception.BusinessException;
import com.jmh.springboot03.mapper.BookMapper;
import com.jmh.springboot03.model.Book;
import com.jmh.springboot03.service.IBookService;
import com.jmh.springboot03.utils.JsonResponseStatus;
import com.jmh.springboot03.utils.PageBean;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author 蒋明辉
 * @data 2022/10/1 15:07
 */
@Service
public class BookServiceImpl implements IBookService {

    /**
     * 注入书本Mapper接口
     */
    @Resource
    private BookMapper bookMapper;

    /**
     * 注入redis模板
     */
    @Resource
    private RedisTemplate redisTemplate;

    @Override
    public Book selectByPrimaryKey(Integer id) {
        Book book = bookMapper.selectByPrimaryKey(id);
        //将获取到的数据保存到redis数据库里面
        redisTemplate.opsForValue().set("book:"+book.getId(),book);
        return book;
    }


}

你可能感兴趣的:(缓存,redis,数据库,spring,boot)