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

springboot整合druid及多數(shù)據(jù)源配置的demo

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

前言

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

一、springboot整合druid的演示demo

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

主要用到的依賴如下:

<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>

配置數(shù)據(jù)庫(kù)需要的配置文件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)計(jì)攔截的filters,stat:監(jiān)控統(tǒng)計(jì)、log4j:日志記錄、wall:防御sql注入
     #如果允許時(shí)報(bào)錯(cuò)  java.lang.ClassNotFoundException: org.apache.log4j.Priority
 #則導(dǎo)入 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

編寫(xiě)durid的啟動(dòng)配置類,加載數(shù)據(jù)庫(kù)信息,和druid監(jiān)控頁(yè)面的初始化工作

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)控管理臺(tái)的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");
        //后臺(tái)允許誰(shuí)可以訪問(wèn)
        //initParams.put("allow", "localhost"):表示只有本機(jī)可以訪問(wèn)
        //initParams.put("allow", ""):為空或者為null時(shí),表示允許所有訪問(wèn)
        initParams.put("allow","");
        //deny:Druid 后臺(tái)拒絕誰(shuí)訪問(wèn)
        //initParams.put("msb", "192.168.1.20");表示禁止此ip訪問(wèn)
        servletRegistrationBean.setInitParameters(initParams);
        return servletRegistrationBean;
    }
    @Bean
    public FilterRegistrationBean webStatFilter() {
        FilterRegistrationBean bean = new FilterRegistrationBean();
        bean.setFilter(new WebStatFilter());
        //exclusions:設(shè)置哪些請(qǐng)求進(jìn)行過(guò)濾排除掉,從而不進(jìn)行統(tǒng)計(jì)
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions", "*.js,*.css,/druid/*");
        bean.setInitParameters(initParams);
        //"/*" 表示過(guò)濾所有請(qǐng)求
        bean.setUrlPatterns(Arrays.asList("/*"));
        return bean;
    }
}

編寫(xiě)controller類進(jìn)行測(cè)試(此處使用jdbcTemplate進(jìn)行演示)

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實(shí)現(xiàn)數(shù)據(jù)庫(kù)操作
     * @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;
    }
}

啟動(dòng)項(xiàng)目,演示效果

項(xiàng)目啟動(dòng)日志:

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

二、druid多數(shù)據(jù)源的配置使用

修改application.yml文件

spring:
  datasource:
    local:
      username: root
      password: root
      #注意多數(shù)據(jù)源配置的時(shí)候此處為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

編寫(xiě)多數(shù)據(jù)源的配置類:

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);
    }
}

使用自定義注解,在查詢方法的時(shí)候指定對(duì)應(yīng)的數(shù)據(jù)源:

編寫(xiě)枚舉類,用于指定數(shù)據(jù)源

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

數(shù)據(jù)源切換的處理類

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

數(shù)據(jù)源信息加載的實(shí)現(xiàn)

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()方法調(diào)用時(shí)用來(lái)將targetDataSources的屬性寫(xiě)入resolvedDataSources中的
        super.afterPropertiesSet();
    } 
    /**
     * @Author wangchengzhi
     * @Description
     * 根據(jù)Key獲取數(shù)據(jù)源的信息
     * @Date 23:06 2023/5/10
     * @Param
     * @return
     **/
    @Override
    protected Object determineCurrentLookupKey() {
        return DynamicDataSourceContextHolder.getDataSourceType();
    }
}

多數(shù)據(jù)源的配置啟動(dòng)類,注入數(shù)據(jù)庫(kù)配置信息

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 {
    /**
     * 切換數(shù)據(jù)源名稱
     */
    DataSourceType value() default DataSourceType.REMOTE;
}

AOP攔截類的實(shí)現(xiàn)

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 {
            // 銷毀數(shù)據(jù)源 在執(zhí)行方法之后
            DynamicDataSourceContextHolder.clearDataSourceType();
        }
    }
}

controller測(cè)試類的編寫(xiě)驗(yàn)證

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實(shí)現(xiàn)數(shù)據(jù)庫(kù)操作
     * @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實(shí)現(xiàn)數(shù)據(jù)庫(kù)操作
     * @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;
    }
}

啟動(dòng)項(xiàng)目,分別訪問(wèn)兩個(gè)接口查詢不同的數(shù)據(jù)源

http://localhost:8080/selectTest的訪問(wèn)數(shù)據(jù):

http://localhost:8080/selectRemote的訪問(wèn)數(shù)據(jù)

結(jié)語(yǔ)

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

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

相關(guān)文章

  • SpringBoot結(jié)合Knife4j進(jìn)行API分組授權(quán)管理配置詳解

    SpringBoot結(jié)合Knife4j進(jìn)行API分組授權(quán)管理配置詳解

    在現(xiàn)代的微服務(wù)架構(gòu)中,API 文檔和授權(quán)管理是不可或缺的一部分,本文將介紹如何在 Spring Boot 應(yīng)用中集成 Knife4j,并進(jìn)行 API 分組和授權(quán)管理配置,感興趣的小伙伴可以了解下
    2025-08-08
  • Java中SimpleDateFormat方法超詳細(xì)分析

    Java中SimpleDateFormat方法超詳細(xì)分析

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

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

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

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

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

    java 實(shí)現(xiàn)取int型的第二個(gè)字節(jié)的數(shù)

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

    mybatis 一對(duì)多嵌套查詢的實(shí)現(xiàn)

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

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

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

    Java自旋鎖的實(shí)現(xiàn)示例

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

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

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

    MyBatis入門(mén)學(xué)習(xí)教程-MyBatis快速入門(mén)

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

最新評(píng)論

达拉特旗| 澄江县| 新和县| 同仁县| 含山县| 阿拉善左旗| 盘锦市| 鹤庆县| 凤山市| 博客| 玉龙| 游戏| 佳木斯市| 辽宁省| 沧源| 韩城市| 贡觉县| 西畴县| 汉源县| 象州县| 沿河| 通许县| 金山区| 沧州市| 合肥市| 泰州市| 奉新县| 冀州市| 大庆市| 那曲县| 德令哈市| 塘沽区| 乐清市| 马山县| 息烽县| 永靖县| 新津县| 泰兴市| 青铜峡市| 西宁市| 旬邑县|