Be serious about writing, not clickbait.
The article is available at Github.com/niumoo/Java… And program ape Alang’s blog, point attention, don’t get lost.
preface
As a Java developer, I believe that YOU are familiar with JDBC (Java Data Base Connectivity). JDBC is the basic content of Java. It provides a benchmark on which you can build more advanced tools and interfaces to enable database developers to write database applications. The Druid connection pool is used to monitor and extend the Druid database operations. Alibaba-Durid official manual click here.
1. Prepare the database
Mysql > springBoot; mysql > springBoot; mysql > springBoot;
CREATE TABLE `user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`age` int(11) DEFAULT NULL,
`birthday` datetime DEFAULT NULL,
`password` varchar(32) NOT NULL,
`skills` varchar(255) DEFAULT NULL,
`username` varchar(32) NOT NULL.PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8; # Add dataINSERT INTO `springboot`.`user`(`id`, `age`, `birthday`, `password`, `skills`, `username`) VALUES (1.17.'the 2019-01-12 21:02:30'.'123'.'Go'.'Darcy');
INSERT INTO `springboot`.`user`(`id`, `age`, `birthday`, `password`, `skills`, `username`) VALUES (3.23.'the 2019-01-01 00:11:22'.'456'.'Java'.'Chris');
Copy the code
2. Add dependencies
I’m going to create a new Springboot project. Add dependencies as follows.
<dependencies>
<! Spring JDBC operation Template -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<! -- SpringBoot Web Development -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<! Mysql > connect to mysql
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<! Druid data source -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
Copy the code
3. Configure data source information
A regular JDBC configuration does not require this much configuration, but here the Druid part is configured because the Druid connection pool is used. For those who do not understand automatic configuration, see the Spring Boot configuration file.
spring:
datasource:
username: root
password: 123
url: JDBC: mysql: / / 127.0.0.1:3306 / springboot? characterEncoding=utf-8&serverTimezone=GMT%2B8
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
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
# Configure the filters for monitoring statistics interception. After removing the filters, the MONITORING interface SQL cannot be counted. 'wall' is used for the firewall
filters: stat
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true; druid.stat.slowSqlMillis=500
Copy the code
Once configured, the configuration information cannot be bound to the Druid data source. You need to create a new configuration class to bind the data source to the configuration information.
/** * <p> * Druid data source configuration **@Author niujinpeng
* @Date2019/1/14 "* /
@Configuration
public class DruidConfig {
/** * Configure binding *@return* /
@Bean
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource druid(a) {
return newDruidDataSource(); }}Copy the code
Now that the data source is configured, write a test method to test whether the Druid connection pool works.
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringbootDataJdbcApplicationTests {
@Autowired
DataSource dataSource;
/** * Test JDBC data source *@throws SQLException
*/
@Test
public void contextLoads(a) throws SQLException { System.out.println(dataSource.getClass()); Connection connection = dataSource.getConnection(); System.out.println(connection); connection.close(); }}Copy the code
Run and see contextLoads output.
class com.alibaba.druid.pool.DruidDataSource Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'. The driver is automatically registered via the SPI and manual loading of the driver Class is generally unnecessary. 2019-02-27 14:14:56. 144 INFO 12860 - [the main] com. Alibaba. Druid. Pool. DruidDataSource: {dataSource-1} inited com.alibaba.druid.proxy.jdbc.ConnectionProxyImpl@3e104d4bCopy the code
Com.alibaba. Druid indicates that druid has taken effect.
4. Use the Spring JDBC
In traditional JDBC use, there is a lot of code to write, from constructing preparedStatements to annoying queries. Facing such a development pain point, Spring encapsulates Spring-JDBC. Let’s use the JdbcTemplate to easily manipulate the database. The detailed use of Spring-JDBC is not the focus of this article, but a brief demonstration of whether it works. Write controller, query a user information.
@RestController
public class JdbcController {
@Autowired
JdbcTemplate jdbcTemplate;
@ResponseBody
@GetMapping("/query")
public Map<String, Object> map(a) {
List<Map<String, Object>> list = jdbcTemplate.queryForList("select * FROM user");
return list.get(0); }}Copy the code
Start the Spring project and the request/Query interface responds normally.
{
"id": 1."age": 17."birthday": "The 2019-01-12 T13:02:30. 000 + 0000"."password": "123"."skills": "Go"."username": "Darcy"
}
Copy the code
You can see that Spring-JDBC has fetched the data information from the database.
5. Use Druid to monitor
It would be a waste to use the Druid connection pool without using the monitoring function. Configure SQL monitoring for Druid. Add the Servlet and Filter for configuring Druid to the DruidConfig config class written above.
/** * Druid's servlet *@return* /
@Bean
public ServletRegistrationBean statViewServlet(a) {
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet());
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername"."admin");
initParams.put("loginPassword"."123");
initParams.put("allow"."127.0.0.1");
bean.setInitParameters(initParams);
bean.setUrlMappings(Arrays.asList("/druid/*"));
return bean;
}
@Bean
public FilterRegistrationBean webStatFilter(a) {
FilterRegistrationBean<WebStatFilter> bean = new FilterRegistrationBean<>(new WebStatFilter());
HashMap<String, String> initParams = new HashMap<>();
initParams.put("exclusions"."/css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/ *"));
return bean;
}
Copy the code
The Druid access path is/Druid, the login user is admin, the login password is 123, and the IP address allowed to access is 127.0.0.1. The requests that do not need to be monitored are those that start with/CSS and/Druid.
Restart the project and access the tests/query
And then visit/durid
The login page.
After login, you can view the SQL monitoring information and URL monitoring information.Monitor the URL.
The article code has been uploaded to GitHub Spring Boot JDB.
After < >
Hello world 🙂
I am a lang, lang of the moon, a technical tool person who moves bricks every day. Personal website: www.wdbyte.com If you want to subscribe, you can follow the public account of “Procedural Ape Alang”, or the blog of procedural ape Alang, or add me on wechat (WN8398).
This article has also been compiled at GitHub.com/niumoo/Java… Welcome Star.