SpringBoot+Druid+Nutz+Jasypt整合配置多数据源

天大地大妈咪最大 提交于 2019-12-20 18:51:04

【推荐】2019 Java 开发者跳槽指南.pdf(吐血整理) >>>

一 .    引入依赖

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

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>

        <!-- jdbc驱动依赖 -->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.alibaba/druid-spring-boot-starter -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.21</version>
        </dependency>

        <dependency>
            <groupId>org.nutz</groupId>
            <artifactId>nutz</artifactId>
            <version>1.r.62</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.0</version>
        </dependency>

        <!--jasypt密码加密解密-->
        <dependency>
            <groupId>org.jasypt</groupId>
            <artifactId>jasypt</artifactId>
            <version>1.9.3</version>
            <scope>compile</scope>
        </dependency>

二.    application.yml配置文件

spring:
  datasource:
    type: com.alibaba.druid.pool.DruidDataSource
    druid:
      main:
        url: jdbc:mysql://127.0.0.1:3306/data_hn?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
        username: root
        password: +7kwXYHUt9V4btttYVr3MOr/71O/ZIL7
        salt: gxmh
      subo:
        url: jdbc:mysql://127.0.0.1:3306/data_gs?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=GMT%2B8
        username: root
        password: +7kwXYHUt9V4btttYVr3MOr/71O/ZIL7
        salt: gxmh
      initial-size: 5   # 初始化连接大小 默认0
      max-active: 20   # 最大连接数 默认8
      min-idle: 5   # 最小空闲连接数 默认0
      # 监控页面的用户名密码及页面地址
      stat-view-servlet:
        login-username: admin
        login-password: 123456
        enabled: true
        url-pattern: /druid/*
      max-wait: 60000   # 获取连接等待超时的时间(毫秒) 默认:-1
      query-timeout: 90   # 查询超时时间
      validation-query: SELECT 1 FROM DUAL
      test-on-borrow: false   # 申请连接时检测连接可用性 默认:false
      test-on-return: false   # 归还连接检测 默认false
      test-while-idle: true   # 超时是否检测连接可用性
      time-between-eviction-runs-millis: 60000  # 配置空闲多久检测需要配置的空闲连接(毫秒)
      min-evictable-idle-time-millis: 300000    # 配置一个连接在池中最小生存时间 默认30分钟
      filters: config,stat,wall,slf4j    # 通过别名的方式配置扩展插件,常用的插件有:监控统计用的filter:stat;日志用的filter:log4j;防御sql注入的filter:wall
      filter:
        stat:
          log-slow-sql: true  # 慢SQL记录
          slow-sql-millis: 2000
          db-type: mysql
          merge-sql: false    # SQL合并 默认false
        wall:
          config:   #是否允许delete和drop表语句
            delete-allow: true
            drop-table-allow: false
          enabled: true
          db-type: mysql
      pool-prepared-statements: false   # 是否缓存PreparedStatement. PSCache对支持游标的数据库性能提升巨大,比如说oracle.在mysql下建议关闭.
      max-pool-prepared-statement-per-connection-size: 20   # 每个连接上的PSCache的大小
      use-global-data-source-stat: true   # 合并多个DataSource的监控数据

server:
  port: 8181

三.    数据源配置类DataSourceConfig

import com.alibaba.druid.pool.DruidDataSource;
import com.example.demo.utils.JasyptUtils;
import org.nutz.dao.Dao;
import org.nutz.dao.impl.NutDao;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.bind.Binder;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.env.Environment;

import javax.sql.DataSource;

/**
 * @program: demo
 * @description: 数据源配置类
 * @author: guoxu
 * @create: 2019-12-19 14:56
 */
/**
 * 1.当存在多个数据源时,最好加上@Primary注解,这样默认使用这个连接。
 * 2.使用Qualifier注解说明使用某个连接。
 */
@Configuration
public class DataSourceConfig implements EnvironmentAware {

    @Value("${spring.datasource.druid.main.salt}")
    private String salt;

    private Environment environment;

    private DataSource defaultDataSource;

    @Override
    public void setEnvironment(Environment environment) {
        this.environment = environment;
    }

    //配置主数据源
    @Primary
    @Bean
    public DataSource initDataSource(){
        Binder binder = Binder.get(environment);
        defaultDataSource = binder.bind("spring.datasource.druid.main", DruidDataSource.class).get();
        String password = ((DruidDataSource) defaultDataSource).getPassword();
        ((DruidDataSource) defaultDataSource).setPassword(JasyptUtils.strEnDecrypt(password, salt, 1));
        return defaultDataSource;
    }

    //配置从数据源
    @Bean(name = "sds")
    public DataSource initSDataSource(){
        Binder binder = Binder.get(environment);
        defaultDataSource = binder.bind("spring.datasource.druid.subo", DruidDataSource.class).get();
        String password = ((DruidDataSource) defaultDataSource).getPassword();
        ((DruidDataSource) defaultDataSource).setPassword(JasyptUtils.strEnDecrypt(password, salt, 1));
        return defaultDataSource;
    }

    //主数据源绑定Nutz
    @Primary
    @Bean
    public Dao initNutzDao(DataSource dataSource){
        return new NutDao(dataSource);
    }

    //从数据源绑定Nutz
    @Bean(name = "sdao")
    public Dao initSNutzDao(@Qualifier("sds") DataSource dataSource){
        return new NutDao(dataSource);
    }
}

四.    Nutz使用

    @Autowired
    Dao dao;

    @Autowired
    @Qualifier("sdao")
    Dao sdao;

五. Jasypt加密工具类

package com.example.demo.utils;

import org.jasypt.encryption.pbe.StandardPBEStringEncryptor;
import org.jasypt.encryption.pbe.config.EnvironmentStringPBEConfig;

/**
 * @program: gxww-frame-cloud
 * @description: Jasypt加密解密工具类
 * @author: guoxu
 * @create: 2019-12-16 14:57
 */
public class JasyptUtils {

    public static void main(String[] args) {
        String encrypt = strEnDecrypt("7j41Gq3M!@#", "gxmh", 0);
        System.out.println("encrypt:"+encrypt);
        String decrypt = strEnDecrypt(encrypt, "gxmh", 1);
        System.out.println("decrypt:"+decrypt);
    }

    /** 
    * @Description: 字符串加密解密
    * @Param: [plainText, salt, type]
     * salt 加密盐
     * type 0 加密  1或其他为 解密
    * @return: java.lang.String 
    * @Author: guoxu
    * @Date: 2019/12/16 
    */ 
    public static String strEnDecrypt(String plainText, String salt,int type){
        String resultStr = "";
        //加密工具
        StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
        //加密配置
        EnvironmentStringPBEConfig config = new EnvironmentStringPBEConfig();
        //加密方式,默认PBEWithMD5AndDES,可改PBEWithMD5AndTripleDES
        config.setAlgorithm("PBEWithMD5AndDES");
        //加密所需的salt(盐)
        config.setPassword(salt);
        //应用配置
        encryptor.setConfig(config);
        if (type == 0){
            resultStr = encryptor.encrypt(plainText);
        } else {
            resultStr = encryptor.decrypt(plainText);
        }
        return resultStr;
    }
}

六. 不加密数据库密码时的另一种数据源配置类

package com.example.demo.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.nutz.dao.Dao;
import org.nutz.dao.impl.NutDao;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.sql.SQLException;

/**
 * @program: demo
 * @description: 多数据源配置类
 * @author: guoxu
 * @create: 2019-12-19 14:56
 */
@Configuration
public class DataSourceConfig {

    /**
     * 当存在多个数据源时,最好加上@Primary注解,这样默认使用这个连接。
     * 不需要使用Qualifier注解说明使用某个连接。
     * @return
     * @throws SQLException
     */
    @Primary
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource.druid.main")
    public DataSource initMainDataSource() throws SQLException {
        DruidDataSource mainDataSource = DataSourceBuilder.create().type(DruidDataSource.class).build();
        return mainDataSource;
    }

    @Bean(name = "sds")
    @ConfigurationProperties(prefix = "spring.datasource.druid.subo")
    public DataSource initSuboDataSource() throws SQLException {
        DruidDataSource suboDataSource = DataSourceBuilder.create().type(DruidDataSource.class).build();
        return suboDataSource;
    }

    @Primary
    @Bean
    public Dao initNutzDao(DataSource dataSource){
        return new NutDao(dataSource);
    }

    @Bean(name = "sdao")
    public Dao initsNutzDao(@Qualifier("sds") DataSource dataSource){
        return new NutDao(dataSource);
    }


}

 

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!