在实际项目开发过程中,有可能会有需求,数据源动态来创建,数据库连接地址、账号、密码不允许明文存在,然后服务有可能是集群部署的,如果修改了连接等等,就需要所有的服务器一起来进行修改,这个会有一些问题,一是服务器有可能很多,而是人为修改,有可能出现手误修改错误。所以使用携程推出的apollo,自动发布到各个服务器中。利用此可以进行动态Druid的数据源生成。
一:SpringBoot集成Apollo
首先在pom中引入apollo。
<!-- apollo -->
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-client</artifactId>
<version>1.1.0</version>
</dependency>
<dependency>
<groupId>com.ctrip.framework.apollo</groupId>
<artifactId>apollo-core</artifactId>
<version>1.1.0</version>
</dependency>
如果是windows系统,需要在C盘创建opt文件夹,然后在创建settings文件夹,然后加入server.properties文件,内容:env=DEV,这个发布到生产后,换成生产。经过测试,不创建这个文件也没有什么问题。
成功后,apollo发布后,会在opt文件夹中出现一个data文件夹,这个文件夹中就是apollo生成的文件。
里面的内容大体上为:
这个就是在apollo中配置的。
然后进行application.yml的配置:
spring:
thymeleaf:
prefix: classpath:/templates/
suffix: .html
mode: LEGACYHTML5
encoding: UTF-8
cache: false
resources:
chain:
strategy:
content:
enabled: true
paths: /**
mvc:
static-path-pattern: /static/**
datasource:
type: com.alibaba.druid.pool.DruidDataSource
# 下面为连接池的补充设置,应用到上面所有数据源中
# 初始化大小,最小,最大
initialSize: 1
maxActive: 20
# 配置获取连接等待超时的时间
maxWait: 60000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 30000
validationQuery: select 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小
poolPreparedStatements: true
maxPoolPreparedStatementPerConnectionSize: 20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall,slf4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
# 合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
application:
name: gportal
jmx:
enabled: false
# server config
server:
port: 8443
tomcat:
uri-encoding: UTF-8
http:
port: 8081
ssl:
key-store: classpath:*****.jks
key-store-password: ******
key-store-type: JKS
# swagger config
swagger:
enabled: true
scan_package: com.**.***.***
# mybatis config
mybatis:
mapper-locations: classpath:mapper/*Mapper.xml #所有的mapper映射文件
type-aliases-package: com.**.***.**.model #定义所有操作类的别名所在包
config-location: classpath:mybatis/mybatis.cfg.xml #mybatis配置文件所在路径
# apollo config
app:
id: ***_****
apollo:
meta: apollo地址
bootstrap:
enabled: true
namespaces: datasource
然后进行apollo和Druid的结合,确保启动类上加入@EnableApolloConfig 这个注解。
@SpringBootApplication
@EnableApolloConfig
public class FormApplication {
public static void main(String[] args) {
SpringApplication.run(FormApplication.class, args);
}
}
然后创建配置类,上代码:
使用@Data以及@ToString的注解,需要下载lombook的插件,否则会出现问题,不能生成getter() setter()等等方法。
import com.ctrip.framework.apollo.Config;
import com.ctrip.framework.apollo.model.ConfigChange;
import com.ctrip.framework.apollo.model.ConfigChangeEvent;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfig;
import com.ctrip.framework.apollo.spring.annotation.ApolloConfigChangeListener;
import com.ctrip.framework.apollo.spring.annotation.EnableApolloConfig;
import lombok.Data;
import lombok.ToString;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;
@Data
@ToString
@Component
@ConfigurationProperties
@EnableApolloConfig("datasource")
@SuppressWarnings({"unused"})
public class DatasourceConfig {
// 动态的从Apollo获取
private String url;
private String userName;
private String password;
private String driverClassName;
/**
* @ApolloConfig用来自动注入Config对象
*/
@ApolloConfig("datasource")
private Config config;
@ApolloConfigChangeListener("datasource")
private void someOnChange(final ConfigChangeEvent configChangeEvent) {
configChangeEvent.changedKeys().forEach(key -> {
ConfigChange configChange = configChangeEvent.getChange(key);
System.out.println(String.format("Found datasource change - key: %s, oldValue: %s, newValue: %s, changeType: %s",
configChange.getPropertyName(), configChange.getOldValue(), configChange.getNewValue(), configChange.getChangeType()));
});
}
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;
}
public String getDriverClassName() {
return driverClassName;
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
public Config getConfig() {
return config;
}
public void setConfig(Config config) {
this.config = config;
}
}
然后进行Druid的配置:
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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;
import java.sql.SQLException;
@Configuration
public class DruidConfig {
public static final Logger logger = LoggerFactory.getLogger(DruidConfig.class);
private static final String DB_PREFIX = "spring.datasource";
@Bean
public ServletRegistrationBean druidServlet() {
logger.info("init Druid Servlet Configuration");
ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
// IP 白名单
servletRegistrationBean.addInitParameter("allow", "*****");
// IP黑名单(共同存在时,deny优先于allow)
servletRegistrationBean.addInitParameter("deny", "****");
// 控制台管理用户
servletRegistrationBean.addInitParameter("loginUsername", "****");
servletRegistrationBean.addInitParameter("loginPassword", "****");
// 是否能够重置数据 禁用HTML页面上的“Reset All”功能
servletRegistrationBean.addInitParameter("resetEnable", "false");
return servletRegistrationBean;
}
@Bean
public FilterRegistrationBean filterRegistrationBean() {
FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
filterRegistrationBean.addUrlPatterns("/*");
filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
return filterRegistrationBean;
}
@Autowired
DatasourceConfig datasourceConfig;
//解决 spring.datasource.filters=stat,wall,log4j 无法正常注册进去
@ConfigurationProperties(prefix = DB_PREFIX)
class IDataSourceProperties {
private String url = datasourceConfig.getUrl();
private String username = datasourceConfig.getUserName();
private String password = datasourceConfig.getPassword();
private String driverClassName = datasourceConfig.getDriverClassName();
private int initialSize;
private int minIdle;
private int maxActive;
private int maxWait;
private int timeBetweenEvictionRunsMillis;
private int minEvictableIdleTimeMillis;
private String validationQuery;
private boolean testWhileIdle;
private boolean testOnBorrow;
private boolean testOnReturn;
private boolean poolPreparedStatements;
private int maxPoolPreparedStatementPerConnectionSize;
private String filters;
private String connectionProperties;
@Bean
@Primary
public DataSource dataSource() {
DruidDataSource datasource = new DruidDataSource();
datasource.setUrl(url);
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);
try {
datasource.setFilters(filters);
} catch (SQLException e) {
System.err.println("druid configuration initialization filter: " + e);
}
datasource.setConnectionProperties(connectionProperties);
return datasource;
}
public String getUrl() {
return datasourceConfig.getUrl();
}
public void setUrl(String url) {
this.url = url;
}
public String getUsername() {
return datasourceConfig.getUserName();
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return datasourceConfig.getPassword();
}
public void setPassword(String password) {
this.password = password;
}
public String getDriverClassName() {
return datasourceConfig.getDriverClassName();
}
public void setDriverClassName(String driverClassName) {
this.driverClassName = driverClassName;
}
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 int getMaxWait() {
return maxWait;
}
public void setMaxWait(int maxWait) {
this.maxWait = maxWait;
}
public int getTimeBetweenEvictionRunsMillis() {
return timeBetweenEvictionRunsMillis;
}
public void setTimeBetweenEvictionRunsMillis(int timeBetweenEvictionRunsMillis) {
this.timeBetweenEvictionRunsMillis = timeBetweenEvictionRunsMillis;
}
public int getMinEvictableIdleTimeMillis() {
return minEvictableIdleTimeMillis;
}
public void setMinEvictableIdleTimeMillis(int 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 getConnectionProperties() {
return connectionProperties;
}
public void setConnectionProperties(String connectionProperties) {
this.connectionProperties = connectionProperties;
}
}
}
配置到此完成。然后就可以进行正常的CURD的操作了。