springboot druid配置配置的druid德鲁伊访问出404

zhuanlan_ 删除。分享分享文章到朋友圈分享文章到 QQ分享文章到 QQ 空间分享文章到微博复制文章链接到剪贴板扫描二维码扫描关注云+社区289 篇文章37 人订阅并不是因为我需要用到什么领域的知识而去学习,而只是单纯的我想知道,我想弄明白。相关文章来自专栏75来自专栏55来自专栏68来自专栏91来自专栏35来自专栏49扫描二维码扫描关注云+社区记录SpringBoot使用Druid和Mybatis配置
1.Druid介绍也不专业,百度自查
主要几个配置:
先配置文件application.properties中:
server.port=8081
spring.mvc.view.prefix = classpath:/templates/
spring.mvc.view.suffix = .html
#静态资源配置在conf/WebMvcConfig
#使用Mysql
spring.datasource.type = com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3307/website
spring.datasource.username=root
spring.datasource.password=
spring.datasource.driverClassName=com.mysql.jdbc.Driver
#连接池的配置信息
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=druid.stat.slowSqlMillis=5000
mybatis.config-locations=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.type-aliases-package=com.damionew.website.model然后几个类
DruidDBConfig
import java.sql.SQLE
import javax.sql.DataS
import org.slf4j.L
import org.slf4j.LoggerF
import org.springframework.beans.factory.annotation.V
import org.springframework.context.annotation.B
import org.springframework.context.annotation.C
import org.springframework.context.annotation.P
import com.alibaba.druid.pool.DruidDataS
import com.alibaba.druid.support.http.StatViewS
import com.alibaba.druid.support.http.WebStatF
@Configuration
public class DruidDBConfig {
private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
@Value("${spring.datasource.url}")
private String dbU
@Value("${spring.datasource.username}")
@Value("${spring.datasource.password}")
@Value("${spring.datasource.driverClassName}")
private String driverClassN
@Value("${spring.datasource.initialSize}")
private int initialS
@Value("${spring.datasource.minIdle}")
private int minI
@Value("${spring.datasource.maxActive}")
private int maxA
@Value("${spring.datasource.maxWait}")
private int maxW
@Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsM
@Value("${spring.datasource.minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeM
@Value("${spring.datasource.validationQuery}")
private String validationQ
@Value("${spring.datasource.testWhileIdle}")
private boolean testWhileI
@Value("${spring.datasource.testOnBorrow}")
private boolean testOnB
@Value("${spring.datasource.testOnReturn}")
private boolean testOnR
@Value("${spring.datasource.poolPreparedStatements}")
private boolean poolPreparedS
@Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionS
@Value("${spring.datasource.filters}")
@Value("{spring.datasource.connectionProperties}")
private String connectionP
//声明其为Bean实例
//在同样的DataSource中,首先使用被标注的DataSource
public DataSource dataSource(){
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(this.dbUrl);
datasource.setUsername(username);
datasource.setPassword(password);
datasource.setDriverClassName(driverClassName);
//configuration
datasource.setInitialSize(initialSize);
datasource.setMinIdle(minIdle);
datasource.setMaxActive(maxActive);
datasource.setMaxWait(maxWait);
datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
datasource.setValidationQuery(validationQuery);
datasource.setTestWhileIdle(testWhileIdle);
datasource.setTestOnBorrow(testOnBorrow);
datasource.setTestOnReturn(testOnReturn);
datasource.setPoolPreparedStatements(poolPreparedStatements);
datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
datasource.setFilters(filters);
} catch (SQLException e) {
logger.error("druid configuration initialization filter", e);
datasource.setConnectionProperties(connectionProperties);
}DruidStatFilterimport javax.servlet.annotation.WebF
import javax.servlet.annotation.WebInitP
import com.alibaba.druid.support.http.WebStatF
@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
initParams={
@WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")//忽略资源
public class DruidStatFilter extends WebStatFilter {
DruidStatViewServlet
@WebServlet(urlPatterns="/druid/*",
initParams={
@WebInitParam(name="allow",value=""),// IP白名单(没有配置或者为空,则允许所有访问)
@WebInitParam(name="deny",value=""),// IP黑名单 (存在共同时,deny优先于allow)
@WebInitParam(name="loginUsername",value="root"),// 用户名
@WebInitParam(name="loginPassword",value="123"),// 密码
@WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能
public class DruidStatViewServlet extends StatViewServlet {
private static final long serialVersionUID = -5249539L;
这样,等下http://localhost:8081/druid/login.html登录时账号密码就是root,123
还有一个就是,在Application类中加上@ServletComponentScan
@ServletComponentScan
@EnableWebMvc
@SpringBootApplication
@MapperScan("com.damionew.website.dao")
public class Application extends WebMvcConfigurerAdapter{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
这样就可以显示数据库监控页面,页面是Druid生成的
然后Mybatis配置,心痛,当出现
Invalid bound statement (not found): com.damionew.website.dao.UserDao.insert
时,查了很久,在xml配置文件终于找到,mybatis.mapper-locations
手写的,手残少了s。。
详情还是这个自带demo的,使用xml配置
感觉只要配置文件路径正确,命名空间正确,就没啥毛病了
没有更多推荐了,SpringBoot整合druid数据源及添加Druid监控页面 - 简书
SpringBoot整合druid数据源及添加Druid监控页面
不是不会,只是没见过,代码只是一种工具,首先要会用,应用中使用druid连接池,并添加监控
1.首先引入druid坐标
&dependency&
&groupId&com.alibaba&/groupId&
&artifactId&druid&/artifactId&
&version&1.0.11&/version&
&/dependency&
2.添加druid配置参数
initialSize
初始化配置
最小连接数
最大连接数
获取连接超时时间(单位:ms)
timeBetweenEvictionRunsMillis
连接有效性检测时间(单位:ms)
testOnBorrow
获取连接检测
testOnReturn
归还连接检测
minEvictableIdleTimeMillis
最大空闲时间(单位ms)
testWhileIdle
在获取连接后,确定是否要进行连接空间时间的检查
配置说明:
1:minEvictableIdleTimeMillis(最大空闲时间):默认为30分钟,配置里面不进行设置。
2:testOnBorrow ,testOnReturn 默认为关闭,可以设置为不配置。
3:testWhileIdle(在获取连接后,确定是否要进行连接空闲时间的检查)。默认为true。配置里面不再进行设置。
流程说明:
1:在第一次调用connection的时候,才会进行 initialSize的初始化。
2:心跳检测时间线程,会休眠timeBetweenEvictionRunsMillis时间,然后只对(没有borrow的线程 减去 minIdle)的线程进行检查,如果空闲时间大于minEvictableIdleTimeMillis则进行close。
3:testWhileIdle必须设置为true,在获取到连接后,先检查testOnBorrow,然后再判定testwhileIdle,如果连接空闲时间大于timeBetweenEvictionRunsMillis,则会进行心跳检测。
4:不需要配置validationQuery,如果不配置的情况下会走ping命令,性能更高。
5:连接保存在数组里面,获取连接的时候,获取数组的最后一位。在imeBetweenEvictionRunsMillis时是从前往后进行检查连接的有效性。
在applicatioin.properties中添加配置
druid.url=jdbc:postgresql://139.1X8.1.1X8:1XX0/account
druid.driver-class=org.postgresql.Driver
druid.username=root
druid.password=123
druid.initial-size=1
druid.min-idle=1
druid.max-active=20
druid.test-on-borrow=true
druid.timeBetweenEvictionRunsMillis=9000
3.定义配置类,启动读取druid开头的参数
driver-class有和driverClass是不一样的,所以要引入,参数容错坐标
&!--配置命名容错处理--&
&dependency&
&groupId&org.springframework.boot&/groupId&
&artifactId&spring-boot-configuration-processor&/artifactId&
&optional&true&/optional&
&/dependency&
@ConfigurationProperties(prefix = "druid")
public class DruidProperties {
private String driverC
private int maxA//最大连接数
private int minI//最小连接数
private int initialS//初始化数量和
private boolean testOnB
private Long timeBetweenEvictionRunsM//心跳
@Configuration
@EnableConfigurationProperties(DruidProperties.class)
@ConditionalOnClass(DruidDataSource.class)
@ConditionalOnProperty(prefix = "druid", name = "url")
@AutoConfigureBefore(DataSourceAutoConfiguration.class)
public class DruidAutoConfiguration {
@Autowired
private DruidP
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(properties.getUrl());
dataSource.setUsername(properties.getUsername());
dataSource.setPassword(properties.getPassword());
dataSource.setTimeBetweenEvictionRunsMillis(properties.getTimeBetweenEvictionRunsMillis());
if (properties.getInitialSize() & 0) {
dataSource.setInitialSize(properties.getInitialSize());
if (properties.getMinIdle() & 0) {
dataSource.setMinIdle(properties.getMinIdle());
if (properties.getMaxActive() & 0) {
dataSource.setMaxActive(properties.getMaxActive());
dataSource.setTestOnBorrow(properties.isTestOnBorrow());
dataSource.init();
} catch (SQLException e) {
throw new RuntimeException(e);
return dataS
5.添加拦截器,拦截器druid性能监控
* @Package: pterosaur.account.config.druid
* @Description: 监控数据库性能
* @author: liuxin
* @date: 17/4/21 上午11:23
@SuppressWarnings("serial")
@WebServlet(urlPatterns = "/druid/*",
initParams={
@WebInitParam(name="allow",value="192.168.16.110,127.0.0.1"),// IP白名单 (没有配置或者为空,则允许所有访问)
@WebInitParam(name="deny",value="192.168.16.111"),// IP黑名单 (存在共同时,deny优先于allow)
@WebInitParam(name="loginUsername",value="test"),// 用户名
@WebInitParam(name="loginPassword",value="test"),// 密码
@WebInitParam(name="resetEnable",value="false")// 禁用HTML页面上的“Reset All”功能
public class DruidStatViewServlet extends StatViewServlet{
* @Package: pterosaur.account.config.filter
* @Description: 拦截druid监控请求
* @author: liuxin
* @date: 17/4/21 上午11:24
@WebFilter(filterName="druidWebStatFilter",urlPatterns="/*",
initParams={
@WebInitParam(name="exclusions",value="*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*")// 忽略资源
public class DruidStatFilter extends WebStatFilter{
6.最终要一步,启动扫描Servlet
@SpringBootApplication
@MapperScan(basePackages = "pterosaur.account.mapper")
@EnableCaching
@ServletComponentScan
public class AccountApplication {
public static void main(String[] args) {
SpringApplication.run(AccountApplication.class, args);
最终,你归本溯源,你还是拿起了当初那本《设计模式》,你终于深深体会到了里面闪烁的智慧。
Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智能路由,微代理,控制总线)。分布式系统的协调导致了样板模式, 使用Spring Cloud开发人员可以快速地支持实现这些模式的服务和应用程序。他们将在任何分布式...
国家电网公司企业标准(Q/GDW)- 面向对象的用电信息数据交换协议 - 报批稿: 前言: 排版 by Dr_Ting公众号:庭说移步 tingtalk.me 获得更友好的阅读体验 Q/GDW XXXX-201X《面向对象的用电信息数据交换协议》是根据《国家...
百战程序员_ Java1573题 QQ群:034603 掌握80%年薪20万掌握50%年薪10万 全程项目穿插, 从易到难,含17个项目视频和资料持续更新,请关注www.itbaizhan.com 国内最牛七星级团队马士兵、高淇等11位十年开发经验专...
druid介绍 这是druid对自己的介绍: Druid是阿里开源的一个数据库连接池技术,号称自己是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。至于为什么它...
用两张图告诉你,为什么你的 App 会卡顿? - Android - 掘金Cover 有什么料? 从这篇文章中你能获得这些料: 知道setContentView()之后发生了什么? ... Android 获取 View 宽高的常用正确方式,避免为零 - 掘金相信有很多朋友...
你曾经怀揣着梦想与不肯放弃的机会,你告诉自己去过自己想过的生活,我记得那天是日,你很高兴也很兴奋,因为你考上了正式的公职教师,可是你也因此失去留在好学校让自己成长的机会,你告诉自己只要努力一切都将过去,也将变得更好。可是第二天却换来了自己心爱的女人和自己...
此时此地没有答案是必须的 不要一个人在莱茵河畔听雨 水汽过于稠密 会沾湿情人的眼眸 爱情已经过分得朦胧 即便是清醒的 水深两百米 看不清晰 空气并不是没有份量 沉默的时候也不是没了话语 只是有你的时候 我是贪婪 吞吐着愈来愈珍贵的快乐 披风而飞 一个人的时候最好什么都不做 ...
坚持就是胜利 好!环境
将 UIImage 转换为 CIImage 将 CIImage 转换为 UIImage 图片转成 Base 64 编码
最近几个月来,外媒一直有消息称,2016年上半年,苹果公司将会对笔记本产品线进行升级或者刷新,据称可能会在年中的开发大会上宣布。 就在昨天,苹果在官网上更新了 12 英寸 Macbook 产品线,新版 MacBook 配备了 Intel 的新一代 Skylake 架构处理器...springboot1.5.4 配置druid1.1.0(使用druid-spring-boot-starter)
时间: 11:23:57
&&&& 阅读:1173
&&&& 评论:
&&&& 收藏:0
标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&原文:
### Druid 最近发布了1.1.0 版本,并且提供了 [druid-spring-boot-starter](https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter),方便与Spring Boot集成
1. 首先添加依赖```
&dependency&
&groupId&com.alibaba&/groupId&
&artifactId&druid-spring-boot-starter&/artifactId&
&version&1.1.0&/version&
&/dependency&```2. 然后配置[application.properties](https://github.com/x113773/testall/blob/master/src/main/resources/application.properties)```#JDBCspring.datasource.url=jdbc:mysql://localhost:3306/testall?characterEncoding=utf8&useSSL=truespring.datasource.username=rootspring.datasource.password=123qwespring.datasource.driver-class-name=com.mysql.jdbc.Driver #非必需spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #非必需
# 连接池配置,下面配置说明请参考Druid Github Wiki,配置_DruidDataSource参考配置spring.datasource.druid.initialSize=2spring.datasource.druid.minIdle=2spring.datasource.druid.maxActive=30
######Druid监控配置#######下面配置说明请参考Druid Github Wiki,配置_配置WebStatFilterspring.datasource.druid.WebStatFilter.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*
#下面配置说明请参考Druid Github Wiki,配置_StatViewServlet配置spring.datasource.druid.StatViewServlet.loginUsername=druidspring.datasource.druid.StatViewServlet.loginPassword=druid```更多配置,请参考[这里](https://github.com/alibaba/druid/blob/master/druid-spring-boot-starter/src/test/resources/config-template.properties)
---接下来可以启动项目看看,访问http://localhost:8080/druid
首先输入上面配置的用户名和密码 druid 进行登录:
执行一个查询请求,然后查看SQL监控页面![qq 28](https://user-images.githubusercontent.com/60-5cae-11e7-852a-7bc43cd6672c.png)
查看数据源页面![qq 48](https://user-images.githubusercontent.com/67637-ab20ebae-5cae-11e7-822d-85.png)标签:&&&&&&&&&&&&&&&&&&&&&&&&&&&原文地址:http://www.cnblogs.com/x113773/p/7093171.html
&&国之画&&&& &&&&chrome插件
版权所有 京ICP备号-2
迷上了代码!在搭建项目框架的时候用的是springboot,想统一处理异常,但是发现404的错误总是捕捉不到,总是返回的是springBoot自带的错误结果信息。
如下是springBoot自带的错误结果信息:
"timestamp": 9,
"status": 404,
"error": "Not Found",
"message": "No message available",
"path": "/rest11/auth"
百度一波,发现需要配置文件中加上如下配置:
properties格式:
#出现错误时, 直接抛出异常
spring.mvc.throw-exception-if-no-handler-found=true
#不要为我们工程中的资源文件建立映射
spring.resources.add-mappings=false
#出现错误时, 直接抛出异常(便于异常统一处理,否则捕获不到404)
throw-exception-if-no-handler-found: true
#不要为我们工程中的资源文件建立映射
resources:
add-mappings: false
下面是我SpringMVC-config配置代码,里面包含统一异常处理代码,都贴上:
1 package com.qunyi.jifenzhi_zx.core.
3 import com.alibaba.druid.pool.DruidDataS
4 import com.alibaba.druid.support.http.StatViewS
5 import com.alibaba.druid.support.http.WebStatF
6 import com.alibaba.druid.support.spring.stat.BeanTypeAutoProxyC
7 import com.alibaba.druid.support.spring.stat.DruidStatI
8 import com.alibaba.fastjson.JSON;
9 import com.alibaba.fastjson.serializer.SerializerF
10 import com.alibaba.fastjson.support.config.FastJsonC
11 import com.alibaba.fastjson.support.spring.FastJsonHttpMessageC
12 import com.qunyi.jifenzhi_zx.core.C
13 import com.qunyi.jifenzhi_zx.core.base.exception.ServiceE
14 import com.qunyi.jifenzhi_zx.core.base.result.ResponseM
15 import com.qunyi.jifenzhi_zx.core.base.result.R
16 import org.slf4j.L
17 import org.slf4j.LoggerF
18 import org.springframework.beans.factory.annotation.V
19 import org.springframework.boot.web.servlet.FilterRegistrationB
20 import org.springframework.boot.web.servlet.ServletListenerRegistrationB
21 import org.springframework.boot.web.servlet.ServletRegistrationB
22 import org.springframework.context.annotation.B
23 import org.springframework.context.annotation.C
24 import org.springframework.http.converter.HttpMessageC
25 import org.springframework.web.context.request.RequestContextL
26 import org.springframework.web.method.HandlerM
27 import org.springframework.web.servlet.HandlerExceptionR
28 import org.springframework.web.servlet.ModelAndV
29 import org.springframework.web.servlet.NoHandlerFoundE
30 import org.springframework.web.servlet.config.annotation.CorsR
31 import org.springframework.web.servlet.config.annotation.InterceptorR
32 import org.springframework.web.servlet.config.annotation.ResourceHandlerR
33 import org.springframework.web.servlet.config.annotation.WebMvcConfigurerA
34 import org.springframework.web.servlet.handler.HandlerInterceptorA
36 import javax.servlet.http.HttpServletR
37 import javax.servlet.http.HttpServletR
38 import java.io.IOE
39 import java.nio.charset.C
40 import java.util.L
* Spring MVC 配置
* @author xujingyang
48 @Configuration
49 public class WebMvcConfigurer extends WebMvcConfigurerAdapter {
private final Logger logger = LoggerFactory.getLogger(WebMvcConfigurer.class);
@Value("${spring.profiles.active}")
private S//当前激活的配置文件
//使用阿里 FastJson 作为JSON MessageConverter
public void configureMessageConverters(List&HttpMessageConverter&?&& converters) {
FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
FastJsonConfig config = new FastJsonConfig();
config.setSerializerFeatures(SerializerFeature.WriteMapNullValue,//保留空的字段
SerializerFeature.WriteNullStringAsEmpty,//String null -& ""
SerializerFeature.WriteNullNumberAsZero);//Number null -& 0
converter.setFastJsonConfig(config);
converter.setDefaultCharset(Charset.forName("UTF-8"));
converters.add(converter);
//统一异常处理
public void configureHandlerExceptionResolvers(List&HandlerExceptionResolver& exceptionResolvers) {
exceptionResolvers.add(new HandlerExceptionResolver() {
public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception e) {
if (e instanceof ServiceException) {//业务失败的异常,如&账号或密码错误&
result = new ResponseMsg("501", "业务层出错:" + e.getMessage());
logger.info(e.getMessage());
} else if (e instanceof NoHandlerFoundException) {
result = new ResponseMsg("404", "接口 [" + request.getRequestURI() + "] 不存在");
result = new ResponseMsg("500", "接口 [" + request.getRequestURI() + "] 错误,请联系管理员!");
if (handler instanceof HandlerMethod) {
HandlerMethod handlerMethod = (HandlerMethod)
message = String.format("接口 [%s] 出现异常,方法:%s.%s,异常摘要:%s",
request.getRequestURI(),
handlerMethod.getBean().getClass().getName(),
handlerMethod.getMethod().getName(),
e.getMessage());
message = e.getMessage();
logger.error(message, e);
responseResult(response, result);
return new ModelAndView();
//解决跨域问题
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**") // **代表所有路径
.allowedOrigins("*") // allowOrigin指可以通过的ip,*代表所有,可以使用指定的ip,多个的话可以用逗号分隔,默认为*
.allowedMethods("GET", "POST", "HEAD", "PUT", "DELETE") // 指请求方式 默认为*
.allowCredentials(false) // 支持证书,默认为true
.maxAge(3600) // 最大过期时间,默认为-1
.allowedHeaders("*");
//添加拦截器
public void addInterceptors(InterceptorRegistry registry) {
//接口登录验证拦截器
if (!"dev".equals(env)) { //开发环境忽略登录验证
registry.addInterceptor(new HandlerInterceptorAdapter() {
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//验证登录
Object obj = request.getSession().getAttribute(Const.LOGIN_SESSION_KEY);
if (obj != null) {
return true;
logger.warn("请先登录!==& 请求接口:{},请求IP:{},请求参数:{}",
request.getRequestURI(), getIpAddress(request), JSON.toJSONString(request.getParameterMap()));
responseResult(response, new ResponseMsg(Result.SIGNERROR));
return false;
private void responseResult(HttpServletResponse response, ResponseMsg result) {
response.setCharacterEncoding("UTF-8");
response.setHeader("Content-type", "application/charset=UTF-8");
response.setStatus(200);
response.getWriter().write(JSON.toJSONString(result));
} catch (IOException ex) {
logger.error(ex.getMessage());
private String getIpAddress(HttpServletRequest request) {
String ip = request.getHeader("x-forwarded-for");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
// 如果是多级代理,那么取第一个ip为客户端ip
if (ip != null && ip.indexOf(",") != -1) {
ip = ip.substring(0, ip.indexOf(",")).trim();
* druidServlet注册
public ServletRegistrationBean druidServletRegistration() {
ServletRegistrationBean registration = new ServletRegistrationBean(new StatViewServlet());
registration.addUrlMappings("/druid/*");
* druid监控 配置URI拦截策略
public FilterRegistrationBean druidStatFilter() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
// 添加过滤规则.
filterRegistrationBean.addUrlPatterns("/*");
// 添加不需要忽略的格式信息.
filterRegistrationBean.addInitParameter("exclusions", "/web_frontend/*,*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid,/druid/*,/error,/login*");
// 用于session监控页面的用户名显示 需要登录后主动将username注入到session里
filterRegistrationBean.addInitParameter("principalSessionName", "username");
return filterRegistrationB
* druid数据库连接池监控
public DruidStatInterceptor druidStatInterceptor() {
return new DruidStatInterceptor();
* druid数据库连接池监控
public BeanTypeAutoProxyCreator beanTypeAutoProxyCreator() {
BeanTypeAutoProxyCreator beanTypeAutoProxyCreator = new BeanTypeAutoProxyCreator();
beanTypeAutoProxyCreator.setTargetBeanType(DruidDataSource.class);
beanTypeAutoProxyCreator.setInterceptorNames("druidStatInterceptor");
return beanTypeAutoProxyC
* RequestContextListener注册
public ServletListenerRegistrationBean&RequestContextListener& requestContextListenerRegistration() {
return new ServletListenerRegistrationBean&&(new RequestContextListener());
* 将swagger-ui.html 添加 到 resources目录下
* @param registry
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("swagger-ui.html").addResourceLocations("classpath:/META-INF/resources/");
registry.addResourceHandler("/webjars/**").addResourceLocations("classpath:/META-INF/resources/webjars/");
registry.addResourceHandler("/web_frontend/**").addResourceLocations("classpath:/web_frontend/");
  至此,所有错误异常都能捕捉到,统一处理了~~
阅读(...) 评论()

我要回帖

更多关于 springcloud配置druid 的文章

 

随机推荐