1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > springboot整合JDBC+Druid

springboot整合JDBC+Druid

时间:2023-12-01 08:38:52

相关推荐

springboot整合JDBC+Druid

一、整合JDBC

第一步:创建springboot项目

创建springboot项目时勾选如图所示依赖。

第二步:配置连接

这里使用的是ymal配置文件。

配置代码:

spring:datasource:username: rootpassword: '000000'url: jdbc:mysql://127.0.0.1:3306/testjdbc?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8driver-class-name: com.mysql.cj.jdbc.Driver

注意使用的mysql驱动是8.0.0以上版本的,springboot2.4版本中password中密码要加单引号。

第三步:测试连接

创建一个控制器并且写一个查询所有数据并将查询的数据直接输出到页面上。

@RestControllerpublic class JDBCController {@Autowiredprivate JdbcTemplate jdbcTemplate;@GetMapping("/list")public List<Map<String,Object>> getAll(){String sql = "select * from tb_user";List<Map<String, Object>> list_map = jdbcTemplate.queryForList(sql);return list_map;}}

启动项目访问http://localhost:8080/list,数据成功展示,表示整合JDBC成功。

二、整合Druid

第一步:添加ymal配置

整合JDBC默认的是Hikari是目前速度最快的数据源,在整合了JDBC的配置文件中,指定Druid数据源。

spring:datasource:username: rootpassword: '000000'url: jdbc:mysql://127.0.0.1:3306/testjdbc?serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8driver-class-name: com.mysql.cj.jdbc.Driver# 指定数据类型type: com.alibaba.druid.pool.DruidDataSource# 数据源其他配置initialSize: 5minIdle: 5maxActive: 20maxWait: 60000timeBetweenEvictionRunsMillis: 60000minEvictableIdleTimeMillis: 300000validationQuery: SELECT 1 FROM DUALtestWhileIdle: truetestOnBorrow: falsetestOnReturn: falsepoolPreparedStatements: true# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙filters: stat,wall,LogmaxPoolPreparedStatementPerConnectionSize: 20useGlobalDataSourceStat: trueconnectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

第二步:导入Druid依赖与log4j的依赖

<dependency><groupId>com.alibaba</groupId><artifactId>druid</artifactId><version>1.0.9</version></dependency><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>1.2.17</version></dependency>

第三步:自己配置Druid

@Configurationpublic class DruidConfig {@ConfigurationProperties(prefix = "spring.datasource")@Beanpublic DataSource druidDataSource(){return new DruidDataSource();}//后台监控 web.xml@Beanpublic ServletRegistrationBean statViewServlet(){ServletRegistrationBean<StatViewServlet> bean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");//后台需要有人监控、账号密码配置HashMap<String,String> map = new HashMap<>();map.put("loginUsername","admin");map.put("loginPassword","000000");//允许谁可以访问map.put("allow","");bean.setInitParameters(map);return bean;}}

第四步:启动项目测试

访问:http://localhost:8080/druid,显示如下登录页面。

输入配置文件DruidConfig中自己配置的账号密码登录。

登录成功进入日志监控首页

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。