欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

前言

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

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

配置數(shù)據(jù)庫需要的配置文件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的啟動配置類,加載數(shù)據(jù)庫信息,和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實現(xiàn)數(shù)據(jù)庫操作
     * @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多數(shù)據(jù)源的配置使用

修改application.yml文件

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

編寫多數(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ù)據(jù)源:

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

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

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

package com.czing.jdbcdemo.mult; 
public class DynamicDataSourceContextHolder {
    /**
     * 使用ThreadLocal維護變量,ThreadLocal為每個使用該變量的線程提供獨立的變量副本,
     *  所以每一個線程都可以獨立地改變自己的副本,而不會影響其它線程所對應的副本。
     */
    private static final ThreadLocal<String> CONTEXT_HOLDER = new ThreadLocal<>();
    /**
     * 設置數(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ù)源信息加載的實現(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)用時用來將targetDataSources的屬性寫入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ù)源的配置啟動類,注入數(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);
    }
}

自定義注解

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攔截類的實現(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測試類的編寫驗證

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

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

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

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

結語

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

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

相關文章

  • Servlet系列兩種創(chuàng)建方式

    Servlet系列兩種創(chuàng)建方式

    本文主要介紹了Servlet系列兩種創(chuàng)建方式,包含Servlet2.5之前使用和Servlet3.0后,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2024-02-02
  • 詳解Java無需解壓直接讀取Zip文件和文件內(nèi)容

    詳解Java無需解壓直接讀取Zip文件和文件內(nèi)容

    本篇文章主要介紹了詳解Java無需解壓直接讀取Zip文件和文件內(nèi)容,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2017-10-10
  • java對象和json的來回轉換知識點總結

    java對象和json的來回轉換知識點總結

    在本篇文章里小編給大家分享了一篇關于java對象和json的來回轉換知識點總結內(nèi)容,有興趣的朋友們可以學習下。
    2021-01-01
  • Spring 實現(xiàn)excel及pdf導出表格示例

    Spring 實現(xiàn)excel及pdf導出表格示例

    本篇文章主要介紹了Spring 實現(xiàn)excel及pdf導出表格示例,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧
    2017-03-03
  • mybatis通過XML的方式拼接動態(tài)sql

    mybatis通過XML的方式拼接動態(tài)sql

    動態(tài)SQL是一種在運行時構造和執(zhí)行SQL語句的技術,這篇文章主要為大家介紹了mybatis如何通過XML的方式拼接動態(tài)sql,有需要的小伙伴可以參考一下
    2024-12-12
  • Kotlin 基礎教程之異常

    Kotlin 基礎教程之異常

    這篇文章主要介紹了Kotlin 基礎教程之異常的相關資料,需要的朋友可以參考下
    2017-06-06
  • swagger2和knife4j的詳細使用教程(入門級)

    swagger2和knife4j的詳細使用教程(入門級)

    最近項目中用到了Swagger2和knife4j作為接口文檔,所以下面這篇文章主要給大家介紹了關于swagger2和knife4j的詳細使用教程,文中通過實例代碼介紹的非常詳細,需要的朋友可以參考下
    2022-09-09
  • 關于@RequestParam的使用所遇到的404問題

    關于@RequestParam的使用所遇到的404問題

    這篇文章主要介紹了關于@RequestParam的使用所遇到的404問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2021-08-08
  • Java中如何自定義一個類加載器

    Java中如何自定義一個類加載器

    這篇文章主要介紹了Java中如何自定義一個類加載器,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教
    2022-11-11
  • SpringBoot集成thymeleaf渲染html模板的步驟詳解

    SpringBoot集成thymeleaf渲染html模板的步驟詳解

    這篇文章主要給大家詳細介紹了SpringBoot集成thymeleaf如何使實現(xiàn)html模板的渲染,文中有詳細的代碼示例,具有一定的參考價值,需要的朋友可以參考下
    2023-06-06

最新評論