SpringBoot+SpringCloud+vue+Element开发项目——集成Druid数据源

添加依赖

pom.xml

<!--druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.10</version>
</dependency>

添加配置文件

application.yml

server:
  port: 8001
spring:
  datasource:
    name: druidDataSource
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      driver-class-name: com.mysql.jdbc.Driver
      url: jdbc:mysql://localhost:3306/mdh?useUnicode=true&zeroDateTimeBehavior=convertToNull&autoReconnect=true&characterEncoding=utf-8
      username: root
      password: root
      filters: stat,wall,log4j,config
      max-active: 100
      initial-size: 1
      max-wait: 60000
      min-idle: 1
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 300000
      validation-query: select ‘x‘
      test-while-idle: true
      test-on-borrow: false
      test-on-return: false
      pool-prepared-statements: true
      max-open-prepared-statements: 50
      max-pool-prepared-statement-per-connection-size: 20

自定义属性配置,添加配置类

DruidDataSourceProperties.java

/**
 * 数据源属性
 */
@ConfigurationProperties(prefix = "spring.datasource.druid")
public class DruidDataSourceProperties {

   // jdbc
   private String driverClassName;
   private String url;
   private String username;
   private String password;
   // jdbc connection pool
   private int initialSize;
   private int minIdle;
   private int maxActive = 100;
   private long maxWait;
   private long timeBetweenEvictionRunsMillis;
   private long minEvictableIdleTimeMillis;
   private String validationQuery;
   private boolean testWhileIdle;
   private boolean testOnBorrow;
   private boolean testOnReturn;
   private boolean poolPreparedStatements;
   private int maxPoolPreparedStatementPerConnectionSize;
   // filter
   private String filters;

   public int getInitialSize() {
      return initialSize;
   }

   public void setInitialSize(int initialSize) {
      this.initialSize = initialSize;
   }

   public int getMinIdle() {
      return minIdle;
   }

   public void setMinIdle(int minIdle) {
      this.minIdle = minIdle;
   }

   public int getMaxActive() {
      return maxActive;
   }

   public void setMaxActive(int maxActive) {
      this.maxActive = maxActive;
   }

   public long getMaxWait() {
      return maxWait;
   }

   public void setMaxWait(long maxWait) {
      this.maxWait = maxWait;
   }

   public long getTimeBetweenEvictionRunsMillis() {
      return timeBetweenEvictionRunsMillis;
   }

   public void setTimeBetweenEvictionRunsMillis(long timeBetweenEvictionRunsMillis) {
      this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
   }

   public long getMinEvictableIdleTimeMillis() {
      return minEvictableIdleTimeMillis;
   }

   public void setMinEvictableIdleTimeMillis(long minEvictableIdleTimeMillis) {
      this.minEvictableIdleTimeMillis = minEvictableIdleTimeMillis;
   }

   public String getValidationQuery() {
      return validationQuery;
   }

   public void setValidationQuery(String validationQuery) {
      this.validationQuery = validationQuery;
   }

   public boolean isTestWhileIdle() {
      return testWhileIdle;
   }

   public void setTestWhileIdle(boolean testWhileIdle) {
      this.testWhileIdle = testWhileIdle;
   }

   public boolean isTestOnBorrow() {
      return testOnBorrow;
   }

   public void setTestOnBorrow(boolean testOnBorrow) {
      this.testOnBorrow = testOnBorrow;
   }

   public boolean isTestOnReturn() {
      return testOnReturn;
   }

   public void setTestOnReturn(boolean testOnReturn) {
      this.testOnReturn = testOnReturn;
   }

   public boolean isPoolPreparedStatements() {
      return poolPreparedStatements;
   }

   public void setPoolPreparedStatements(boolean poolPreparedStatements) {
      this.poolPreparedStatements = poolPreparedStatements;
   }

   public int getMaxPoolPreparedStatementPerConnectionSize() {
      return maxPoolPreparedStatementPerConnectionSize;
   }

   public void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize) {
      this.maxPoolPreparedStatementPerConnectionSize = maxPoolPreparedStatementPerConnectionSize;
   }

   public String getFilters() {
      return filters;
   }

   public void setFilters(String filters) {
      this.filters = filters;
   }

   public String getDriverClassName() {
      return driverClassName;
   }

   public void setDriverClassName(String driverClassName) {
      this.driverClassName = driverClassName;
   }

   public String getUrl() {
      return url;
   }

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

   public String getUsername() {
      return username;
   }

   public void setUsername(String username) {
      this.username = username;
   }

   public String getPassword() {
      return password;
   }

   public void setPassword(String password) {
      this.password = password;
   }

在config包下创建DruidConfig配置类

DruidConfig.java

/**
 * Druid数据源配置
 */
@Configuration
@EnableConfigurationProperties({DruidDataSourceProperties.class})
public class DruidConfig {
    @Autowired
    private DruidDataSourceProperties properties;

    @Bean
    @ConditionalOnMissingBean
    public DataSource druidDataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(properties.getDriverClassName());
        druidDataSource.setUrl(properties.getUrl());
        druidDataSource.setUsername(properties.getUsername());
        druidDataSource.setPassword(properties.getPassword());
        druidDataSource.setInitialSize(properties.getInitialSize());
        druidDataSource.setMinIdle(properties.getMinIdle());
        druidDataSource.setMaxActive(properties.getMaxActive());
        druidDataSource.setMaxWait(properties.getMaxWait());
        druidDataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
        druidDataSource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
        druidDataSource.setValidationQuery(properties.getValidationQuery());
        druidDataSource.setTestWhileIdle(properties.isTestWhileIdle());
        druidDataSource.setTestOnBorrow(properties.isTestOnBorrow());
        druidDataSource.setTestOnReturn(properties.isTestOnReturn());
        druidDataSource.setPoolPreparedStatements(properties.isPoolPreparedStatements());
        druidDataSource.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize());

        try {
            druidDataSource.setFilters(properties.getFilters());
            druidDataSource.init();
        } catch (SQLException e) {
            e.printStackTrace();
        }

        return druidDataSource;
    }

    /**
     * 注册Servlet信息, 配置监控视图
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public ServletRegistrationBean<Servlet> druidServlet() {
        ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<Servlet>(new StatViewServlet(), "/druid/*");

        //白名单:
//        servletRegistrationBean.addInitParameter("allow","127.0.0.1,139.196.87.48");
        //IP黑名单 (存在共同时,deny优先于allow) : 如果满足deny的话提示:Sorry, you are not permitted to view this page.
        servletRegistrationBean.addInitParameter("deny","192.168.1.119");
        //登录查看信息的账号密码, 用于登录Druid监控后台
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin");
        //是否能够重置数据.
        servletRegistrationBean.addInitParameter("resetEnable", "true");
        return servletRegistrationBean;

    }

    /**
     * 注册Filter信息, 监控拦截器
     *
     * @return
     */
    @Bean
    @ConditionalOnMissingBean
    public FilterRegistrationBean<Filter> filterRegistrationBean() {
        FilterRegistrationBean<Filter> filterRegistrationBean = new FilterRegistrationBean<Filter>();
        filterRegistrationBean.setFilter(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }
}

添加log4j依赖

pom.xml

<!--log4j-->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

添加log4j配置

log4j.properties

### set log levels ###
log4j.rootLogger = INFO,DEBUG, console, infoFile, errorFile ,debugfile,mail
LocationInfo=true    

log4j.appender.console = org.apache.log4j.ConsoleAppender
log4j.appender.console.Target = System.out
log4j.appender.console.layout = org.apache.log4j.PatternLayout 

log4j.appender.console.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m   %x %n 

log4j.appender.infoFile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.infoFile.Threshold = INFO
log4j.appender.infoFile.File = D:/logs/log
log4j.appender.infoFile.DatePattern = ‘.‘yyyy-MM-dd‘.log‘
log4j.appender.infoFile.Append=true
log4j.appender.infoFile.layout = org.apache.log4j.PatternLayout
log4j.appender.infoFile.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m  %x %n 

log4j.appender.errorFile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.errorFile.Threshold = ERROR
log4j.appender.errorFile.File = D:/logs/error
log4j.appender.errorFile.DatePattern = ‘.‘yyyy-MM-dd‘.log‘
log4j.appender.errorFile.Append=true
log4j.appender.errorFile.layout = org.apache.log4j.PatternLayout
log4j.appender.errorFile.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m  %x %n

log4j.appender.debugfile = org.apache.log4j.DailyRollingFileAppender
log4j.appender.debugfile.Threshold = DEBUG
log4j.appender.debugfile.File = D:/logs/debug
log4j.appender.debugfile.DatePattern = ‘.‘yyyy-MM-dd‘.log‘
log4j.appender.debugfile.Append=true
log4j.appender.debugfile.layout = org.apache.log4j.PatternLayout
log4j.appender.debugfile.layout.ConversionPattern =[%d{yyyy-MM-dd HH:mm:ss,SSS}]-[%p]:%m  %x %n

启动应用 访问http://localhost:8001/druid/login.html   用户名:admin   密码:admin

跨域请求CORS实现

新建一个CORS配置类 实现WebMvcConfigurer接口

CorsConfig.java

@Configuration
public class CorsConfig implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry){
        registry.addMapping("/**")   //允许跨域访问的路径
                .allowedOrigins("*")   //允许跨域访问的源
                .allowedMethods("","","","","")  //允许请求的方法
                .maxAge(168000)   //预检间隔时间
                .allowedHeaders("*")  //允许头部设置
                .allowCredentials(true);  //是否发送cookie
    }
}

原文地址:https://www.cnblogs.com/Jansens520/p/11830706.html

时间: 2024-10-12 23:00:02

SpringBoot+SpringCloud+vue+Element开发项目——集成Druid数据源的相关文章

SpringBoot+SpringCloud+vue+Element开发项目——数据库设计

1.用户表(sys_user) CREATE TABLE `sys_user` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '编号', `name` varchar(50) NOT NULL COMMENT '用户名', `nick_name` varchar(150) DEFAULT NULL COMMENT '昵称', `avatar` varchar(150) DEFAULT NULL COMMENT '头像', `password`

微服务架构【SpringBoot+SpringCloud+VUE】二 || 项目架构简介

目录 1.概述 2.开发环境 3.部署环境 4.项目管理 5.后端主要技术栈 6.前端主要技术栈 7.项目开发环境服务规划 8.学习交流QQ群[883210148] 1.概述 本项目是一个基于SpringBoot2.x+vue2.X的分布式微服务架构项目,项目会不断进行迭代更新.该项目后端利用SpringCloudAlibaba微服务架构解决方案进行重构.项目前端利用vue框架开发,页面展示主要为pc端和手机端(微信公众号). 2.开发环境 开发工具:IntellijIDEA.VSCode Ja

使用vue cli开发项目中遇到的坑

一.部署文件 使用vue cli 开发项目,执行npm run build命令生成dist静态文件,将dist文件包放到服务器中即可. 刚接触webpack,不知道怎么部署前端文件,原以为需要将app文件上传,在 inux上安装node,以及npm install 一系列的包,捣鼓了很久,发现只需要执行 npm run build 将源码打包成一个静态文        文件即可,上传静态文件dist,将 controller指向index.html. 二.跨域问题 实行前后端分离,使用vue i

在Vue+element 开发中报: The template root requires exactly one elemen 错的解决和原因

一.我正准备使用Vue + Element进行新的项目开发,然后在进行添加下一个组件时报错  二.解决及原因: 原来template中只允许模板里存在一个根节点,在 template 中添加一个 <div>标签,之后所有的组件全部加在 <div>即可解决. 注意:<template></template>中必须要有一个根节点且只能存在一个根节点 原文地址:https://www.cnblogs.com/jxnc/p/12219876.html

一、前后端分离【SpringBoot+SpringCloudAlibaba+VUE】一 || 项目架构简介

1.概述 ??本项目是一个基于SpringBoot2.x+vue2.X的分布式微服务架构项目,项目会不断进行迭代更新. 该项目后端利用SpringCloudAlibaba微服务架构解决方案进行重构.项目前端利用vue框架开发,页面展示主要为pc端和手机端(微信公众号). 2.开发环境 开发工具:IntellijIDEA.VSCode Java SDK版本:1.8以上 数据库:mysql 8.X NoSql:Redis.MongoDB 统一编码:UTF-8 3.部署环境 操作系统:CentOS L

微服务架构【SpringBoot+SpringCloud+VUE】一 || 微服务简介

目录 1.什么是微服务 2.Spring Cloud是什么 3.服务注册中心 4.学习交流QQ群[883210148] 1.什么是微服务 在开发项目之前,我们有必要了解一下,什么是微服务?简单来说:微服务是一种架构风格,一个大型复杂软件应用由一个或多个微服务组成.系统中的各个微服务可被独立部署,各个微服务之间是松耦合的.每个微服务仅关注于完成一件任务并很好地完成该任务.在所有情况下,每个任务代表着一个小的业务能力. 2.Spring Cloud是什么 Spring Cloud是一个微服务框架的规

Spring boot 集成 Druid 数据源

Druid是阿里开源的一个JDBC应用组件,其中包括三部分: DruidDriver:代理Driver,能够提供基于Filter-Chain模式的插件体系. DruidDataSource:高效可管理的数据库连接池. SQLParser:实用SQL语法分析 官方文档:https://github.com/alibaba/druid/wiki 依赖 pom.xml Druid Spring Boot Starter是阿里官方提供的Spring Boot插件,用于在Spring Boot项目中集成D

二、基于【 springBoot +springCloud+vue 项目】二 || 项目架构目录

1.项目架构目录 API工具类 ---commons-parent ------commons-api(api接口统一返回与统一异常处理) ------commons-core(业务通用工具类) ------commons-base(项目通用工具类) ------commons-test(工具类测试) API网关解决方案 ---theme-parent ------theme-common ---------theme-common-gateway-core(网关解决方案) ---------t

springboot集成druid数据源并且监控

Druid是Java语言中最好的数据库连接池,并且能够提供强大的监控和扩展功能. 业界把 Druid 和 HikariCP 做对比后,虽说 HikariCP 的性能比 Druid 高,但是因为 Druid 包括很多维度的统计和分析功能,所以这也是大家都选择使用它的原因. 首先配置 druid maven 依赖 <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactI