引入maven依赖
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.3</version>
</dependency>
在配置类中添加配置信息
@Configuration
public class MyDataSourceConfig {
/**
* 配置druid数据源
*
* @return
*/
@ConfigurationProperties("spring.datasource")
@Bean
public DataSource dataSource() {
DruidDataSource druidDataSource = new DruidDataSource();
return druidDataSource;
}
/**
* 配置druid的监控功能
*
* @return
*/
@Bean
public ServletRegistrationBean staViewServlet() {
StatViewServlet statViewServlet = new StatViewServlet();
ServletRegistrationBean<StatViewServlet> registrationBean = new ServletRegistrationBean<>(statViewServlet, "/druid/*");
//配置监控页的登录账号和密码
registrationBean.addInitParameter("loginUsername", "admin");
registrationBean.addInitParameter("loginPassword", "123456");
return registrationBean;
}
/**
* webstatFilter用于采集wb-jdbc关联监控的数据
*/
@Bean
public FilterRegistrationBean webStatFilter() {
WebStatFilter webStatFilter = new WebStatFilter();
FilterRegistrationBean<WebStatFilter> filterFilterRegistrationBean = new FilterRegistrationBean<>(webStatFilter);
//设置拦截的路径
filterFilterRegistrationBean.setUrlPatterns(Arrays.asList("/*"));
//设置发不拦截的请求路径
filterFilterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.icon,/druid/*");
return filterFilterRegistrationBean;
}
}
测试:
@Slf4j
@RestController
@RequestMapping("/hello")
public class HelloController {
@Autowired
private JdbcTemplate jdbcTemplate;
@GetMapping("/sql")
public List<Map<String, Object>> testSql(){
String sql="select * from tb_user";
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql);
return list;
}
}
在druid监控页面