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

一、在配置连接数据源连接池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整体演示截图与代码,如果各位有好的想法与建议,还清大家在下面评论,本人非常愿意进行测试,会将测试结果反馈给各位。






















 

转载于:https://my.oschina.net/u/1041709/blog/897811

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 集成 Sharding-JDBC 可以通过以下步骤完成: 1. 添加相关依赖:首先,在项目的 `pom.xml` 文件添加 Sharding-JDBC 的依赖。例如,可以添加如下依赖: ```xml <dependencies> <!-- Sharding-JDBC --> <dependency> <groupId>io.shardingjdbc</groupId> <artifactId>sharding-jdbc-spring-boot-starter</artifactId> <version>最新版本</version> </dependency> <!-- 数据库驱动 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>最新版本</version> </dependency> </dependencies> ``` 2. 配置数据源:在项目的配置文件(例如 `application.yml` 或 `application.properties`),配置数据源的连接信息。可以配置主库和从库的数据源。例如: ```yaml spring: sharding: jdbc: datasource: names: ds-master, ds-slave1, ds-slave2 ds-master: url: jdbc:mysql://localhost:3306/db_master?useSSL=false&characterEncoding=utf8 username: root password: password driver-class-name: com.mysql.jdbc.Driver ds-slave1: url: jdbc:mysql://localhost:3306/db_slave1?useSSL=false&characterEncoding=utf8 username: root password: password driver-class-name: com.mysql.jdbc.Driver ds-slave2: url: jdbc:mysql://localhost:3306/db_slave2?useSSL=false&characterEncoding=utf8 username: root password: password driver-class-name: com.mysql.jdbc.Driver ``` 3. 配置 Sharding-JDBC:在项目的配置类,使用 `@Configuration` 注解标记该类为配置类,并使用 `@EnableConfigurationProperties` 注解引入 Sharding-JDBC 的配置属性。然后,通过 `ShardingRuleConfiguration` 配置数据分片规则,例如指定分片策略、分片键等信息。最后,通过 `ShardingDataSource` 创建数据源,并将其注入到 Spring 容器。例如: ```java @Configuration @EnableConfigurationProperties(ShardingProperties.class) public class ShardingJdbcConfig { @Autowired private ShardingProperties shardingProperties; @Bean public DataSource dataSource() throws SQLException { ShardingRuleConfiguration shardingRuleConfig = new ShardingRuleConfiguration(); // 配置分片表规则 TableRuleConfiguration tableRuleConfig = new TableRuleConfiguration(); tableRuleConfig.setLogicTable("your_table"); tableRuleConfig.setActualDataNodes("ds-master.your_table_${0..1}, ds-slave.your_table_${0..1}"); // 配置分片算法 InlineShardingStrategyConfiguration shardingStrategyConfig = new InlineShardingStrategyConfiguration(); shardingStrategyConfig.setShardingColumn("id"); shardingStrategyConfig.setAlgorithmExpression("your_table_${id % 2}"); tableRuleConfig.setTableShardingStrategyConfig(shardingStrategyConfig); shardingRuleConfig.getTableRuleConfigs().add(tableRuleConfig); // 创建 ShardingDataSource return ShardingDataSourceFactory.createDataSource( shardingProperties.getDataSourceMap(), shardingRuleConfig, new Properties() ); } } ``` 4. 使用 Sharding-JDBC:在 Service 或 Repository 类,使用 `@Autowired` 注解注入数据源,并使用 SQL 操作数据库。Sharding-JDBC 会根据配置的分片规则自动将数据分发到对应的数据源上。例如: ```java @Service public class UserService { @Autowired private DataSource dataSource; public List<User> getUsers() { // 使用 dataSource 执行查询操作 // ... } public void addUser(User user) { // 使用 dataSource 执行插入操作 // ... } // 其他方法... } ``` 以上就是在 Spring Boot 集成 Sharding-JDBC 的步骤。配置完成后,你可以在需要使用数据库的地方注入数据源并进行数据库操作。请注意,以上示例是基于 Sharding-JDBC 4.x 版本的,如果你使用的是其他版本,请相应调整配置方式。另外,示例的配置是基于 MySQL 数据库的,如果你使用的是其他数据库,请相应调整数据库驱动和连接信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值