微服务,微架构[二]之springboot集成jdbc

  1. 云栖社区>
  2. 博客>
  3. 正文

微服务,微架构[二]之springboot集成jdbc

e生态 2017-05-09 20:28:00 浏览1678
展开阅读全文

一、在配置连接数据源连接池springboot支持多种方式C3P0,DruidDataSource,c3p0,proxool等等,Druid连接池是采用java编写,在国内使用比较多,同时也经历了很多项目的实战,所以本次演示采用Druid连接池来处理数据源的连接

二、在连接数据源中,一般我们会采用两种方式处理

         1、DataSource方式

         2、Jndi方式

         本文重点采用DataSource方式进行配置,完成本文实例,由于需要对数据操作,本文演示接口采用html方式进行增删改查页面操作


三、关键性:相关参数数据源配置说明

         #1.基础配置

         数据库连接池配置

         spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
         spring.datasource.url=jdbc:mysql://localhost:3306/boot
         spring.datasource.username=root
         spring.datasource.password=123456
         spring.datasource.driver-class-name=com.mysql.jdbc.Driver


         #2.扩展配置

         初始化连接数量

         spring.datasource.initialSize=5

         最小空闲连接数

         spring.datasource.minIdle=5

         最大空闲连接数

         spring.datasource.maxActive=20

         最大等待毫秒时间

         spring.datasource.maxWait=60000
         spring.datasource.timeBetweenEvictionRunsMillis=60000
         spring.datasource.minEvictableIdleTimeMillis=300000
         spring.datasource.validationQuery=SELECT 1 FROM DUAL
         spring.datasource.testWhileIdle=true
         spring.datasource.testOnBorrow=false
         spring.datasource.testOnReturn=false
         spring.datasource.poolPreparedStatements=true
         spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
         spring.datasource.filters=stat,wall,log4j

         spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000


四、服务器tomcat配置说明

         # tomcat端口号
         server.port=80

         # tomcat项目名称定义

         server.context-path=/eshengtai

五、java代码展示

        1、初始化脚本

DROP TABLE IF EXISTS `eshengtai`;
CREATE TABLE `eshengtai` (
  `id` int(11) NOT NULL,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
        2、java实体类

/**   
 * @Title: Demo.java 
 * @Package com.didispace.bean
 * Copyright: Copyright (c) 2015
 * @author: abc   
 * @date: 2017年1月16日 上午11:15:05 
 *
 */
package com.didispace.bean;

public class eshengtai {

	private Integer id;
	private String name;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	
}

3、service接口和实现类

package com.didispace.service;

import java.util.List;

import com.didispace.bean.eshengtai;

/**
 * @author e生态
 * @version 1.0.0
 * @date 16/3/17 下午7:04.
 * @blog http://blog.csdn.net/ysl_228
 */
public interface UserService {

    /**
     * 新增一个用户
     * @param name
     * @param age
     */
    void create(String name, Integer age);

    /**
     * 根据name删除一个用户高
     * @param name
     */
    void deleteByName(String name);

    /**
     * 获取用户总量
     */
    Integer getAllUsers();

    /**
     * 删除所有用户
     */
    void deleteAllUsers();
    
    /**
     * 获取所有数据
     * @Title: selectAll
     * @return
     *
     */
    public List<eshengtai> selectAll();


}

package com.didispace.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import com.didispace.bean.eshengtai;

/**
 * @author e生态
 * @version 1.0.0
 * @date 16/3/17 下午6:44.
 * @blog http://blog.csdn.net/ysl_228
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    public void create(String name, Integer id) {
        jdbcTemplate.update("insert into eshengtai(id, name) values(?, ?)", id , name);
    }

    @Override
    public void deleteByName(String name) {
        jdbcTemplate.update("delete from eshengtai where NAME = ?", name);
    }

    @Override
    public Integer getAllUsers() {
        return jdbcTemplate.queryForObject("select count(1) from eshengtai", Integer.class);
    }

    @Override
    public void deleteAllUsers() {
        jdbcTemplate.update("delete from eshengtai");
    }
    
    @Override
    public List<eshengtai> selectAll() {
        return jdbcTemplate.query("select id,name from eshengtai", new Object[]{}, new BeanPropertyRowMapper<eshengtai>(eshengtai.class));
    }
}


4、控制层代码结构

package com.didispace.web;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.didispace.bean.eshengtai;
import com.didispace.service.UserService;

/**
 *
 * @author e生态
 * @version 1.0.0
 * @blog http://blog.csdn.net/ysl_228
 *
 */
@Controller
public class HelloController {
	
	@Autowired
	private UserService userService;
	
	/**
	 * 添加数据
	 * @Title: add
	 * @param map
	 * @return
	 *
	 */
	@RequestMapping("/add")
	public String add(eshengtai demo ,ModelMap map){
		userService.create(demo.getName(), demo.getId());
		map.addAttribute("list",userService.selectAll());
		return "index";
	}
	
	@RequestMapping("/list")
	public String add(ModelMap map){
		map.addAttribute("list",userService.selectAll());
		return "index";
	}

    @RequestMapping("/")
    public String index(ModelMap map) {
        map.addAttribute("host", "http://blog.csdn.net/ysl_228");
        return "index";
    }

}

5、项目启动类

package com.didispace;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 *
 * @author e生态
 * @version 1.0.0
 * @blog http://blog.csdn.net/ysl_228
 *
 */
@SpringBootApplication
public class Application {

	public static void main(String[] args) {

		SpringApplication.run(Application.class, args);

	}

}

6、配置参数文件application.properties

#tomcat port , project Name
server.port=80
server.context-path=/eshengtai

#1.jdbc config
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/boot
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#2.extend config
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.filters=stat,wall,log4j
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000

7、静态pom.xml文件

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>spring-boot-properties</groupId>
	<artifactId>spring-boot-properties</artifactId>
	<version>0.0.1-SNAPSHOT</version>

	<parent>
		<groupId>org.springframework.boot</groupId>
		<artifactId>spring-boot-starter-parent</artifactId>
		<version>1.3.2.RELEASE</version>
		<relativePath /> <!-- lookup parent from repository -->
	</parent>

	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<java.version>1.8</java.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-test</artifactId>
			<scope>test</scope>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-web</artifactId>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-thymeleaf</artifactId>
		</dependency>

		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.21</version>
		</dependency>

		<dependency>
			<groupId>org.springframework.boot</groupId>
			<artifactId>spring-boot-starter-jdbc</artifactId>
		</dependency>

	</dependencies>

	<build>
		<plugins>
			<plugin>
				<groupId>org.springframework.boot</groupId>
				<artifactId>spring-boot-maven-plugin</artifactId>
			</plugin>
		</plugins>
	</build>



</project>

8、操作增、删、改、查页面代码

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8" />
    <title></title>
</head>
<body>
<h1 th:text="${host}">数据列表</h1>
<form action="http://localhost/boot/add" method="post">
	ID:<input type="text" name="id" />
	NAME:<input type="text" name="name" />
	
	<input type="submit"  value="提交" />
</form>
<hr/>
<div th:each="demo,iterStat : ${list}">
    <span th:text="${demo.id}">id</span>
    <span th:text="${demo.name}">name</span>
    <br/>
  </div>
</body>
</html>

项目结构及演示图





以上就是所有springboot集成jdbc整体演示截图与代码,如果各位有好的想法与建议,还清大家在下面评论,本人非常愿意进行测试,会将测试结果反馈给各位。






















 

网友评论

登录后评论
0/500
评论
e生态
+ 关注