乐趣区

关于java:太妙了Spring-boot-整合-Mybatis-Druid还能配置监控

Spring boot 整合 Mybatis Druid 并配置监控

增加依赖

<!--druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid-spring-boot-starter</artifactId>
    <version>1.1.16</version>
</dependency>
<!--mybatis-->
        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>
<!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
        </dependency>
如果应用 log4j 须要增加 log4j 的依赖并且排除自身 slf4j
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-log4j</artifactId>
    <version>1.3.8.RELEASE</version>
</dependency>
<dependency>
     <groupId>org.springframework.boot</groupId>
     <artifactId>spring-boot-starter-web</artifactId>
   <!-- 排除自身日志 -->
     <exclusions>
         <exclusion>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-logging</artifactId>
         </exclusion>
     </exclusions>
</dependency>

​ 附上 log4j.properties 的配置

# LOG4J rootCategory config
# 控制台输入
log4j.rootLogger=INFO, file, console
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 HH:mm:ss} %5p %c{1}:%L - %m%n
# 日志文件
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.file=logs/springboot.log
log4j.appender.file.DatePattern='.'yyyy-MM-dd
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM HH:mm:ss} %5p %c{1}:%L - %m%n

2. 提前创立一个 controller,dao,service,用于查询数据库,测试

dao

import com.ljy.sys.entity.User;

import java.util.List;

public interface SysUserMapper {List<User> findAll();
}

Mapper

service 及其实现类

import com.ljy.sys.entity.User;

import java.util.List;

public interface SysUserService {List<User> findAll();
}
import com.ljy.sys.dao.SysUserMapper;
import com.ljy.sys.entity.User;
import com.ljy.sys.model.SysUserService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
/**
 * SysUserService 实现类
 * @author ljy&jcq
 */
@Service
public class SysUserServiceImpl implements SysUserService {
    @Resource
    private SysUserMapper sysUserMapper;

    @Override
    public List<User> findAll() {return sysUserMapper.findAll();
    }
}

controller

import com.ljy.sys.model.SysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("user")
public class SysUserController {
    @Autowired
    private SysUserService sysUserService;

    @GetMapping("/findAll")
    public Object findAll(){return sysUserService.findAll();
    }
}

编写 Mybatis 的配置类

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;

import javax.sql.DataSource;

/**
 * mybatis 配置类
 * @author ljy&jcq
 * MapperScan 扫描 dao
 *
 */
@Configuration
@MapperScan("com.ljy.sys.**.dao")
public class MybatisConfig {
    @Autowired
    private DataSource dataSource;

    @Bean
    public SqlSessionFactory sqlSessionFactory() throws Exception{SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        // 扫描 service 层
        sqlSessionFactoryBean.setTypeAliasesPackage("com.ljy.sys.**.model");
        PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
        // 扫描映射文件 Mapper 文件所在的地址
        sqlSessionFactoryBean.setMapperLocations(resolver.getResources("classpath*:/templates/*.xml"));
        return sqlSessionFactoryBean.getObject();}
}

批改启动类

// 示意在利用启动时主动扫描 com.ljy.sys 包下的内容,当然 Spring Boot 也会主动扫描启动类包及其子包,这里不设置也是能够主动扫描的
@SpringBootApplication(scanBasePackages = {"com.ljy.sys"})
public class SysApplication {public static void main(String[] args) {SpringApplication.run(SysApplication.class, args);
    }
}

编写 application.yml 配置 druid 的属性

spring:
  datasource:
    #数据库连贯配置
    type: com.alibaba.druid.pool.DruidDataSource
    driver-class-name: com.mysql.cj.jdbc.Driver
    url: jdbc:mysql://127.0.0.1:3306/salery?serverTimezone=GMT%2B8&characterEncoding=UTF-8
    username: root
    password: root
    #连接池配置
    initial-size: 5  # 初始化大小
    min-idle: 5  # 最小
    max-active: 100  # 最大
    max-wait: 60000  # 连贯超时工夫
    time-between-eviction-runs-millis: 60000  # 配置距离多久才进行一次检测,检测须要敞开的闲暇连贯,单位是毫秒
    min-evictable-idle-time-millis: 300000  # 指定一个闲暇连贯起码闲暇多久后可被革除,单位是毫秒
    validationQuery: selectversion()
    test-while-idle: true  # 当连贯闲暇时,是否执行连贯测试
    test-on-borrow: false  # 当从连接池借用连贯时,是否测试该连贯
    test-on-return: false  # 在连贯偿还到连接池时是否测试该连贯
    filters: wall,stat,log4j  # 配置监控统计拦挡的 filters,去掉后监控界面 sql 无奈统计,'wall' 用于防火墙,log4j 应用哪种日志零碎就增加哪种
    poolPreparedStatements: true
    maxPoolPreparedStatementPerConnectionSize: 20
    maxOpenPreparedStatements: 20
    connectionProperties: druid.stat.slowSqlMillis=200;druid.stat.logSlowSql=true

编写配置类

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 *  druid 的配置类
 * @author jcq&ljy
 */
@Configuration
public class DruidConfig {@Bean(name = "dataSource")
    // 这里应用的是主动注入 spring.datasource 下的各种属性,如须要自定义配置,可新建配置类应用
    // 自定义配置类类名上增加 @ConfigurationProperties(prefix = "spring.datasource.druid") 导入 yml 中设置的数据
    // 在本配置类上退出 @EnableConfigurationProperties({自定义.class}) 导入自定义配置 在本办法中手动 set 注入 参考正文的办法
    @ConfigurationProperties("spring.datasource")
    @Primary
    public DataSource masterDataSource() {return DruidDataSourceBuilder.create().build();}
        /**
     *     手动 set 注入
     *     @Bean
     *     public DataSource druidDataSource() {*         DruidDataSource datasource = new DruidDataSource();;
     *         datasource.setUrl(properties.getUrl());
     *         datasource.setUsername(properties.getUsername());
     *         datasource.setPassword(properties.getPassword());
     *         datasource.setDriverClassName(properties.getDriverClassName());
     *         datasource.setInitialSize(properties.getInitialSize());
     *         datasource.setMinIdle(properties.getMinIdle());
     *         datasource.setMaxActive(properties.getMaxActive());
     *         datasource.setMaxWait(properties.getMaxWait());
     *         datasource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
     *         datasource.setMinEvictableIdleTimeMillis(properties.getMinEvictableIdleTimeMillis());
     *         datasource.setValidationQuery(properties.getValidationQuery());
     *         datasource.setTestWhileIdle(properties.isTestWhileIdle());
     *         datasource.setTestOnBorrow(properties.isTestOnBorrow());
     *         datasource.setTestOnReturn(properties.isTestOnReturn());
     *         properties.setPoolPreparedStatements(properties.isPoolPreparedStatements());
     *         properties.setMaxPoolPreparedStatementPerConnectionSize(properties.getMaxPoolPreparedStatementPerConnectionSize());
     *         properties.setFilters(properties.getFilters());
     *         return datasource;
     *     }
     */

    /**
     * 配置 Druid 的监控,一个治理后盾的 Servlet
     * @return
     */
    @Bean
    public ServletRegistrationBean druidServlet() {
        // 指定拦截器只拦挡 druid 治理页面的申请
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
        // IP 白名单,如果没有设置或为空,则示意容许所有拜访.(不能写成 *,不然会报错)servletRegistrationBean.addInitParameter("allow", "");
        // IP 黑名单 (独特存在时,deny 优先于 allow)
        servletRegistrationBean.addInitParameter("deny", "192.168.1.19");
        // 控制台治理的用户名和明码
        servletRegistrationBean.addInitParameter("loginUsername", "admin");
        servletRegistrationBean.addInitParameter("loginPassword", "admin");
        // 是否可能重置数据 禁用 HTML 页面上的“Reset All”性能
        servletRegistrationBean.addInitParameter("resetEnable", "false");
        return servletRegistrationBean;
    }

    /**
     * 配置一个 web 监控的 filter
     * @return
     */
    @Bean
    public FilterRegistrationBean filterRegistrationBean() {FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
        filterRegistrationBean.addUrlPatterns("/*");
        filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
        return filterRegistrationBean;
    }

}

登录 http://localhost:8080/druid/login.html

输出配置类中设置的账号密码,就能够看到如下界面:

然而关上数据源显示如下:

不要放心,只须要向方才的咱们写好的 controller 发送一次申请即可,发送了申请后后果如下:

​ 尤其须要留神:

​ 如果这一行显示为空,须要查看监听器配置或日志零碎是否和 yml 中的配置匹配。

​ 如果 spring 监控为空,是因为咱们没有设置切面,咱们须要设置切面

编写 spring 监控切面

import com.alibaba.druid.support.spring.stat.DruidStatInterceptor;
import org.springframework.aop.Advisor;
import org.springframework.aop.support.DefaultPointcutAdvisor;
import org.springframework.aop.support.JdkRegexpMethodPointcut;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * spring 监控配置切面
 * @author jcq&ljy
 */
@Configuration
public class SpringDaoMethodAspect {
    @Bean
    public DruidStatInterceptor druidStatInterceptor(){return new DruidStatInterceptor();
    }
    @Bean
    public JdkRegexpMethodPointcut druidStatPointcut(){JdkRegexpMethodPointcut druidStatPointcut = new JdkRegexpMethodPointcut();
        String patterns = "com.ljy.*.*.service.*";
        String patterns2 = "com.ljy.*.*.dao.*";
        druidStatPointcut.setPatterns(patterns,patterns2);
        return druidStatPointcut;
    }
    @Bean
    public Advisor druidStatAdvisor() {return new DefaultPointcutAdvisor(druidStatPointcut(), druidStatInterceptor());
    }
}

注:如果仍为空,先查看是否导入了 aop 的依赖

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-aop</artifactId>
</dependency>

最初附上胜利截图

最初

大家看完有什么不懂的能够在评论区留言,感觉对你有帮忙的话能够给我点个赞!

退出移动版