mysql jdbc 多数据源_springboot中整合 jdbc ,druid 多数据源操作mysql

(1) . 导入相关依赖

org.springframework.boot

spring-boot-starter-jdbc

mysql

mysql-connector-java

compile

com.alibaba

druid

1.1.23

(2) . 配置 application.yaml

spring:

datasource:

# druid数据源配置

type: com.alibaba.druid.pool.DruidDataSource

initialSize: 10

minIdle: 10

maxActive: 200

# 配置获取连接等待超时的时间

maxWait: 60000

# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒

timeBetweenEvictionRunsMillis: 60000

# 配置一个连接在池中最小生存的时间,单位是毫秒

minEvictableIdleTimeMillis: 30000

validationQuery: select 'x'

testWhileIdle: true

testOnBorrow: false

testOnReturn: false

# 打开PSCache,并且指定每个连接上PSCache的大小

poolPreparedStatements: true

maxPoolPreparedStatementPerConnectionSize: 20

# 配置监控统计拦截的filters

filters: stat,wall,slf4j

# 通过connectProperties属性来打开mergeSql功能;慢SQL记录

connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

# 23个站点数据库配置

mysql:

jp:

name: 日本

url: jdbc:mysql://localhost:3306/zmkm?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false

username: root

password: "123456"

driver-class-name: com.mysql.cj.jdbc.Driver

rom:

name: 罗马尼亚

url: jdbc:mysql://localhost:3306/rom?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true&serverTimezone=Asia/Shanghai&autoReconnect=true&failOverReadOnly=false

username: root

password: "123456"

driver-class-name: com.mysql.cj.jdbc.Driver

(3) . 配置 DruidDataSource 并绑定到容器

package com.wangjun.daxingxing.configuration;

import com.alibaba.druid.pool.DruidDataSource;

import com.alibaba.druid.support.http.StatViewServlet;

import com.alibaba.druid.support.http.WebStatFilter;

import org.springframework.beans.factory.annotation.Qualifier;

import org.springframework.beans.factory.annotation.Value;

import org.springframework.boot.context.properties.ConfigurationProperties;

import org.springframework.boot.jdbc.DataSourceBuilder;

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.jdbc.core.JdbcTemplate;

import javax.servlet.Filter;

import javax.sql.DataSource;

import java.sql.SQLException;

import java.util.Arrays;

import java.util.HashMap;

import java.util.Map;

/**

* 子站点数据源

*/

@Configuration

public class MysqlSiteConfiguration {

@Value("${mysql.jp.name}")

private String jpName;

@Value("${mysql.rom.name}")

private String romName;

// 日本站点的数据源 ,默认使用 harki数据源

@Bean // 默认的Bean名称就是方法名

@ConfigurationProperties(prefix = "mysql.jp")

public DataSource jpDatasource(){

// return DataSourceBuilder.create().build();

DruidDataSource dataSource = new DruidDataSource();

dataSource.setInitialSize(10);

dataSource.setMinIdle(10);

dataSource.setMaxActive(200);

dataSource.setMaxWait(60000);

dataSource.setTimeBetweenEvictionRunsMillis(60000);

dataSource.setMinEvictableIdleTimeMillis(30000);

dataSource.setValidationQuery("select 1");

dataSource.setTestWhileIdle(true);

dataSource.setTestOnBorrow(false);

dataSource.setTestOnReturn(false);

dataSource.setPoolPreparedStatements(true);

dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);

/**

* 这个是用来配置 druid 监控sql语句的 非常有用 如果你有两个数据源 这个配置哪个数据源就监控哪个数据源的sql 同时配置那就都监控

*/

try {

dataSource.setFilters("stat,wall,slf4j");

} catch (SQLException e) {

e.printStackTrace();

}

dataSource.setName(jpName);

dataSource.setConnectionProperties("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000");

return dataSource;

}

// 日本站点的jdbc实例

@Bean // 默认的Bean名称就是方法名

public JdbcTemplate jpJdbcTemplate(

@Qualifier("jpDatasource") DataSource dataSource

){

return new JdbcTemplate(dataSource);

}

// 罗马尼亚站点的数据源 ,默认使用 harki数据源

@Bean // 默认的Bean名称就是方法名

@ConfigurationProperties(prefix = "mysql.rom")

public DataSource romDatasource(){

DruidDataSource dataSource = new DruidDataSource();

dataSource.setInitialSize(10);

dataSource.setMinIdle(10);

dataSource.setMaxActive(200);

dataSource.setMaxWait(60000);

dataSource.setTimeBetweenEvictionRunsMillis(60000);

dataSource.setMinEvictableIdleTimeMillis(30000);

dataSource.setValidationQuery("select 1");

dataSource.setTestWhileIdle(true);

dataSource.setTestOnBorrow(false);

dataSource.setTestOnReturn(false);

dataSource.setPoolPreparedStatements(true);

dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);

dataSource.setName(romName);

/**

* 这个是用来配置 druid 监控sql语句的 非常有用 如果你有两个数据源 这个配置哪个数据源就监控哪个数据源的sql 同时配置那就都监控

*/

try {

dataSource.setFilters("stat,wall,slf4j");

} catch (SQLException e) {

e.printStackTrace();

}

dataSource.setConnectionProperties("druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000");

return dataSource;

}

// 罗马尼亚站点的jdbc实例

@Bean // 默认的Bean名称就是方法名

public JdbcTemplate romJdbcTemplate(

@Qualifier("romDatasource") DataSource dataSource

){

return new JdbcTemplate(dataSource);

}

// 配置 druid 监控 的web面板

@Bean

public ServletRegistrationBean staViewServlet(){

ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");

Map initParams = new HashMap<>();

//设置servlet初始化参数

initParams.put("loginUsername","admin");// druid登陆名

initParams.put("loginPassword","123456");// druid密码

initParams.put("allow","");//默认就是允许所有访问

initParams.put("deny","192.168.15.21");//拒绝相对应的id访问

bean.setInitParameters(initParams);

//加载到容器中

return bean;

}

//2.配置一个web监控的filter

@Bean

public FilterRegistrationBean webStatFilter(){

FilterRegistrationBean bean = new FilterRegistrationBean<>();

bean.setFilter(new WebStatFilter());

Map initParams = new HashMap<>();

//设置filter初始化参数、

initParams.put("exclusions","*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");//排除静态资源和请求

bean.setInitParameters(initParams);

//拦截所有请求

bean.setUrlPatterns(Arrays.asList("/*"));

//加载到容器中

return bean;

}

}

d12f61f58cf2

image.png

(4) . 基本使用

@Autowired // 依赖注入 日本站点数据库

@Qualifier("jpJdbcTemplate")

JdbcTemplate jpJdbcTemplate;

@Autowired // 依赖注入 jdbcTemplate

@Qualifier("romJdbcTemplate") # 数据源 rom

JdbcTemplate romJdbcTemplate;

@Override

public void run(String... args) {

logger.error("框架初始化加载执行的代码");

String sql = "insert into user(name,password,is_active,createtime) values (?,?,?,?)";

KeyHolder keyHolder = new GeneratedKeyHolder();

int r = 0;

try{

r = template.update(new PreparedStatementCreator() {

@Override

public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {

String name = "wangjun";

String pwd = "123456";

String password = null;

try {

password = DigestUtils.sha1Hex(pwd.getBytes("UTF-8"));

} catch (UnsupportedEncodingException e) {

logger.error("sha1Hex failed"); // 记录日志

}

byte is_active = 0;

PreparedStatement preparedStatement = connection.prepareStatement(sql, new String[]{"id"});

preparedStatement.setString(1, name);

preparedStatement.setString(2, password);

preparedStatement.setByte(3,is_active);

preparedStatement.setDate(4,new java.sql.Date(System.currentTimeMillis()));

return preparedStatement;

}

}, keyHolder);

}catch(Throwable e){

logger.error("execute error: " + e.getMessage()); // 记录日志

}

if(r > 0){

long id = keyHolder.getKey().longValue();

System.out.println("主键 -> " + id);

} else{

System.out.println("写入数据库失败");

}

// 数据源如果为 HikariDataSource,则表示使用默认的 jdbc操作mysql

System.out.println("数据源:"+jpJdbcTemplate.getDataSource().getClass().toString()); // 查看数据源是否为 Druid

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值