- 資訊首頁(yè) > 開(kāi)發(fā)技術(shù) >
- SpringBoot整合JDBC、Druid數據源的示例代碼
主要的依賴(lài)包:
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency> <!--實(shí)現web頁(yè)面接口調用--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency>
application.yml用于連接jdbc數據庫操作數據源配置,這里是最簡(jiǎn)化的配置:
spring: datasource: username: root password: admin #假如時(shí)區報錯,增加時(shí)區配置serverTimezone=UTC,以及編碼配置 url: jdbc:mysql://localhost:3306/mybatis02_0322?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver
實(shí)際開(kāi)發(fā)過(guò)程中基本上會(huì )與Druid、C3P0整合,下面也給出了整合Druid數據源相關(guān)的配置,所以這里一并放上完整的application.yml配置:
spring: datasource: username: root password: admin #假如時(shí)區報錯,增加時(shí)區配置serverTimezone=UTC url: jdbc:mysql://localhost:3306/mybatis02_0322?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource #springboot 默認是不注入這些屬性值的,需要自己綁定 #druid 數據源專(zhuān)有配置 initialSize: 5 minIdle: 5 maxActive: 20 maxWait: 60000 timeBetweenEvictionRunsMillis: 60000 minEvictableIdleTimeMillis: 300000 validationQuery: SELECT 1 FROM DUAL testWhileIdle: true testOnBorrow: false testOnReturn: false poolPreparedStatements: true #配置監控統計攔截的filters,stat:監控統計、log4j:日志記錄、wall:防止sql注入 #如果允許時(shí)報錯:java.lang.ClassNotFoundException:org.apache.log4j.Priority #則導入 log4j 依賴(lài)即可,maven地址:https://mvnrepository.com/artifact/log4j/log4j filters: stat,wall,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
最后測試一下數據庫連接訪(fǎng)問(wèn)是否成功:
@SpringBootTest class SpringbootDataApplicationTests { @Autowired private DataSource dataSource; @Test void testConnection() throws SQLException { System.out.println(dataSource.getClass()); Connection connection = dataSource.getConnection(); System.out.println(connection); } }
打印成功,顯示獲取到了數據源信息:
1.3.界面訪(fǎng)問(wèn)接口測試
@RestController public class JDBCController { @Autowired private JdbcTemplate jdbcTemplate; @RequestMapping("/queryList") public List<Map<String, Object>> query() { String sql = "select * from user"; List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql); return queryForList; } @RequestMapping("/addUser") public String AddUser(){ String sql = "insert into mybatis02_0322.user(id, username, password) values(4, '李磊', '654321')"; int update = jdbcTemplate.update(sql); return "AddUser Ok"; } @RequestMapping("/update/{id}") public String update(@PathVariable("id") Integer id){ String sql = "update mybatis02_0322.user set username = ?, password = ? where id = " + id; Object[] objects = new Object[2]; objects[0] = "測試哈哈哈111"; objects[1] = "32321"; int update = jdbcTemplate.update(sql, objects); return "updateUser Ok"; } @RequestMapping("/delete/{id}") public String delete(@PathVariable("id") Integer id){ String sql = "delete from mybatis02_0322.user where id = " + id; int update = jdbcTemplate.update(sql); return "delete Ok"; } }
這里對應接口請求頁(yè)面進(jìn)行請求測試即可,后臺數據庫層面進(jìn)行驗證,比較簡(jiǎn)單,這里就不一一細說(shuō),對應可以去看我的源碼。
Druid是阿里巴巴開(kāi)源平臺上一個(gè)數據庫連接池實(shí)現,它結合了C3P0、DBCP、PROXOOL等DB池的優(yōu)秀實(shí)踐,同時(shí)加入了日志監控。
Druid可以很好地監控DB池連接和Sql的執行情況,是天生針對監控的DB連接池。
SpringBoot2.0以上默認使用Hikari數據源,可以說(shuō)HiKari和Druid都是當前Java Web上開(kāi)源的優(yōu)秀數據源。
對應pom.xml文件:
<!--整合alibaba druid數據源--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.2.3</version> </dependency> <!--導入log4j日志包--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency>
2.3.配置Druid并使用監控頁(yè)面
①編寫(xiě)DruidConfig類(lèi),啟用后臺監控功能Bean以及過(guò)濾器Bean:
@Configuration public class DruidConfig { @ConfigurationProperties(prefix = "spring.datasource") @Bean public DataSource druidDataSource(){ return new DruidDataSource(); } //后臺監控功能 @Bean public ServletRegistrationBean statViewServlet(){ ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*"); //后臺需要有人登陸,賬號密碼配置 HashMap<String, String> initParameters = new HashMap<>(); initParameters.put("loginUsername", "admin"); //登陸key,是固定的 loginUsername loginPassword initParameters.put("loginPassword", "123456"); //允許誰(shuí)可以訪(fǎng)問(wèn) initParameters.put("allow", ""); //禁止誰(shuí)可以訪(fǎng)問(wèn) initParameters.put("fengye", "192.168.1.10"); bean.setInitParameters(initParameters); //設置初始化參數 return bean; } //過(guò)濾器 @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean<Filter> bean = new FilterRegistrationBean<>(); bean.setFilter(new WebStatFilter()); HashMap<String, String> initParameters = new HashMap<>(); //這些不進(jìn)行統計 initParameters.put("exclusions", "*.js,*.css,/druid/*"); bean.setInitParameters(initParameters); return bean; } }
②啟動(dòng)頁(yè)面訪(fǎng)問(wèn)Druid并測試請求訪(fǎng)問(wèn)sql:
本博客寫(xiě)作參考文檔相關(guān):
https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#using-boot-starter
https://www.yuque.com/atguigu/springboot/aob431#wtNk1
Spring Boot 2 學(xué)習筆記(上):https://blog.csdn.net/u011863024/article/details/113667634
Spring Boot 2 學(xué)習筆記(下):
https://blog.csdn.net/u011863024/article/details/113667946
示例代碼已上傳至Github地址:
https://github.com/devyf/SpringBoot_Study
到此這篇關(guān)于SpringBoot整合JDBC、Druid數據源的文章就介紹到這了,更多相關(guān)SpringBoot整合JDBC、Druid數據源內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
免責聲明:本站發(fā)布的內容(圖片、視頻和文字)以原創(chuàng )、來(lái)自互聯(lián)網(wǎng)轉載和分享為主,文章觀(guān)點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權請聯(lián)系QQ:712375056 進(jìn)行舉報,并提供相關(guān)證據,一經(jīng)查實(shí),將立刻刪除涉嫌侵權內容。
Copyright ? 2009-2021 56dr.com. All Rights Reserved. 特網(wǎng)科技 特網(wǎng)云 版權所有 珠海市特網(wǎng)科技有限公司 粵ICP備16109289號
域名注冊服務(wù)機構:阿里云計算有限公司(萬(wàn)網(wǎng)) 域名服務(wù)機構:煙臺帝思普網(wǎng)絡(luò )科技有限公司(DNSPod) CDN服務(wù):阿里云計算有限公司 中國互聯(lián)網(wǎng)舉報中心 增值電信業(yè)務(wù)經(jīng)營(yíng)許可證B2
建議您使用Chrome、Firefox、Edge、IE10及以上版本和360等主流瀏覽器瀏覽本網(wǎng)站