最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

springboot整合druid及多數據源配置的demo

 更新時間:2024年01月05日 09:04:04   作者:爵嵐  
這篇文章主要介紹了springboot整合druid及多數據源配置的demo,本篇主要分兩部分 ①springboot整合druid的代碼配置,以及druid的監(jiān)控頁面演示;②對實際場景中多數據源的配置使用進行講解,需要的朋友可以參考下

前言

本篇主要分兩部分 ①springboot整合druid的代碼配置,以及druid的監(jiān)控頁面演示;②對實際場景中多數據源的配置使用進行講解。

一、springboot整合druid的演示demo

可以用idea快速生成一個可運行的demo工程,具體可以參考如何快速創(chuàng)建springboot項目

主要用到的依賴如下:

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.2.17</version>
    </dependency>
   <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jdbc</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
</dependencies>

配置數據庫需要的配置文件application.yml(注意格式和空格)

spring:
  datasource:
    username: root
    password: root
    url: jdbc:mysql://localhost:3306/firsttest?serverTimezone=UTC&useUnicode=true@characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource
    poolPreparedStatements: true
     #配置監(jiān)控統(tǒng)計攔截的filters,stat:監(jiān)控統(tǒng)計、log4j:日志記錄、wall:防御sql注入
     #如果允許時報錯  java.lang.ClassNotFoundException: org.apache.log4j.Priority
 #則導入 log4j 依賴即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j     filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

編寫durid的啟動配置類,加載數據庫信息,和druid監(jiān)控頁面的初始化工作

package com.czing.jdbcdemo.config;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
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 javax.servlet.Servlet;
import javax.sql.DataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DruidConfig {
        @ConfigurationProperties(prefix = "spring.datasource")
        @Bean
        public DataSource druidDataSource(){
            return new DruidDataSource();
        }
    /**
     * @Author wangchengzhi
     * @Description
     * 向DruidConfig中添加代碼,配置druid監(jiān)控管理臺的servlet
     * @Date 22:12 2023/5/10
     * @Param
     * @return
     **/
    @Bean
    public ServletRegistrationBean druidServletRegistrationBean(){
        ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
        Map<String,String> initParams = new HashMap<>();
        initParams.put("loginUsername","root");
        initParams.put("loginPassword","root");
        //后臺允許誰可以訪問
        //initParams.put("allow", "localhost"):表示只有本機可以訪問
        //initParams.put("allow", ""):為空或者為null時,表示允許所有訪問
        initParams.put("allow","");
        //deny:Druid 后臺拒絕誰訪問
        //initParams.put("msb", "192.168.1.20");表示禁止此ip訪問
        servletRegistrationBean.setInitParameters(initParams);
        return servletRegistrationBean;
    }
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        //exclusions:設置哪些請求進行過濾排除掉,從而不進行統(tǒng)計
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        //"/*" 表示過濾所有請求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

編寫controller類進行測試(此處使用jdbcTemplate進行演示)

package com.czing.jdbcdemo.controller;
import com.czing.jdbcdemo.mult.DataSource;
import com.czing.jdbcdemo.mult.DataSourceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class JDBCController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    /**
     * @Author wangchengzhi
     * @Description
     * 使用springboot自帶的jdbcTemplate實現數據庫操作
     * @Date 21:34 2023/5/10
     * @Param
     * @return
     **/
    @RequestMapping("/selectTest")
    public List<Map<String, Object>> getTestAccount(){
        String sql ="select * from account";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
}

啟動項目,演示效果

項目啟動日志:

druid的監(jiān)控頁面訪問http://localhost:8080/druid/sql.html

二、druid多數據源的配置使用

修改application.yml文件

spring:
  datasource:
    local:
      username: root
      password: root
      #注意多數據源配置的時候此處為jdbc-url
      jdbc-url: jdbc:mysql://localhost:3306/firsttest?serverTimezone=UTC&useUnicode=true@characterEncoding=utf-8
      driver-class-name: com.mysql.jdbc.Driver
      type: com.alibaba.druid.pool.DruidDataSource
    remote:
      username: root
      password: root
      jdbc-url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true@characterEncoding=utf-8
      driver-class-name: com.mysql.jdbc.Driver
      type: com.alibaba.druid.pool.DruidDataSource

編寫多數據源的配置類:

package com.czing.jdbcdemo.config;
import com.czing.jdbcdemo.mult.DataSourceType;
import com.czing.jdbcdemo.mult.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map; 
@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties("spring.datasource.remote")
    public DataSource remoteDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean
    @ConfigurationProperties("spring.datasource.local")
    public DataSource localDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource remoteDataSource, DataSource localDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.REMOTE.name(), remoteDataSource);
        targetDataSources.put(DataSourceType.LOCAL.name(), localDataSource);
        return new DynamicDataSource(remoteDataSource, targetDataSources);
    }
}

使用自定義注解,在查詢方法的時候指定對應的數據源:

編寫枚舉類,用于指定數據源

package com.czing.jdbcdemo.mult;
public enum DataSourceType {
    REMOTE,
    LOCAL
}

數據源切換的處理類

package com.czing.jdbcdemo.mult; 
public class DynamicDataSourceContextHolder {
    /**
     * 使用ThreadLocal維護變量,ThreadLocal為每個使用該變量的線程提供獨立的變量副本,
     *  所以每一個線程都可以獨立地改變自己的副本,而不會影響其它線程所對應的副本。
     */
    private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
    /**
     * 設置數據源變量
     * @param dataSourceType
     */
    public static void setDataSourceType(String dataSourceType){
        System.out.printf("切換到{%s}數據源", dataSourceType);
        CONTEXT_HOLDER.set(dataSourceType);
    }
    /**
     * 獲取數據源變量
     * @return
     */
    public static String getDataSourceType(){
        return CONTEXT_HOLDER.get();
    }
    /**
     * 清空數據源變量
     */
    public static void clearDataSourceType(){
        CONTEXT_HOLDER.remove();
    }
}

數據源信息加載的實現

package com.czing.jdbcdemo.mult;
import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;
import javax.sql.DataSource;
import java.util.Map;
public class DynamicDataSource extends AbstractRoutingDataSource {
    public DynamicDataSource(DataSource defaultTargetDataSource, Map<Object, Object> targetDataSources) {
        super.setDefaultTargetDataSource(defaultTargetDataSource);
        super.setTargetDataSources(targetDataSources);
        // afterPropertiesSet()方法調用時用來將targetDataSources的屬性寫入resolvedDataSources中的
        super.afterPropertiesSet();
    } 
    /**
     * @Author wangchengzhi
     * @Description
     * 根據Key獲取數據源的信息
     * @Date 23:06 2023/5/10
     * @Param
     * @return
     **/
    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDataSourceType();
    }
}

多數據源的配置啟動類,注入數據庫配置信息

package com.czing.jdbcdemo.config;
import com.czing.jdbcdemo.mult.DataSourceType;
import com.czing.jdbcdemo.mult.DynamicDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
@Configuration
public class DataSourceConfig {
    @Bean
    @ConfigurationProperties("spring.datasource.remote")
    public DataSource remoteDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean
    @ConfigurationProperties("spring.datasource.local")
    public DataSource localDataSource() {
        return DataSourceBuilder.create().build();
    }
    @Bean(name = "dynamicDataSource")
    @Primary
    public DynamicDataSource dataSource(DataSource remoteDataSource, DataSource localDataSource) {
        Map<Object, Object> targetDataSources = new HashMap<>();
        targetDataSources.put(DataSourceType.REMOTE.name(), remoteDataSource);
        targetDataSources.put(DataSourceType.LOCAL.name(), localDataSource);
        return new DynamicDataSource(remoteDataSource, targetDataSources);
    }
}

自定義注解

package com.czing.jdbcdemo.mult;
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface DataSource {
    /**
     * 切換數據源名稱
     */
    DataSourceType value() default DataSourceType.REMOTE;
}

AOP攔截類的實現

package com.czing.jdbcdemo.mult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
/**
 * @Description TODO
 * @Author wangchengzhi
 * @Date 2023/5/11 10:09
 */
@Aspect
@Order(1)
@Component
public class DataSourceAspect {
    @Pointcut("@annotation(com.czing.jdbcdemo.mult.DataSource)")
    public void dsPointCut() {
    }
    @Around("dsPointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        DataSource dataSource = method.getAnnotation(DataSource.class);
        if (dataSource != null) {
            DynamicDataSourceContextHolder.setDataSourceType(dataSource.value().name());
        }
        try {
            return point.proceed();
        } finally {
            // 銷毀數據源 在執(zhí)行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }
}

controller測試類的編寫驗證

package com.czing.jdbcdemo.controller;
import com.czing.jdbcdemo.mult.DataSource;
import com.czing.jdbcdemo.mult.DataSourceType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
public class JDBCController {
    @Autowired
    JdbcTemplate jdbcTemplate;
    /**
     * @Author wangchengzhi
     * @Description
     * 使用springboot自帶的jdbcTemplate實現數據庫操作
     * @Date 21:34 2023/5/10
     * @Param
     * @return
     **/
    @RequestMapping("/selectTest")
    @DataSource(value=DataSourceType.LOCAL)
    public List<Map<String, Object>> getTestAccount(){
        String sql ="select * from account";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
    /**
     * @Author wangchengzhi
     * @Description
     * 使用springboot自帶的jdbcTemplate實現數據庫操作
     * @Date 21:34 2023/5/10
     * @Param
     * @return
     **/
    @RequestMapping("/selectRemote")
    @DataSource(DataSourceType.REMOTE)
    public List<Map<String, Object>> getRemoteAccount(){
        String sql ="select * from account";
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sql);
        return maps;
    }
}

啟動項目,分別訪問兩個接口查詢不同的數據源

http://localhost:8080/selectTest的訪問數據:

http://localhost:8080/selectRemote的訪問數據

結語

以上為springboot實現druid配置查詢的demo,并且演示了如何實現多數據源配置動態(tài)切換的代碼實現,注意多數據源配置的時候url的配置為jdbc-url

到此這篇關于springboot整合druid及多數據源配置的文章就介紹到這了,更多相關springboot整合druid內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

  • SpringBoot結合Knife4j進行API分組授權管理配置詳解

    SpringBoot結合Knife4j進行API分組授權管理配置詳解

    在現代的微服務架構中,API 文檔和授權管理是不可或缺的一部分,本文將介紹如何在 Spring Boot 應用中集成 Knife4j,并進行 API 分組和授權管理配置,感興趣的小伙伴可以了解下
    2025-08-08
  • Java中SimpleDateFormat方法超詳細分析

    Java中SimpleDateFormat方法超詳細分析

    這篇文章主要給大家介紹了關于Java中SimpleDateFormat方法超詳細分析的相關資料,SimpleDateFormat 是一個以國別敏感的方式格式化和分析數據的具體類,文中通過代碼介紹的非常詳細,需要的朋友可以參考下
    2023-08-08
  • SSH框架網上商城項目第21戰(zhàn)之詳解易寶支付的流程

    SSH框架網上商城項目第21戰(zhàn)之詳解易寶支付的流程

    這篇文章主要為大家詳細介紹了SSH框架網上商城項目第21戰(zhàn)之易寶支付的流程,感興趣的小伙伴們可以參考一下
    2016-06-06
  • java中文分詞之正向最大匹配法實例代碼

    java中文分詞之正向最大匹配法實例代碼

    中文分詞應用很廣泛,網上也有很多開源項目,下面這篇文章主要給大家介紹了關于java中文分詞之正向最大匹配法的相關資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考借鑒,下面隨著小編來一起學習學習吧。
    2017-11-11
  • java 實現取int型的第二個字節(jié)的數

    java 實現取int型的第二個字節(jié)的數

    這篇文章主要介紹了java 實現取int型的第二個字節(jié)的數,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-01-01
  • mybatis 一對多嵌套查詢的實現

    mybatis 一對多嵌套查詢的實現

    本文主要介紹了mybatis 一對多嵌套查詢的實現,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-07-07
  • Springboot文件上傳出現找不到指定系統(tǒng)路徑的解決

    Springboot文件上傳出現找不到指定系統(tǒng)路徑的解決

    這篇文章主要介紹了Springboot文件上傳出現找不到指定系統(tǒng)路徑的解決方案,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Java自旋鎖的實現示例

    Java自旋鎖的實現示例

    自旋鎖是一種特殊的鎖,用于解決多線程同步問題,本文主要介紹了Java自旋鎖的實現示例,具有一定的參考價值,感興趣的可以了解一下
    2024-02-02
  • IDEA使用SpringAssistant插件創(chuàng)建SpringCloud項目

    IDEA使用SpringAssistant插件創(chuàng)建SpringCloud項目

    IDEA 功能強大,可以用來高效的開發(fā)應該程序。它還支持第三方插件、用戶可以根據需要添加自己喜歡的插件。下面介紹如何使用 IDEA 創(chuàng)建 Spring Cloud 項目
    2021-06-06
  • MyBatis入門學習教程-MyBatis快速入門

    MyBatis入門學習教程-MyBatis快速入門

    MyBatis是一個支持普通SQL查詢,存儲過程和高級映射的優(yōu)秀持久層框架,這篇文章主要給大家分享MyBatis的一篇快速入門教程
    2021-06-06

最新評論

墨竹工卡县| 怀宁县| 奎屯市| 洛宁县| 海兴县| 长岭县| 锦屏县| 尼玛县| 蓝田县| 罗江县| 黔西| 文成县| 即墨市| 胶州市| 左贡县| 四会市| 平江县| 河东区| 九龙坡区| 德江县| 三江| 石门县| 钦州市| 盐山县| 明溪县| 德格县| 新民市| 临清市| 犍为县| 昌都县| 新营市| 繁昌县| 汉源县| 莱州市| 星子县| 和林格尔县| 容城县| 瓮安县| 渝中区| 桃园县| 赤城县|